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 | getsentry__sentry | src/sentry/snuba/entity_subscription.py | {
"start": 17606,
"end": 19743
} | class ____(BaseMetricsEntitySubscription):
query_type = SnubaQuery.Type.CRASH_RATE
dataset = Dataset.Metrics
metric_key: SessionMRI
def get_granularity(self) -> int:
# Both time_window and granularity are in seconds
# Time windows <= 1h -> Granularity 10s
# Time windows > 1h & <= 4h -> Granularity 60s
# Time windows > 4h and <= 24h -> Granularity 1 hour
# Time windows > 24h -> Granularity 1 day
if self.time_window <= 3600:
granularity = 10
elif self.time_window <= 4 * 3600:
granularity = 60
elif 4 * 3600 < self.time_window <= 24 * 3600:
granularity = 3600
else:
granularity = 24 * 3600
return granularity
def aggregate_query_results(
self, data: list[dict[str, Any]], alias: str | None = None
) -> list[dict[str, Any]]:
aggregated_results: list[dict[str, Any]]
if not data:
total_count = 0
crash_count = 0
else:
assert len(data) == 1
row = data[0]
total_count = row["count"]
crash_count = row["crashed"]
if total_count == 0:
metrics.incr(
"incidents.entity_subscription.metrics.aggregate_query_results.no_session_data"
)
crash_free_rate = None
else:
crash_free_rate = round((1 - crash_count / total_count) * 100, 3)
col_name = alias if alias else CRASH_RATE_ALERT_AGGREGATE_ALIAS
aggregated_results = [{col_name: crash_free_rate}]
return aggregated_results
def get_snql_extra_conditions(self) -> list[Condition]:
# If we don't use the metrics layer we need to filter by metric here. The metrics layer does this automatically.
if not self.use_metrics_layer:
return [
Condition(
Column("metric_id"),
Op.EQ,
resolve(UseCaseID.SESSIONS, self.org_id, self.metric_key.value),
)
]
return []
| BaseCrashRateMetricsEntitySubscription |
python | doocs__leetcode | solution/3100-3199/3109.Find the Index of Permutation/Solution.py | {
"start": 404,
"end": 837
} | class ____:
def getPermutationIndex(self, perm: List[int]) -> int:
mod = 10**9 + 7
ans, n = 0, len(perm)
tree = BinaryIndexedTree(n + 1)
f = [1] * n
for i in range(1, n):
f[i] = f[i - 1] * i % mod
for i, x in enumerate(perm):
cnt = x - 1 - tree.query(x)
ans += cnt * f[n - i - 1] % mod
tree.update(x, 1)
return ans % mod
| Solution |
python | django__django | tests/postgres_tests/test_ranges.py | {
"start": 988,
"end": 3301
} | class ____(PostgreSQLSimpleTestCase):
def test_get_field_display(self):
class Model(PostgreSQLModel):
field = pg_fields.IntegerRangeField(
choices=[
["1-50", [((1, 25), "1-25"), ([26, 50], "26-50")]],
((51, 100), "51-100"),
],
)
tests = (
((1, 25), "1-25"),
([26, 50], "26-50"),
((51, 100), "51-100"),
((1, 2), "(1, 2)"),
([1, 2], "[1, 2]"),
)
for value, display in tests:
with self.subTest(value=value, display=display):
instance = Model(field=value)
self.assertEqual(instance.get_field_display(), display)
def test_discrete_range_fields_unsupported_default_bounds(self):
discrete_range_types = [
pg_fields.BigIntegerRangeField,
pg_fields.IntegerRangeField,
pg_fields.DateRangeField,
]
for field_type in discrete_range_types:
msg = f"Cannot use 'default_bounds' with {field_type.__name__}."
with self.assertRaisesMessage(TypeError, msg):
field_type(choices=[((51, 100), "51-100")], default_bounds="[]")
def test_continuous_range_fields_default_bounds(self):
continuous_range_types = [
pg_fields.DecimalRangeField,
pg_fields.DateTimeRangeField,
]
for field_type in continuous_range_types:
field = field_type(choices=[((51, 100), "51-100")], default_bounds="[]")
self.assertEqual(field.default_bounds, "[]")
def test_invalid_default_bounds(self):
tests = [")]", ")[", "](", "])", "([", "[(", "x", "", None]
msg = "default_bounds must be one of '[)', '(]', '()', or '[]'."
for invalid_bounds in tests:
with self.assertRaisesMessage(ValueError, msg):
pg_fields.DecimalRangeField(default_bounds=invalid_bounds)
def test_deconstruct(self):
field = pg_fields.DecimalRangeField()
*_, kwargs = field.deconstruct()
self.assertEqual(kwargs, {})
field = pg_fields.DecimalRangeField(default_bounds="[]")
*_, kwargs = field.deconstruct()
self.assertEqual(kwargs, {"default_bounds": "[]"})
| BasicTests |
python | bokeh__bokeh | tests/unit/bokeh/embed/test_elements.py | {
"start": 1521,
"end": 1800
} | class ____:
def test_render(self) -> None:
render_item = RenderItem(docid=ID("doc123"), elementid=ID("foo123"))
assert bee.div_for_render_item(render_item).strip() == \
"""<div id="foo123" style="display: contents;"></div>"""
| Test_div_for_render_item |
python | keon__algorithms | algorithms/tree/bst/depth_sum.py | {
"start": 1137,
"end": 1615
} | class ____(unittest.TestCase):
def setUp(self):
self.tree = bst()
self.tree.insert(9)
self.tree.insert(6)
self.tree.insert(12)
self.tree.insert(3)
self.tree.insert(8)
self.tree.insert(10)
self.tree.insert(15)
self.tree.insert(7)
self.tree.insert(18)
def test_depth_sum(self):
self.assertEqual(253, depth_sum(self.tree.root, 4))
if __name__ == '__main__':
unittest.main()
| TestSuite |
python | pandas-dev__pandas | pandas/tests/indexes/numeric/test_setops.py | {
"start": 5152,
"end": 5968
} | class ____:
@pytest.mark.parametrize("slice_", [slice(None), slice(0)])
def test_union_sort_other_special(self, slice_):
# https://github.com/pandas-dev/pandas/issues/24959
idx = Index([1, 0, 2])
# default, sort=None
other = idx[slice_]
tm.assert_index_equal(idx.union(other), idx)
tm.assert_index_equal(other.union(idx), idx)
# sort=False
tm.assert_index_equal(idx.union(other, sort=False), idx)
@pytest.mark.parametrize("slice_", [slice(None), slice(0)])
def test_union_sort_special_true(self, slice_):
idx = Index([1, 0, 2])
# default, sort=None
other = idx[slice_]
result = idx.union(other, sort=True)
expected = Index([0, 1, 2])
tm.assert_index_equal(result, expected)
| TestSetOpsSort |
python | huggingface__transformers | tests/models/speecht5/test_modeling_speecht5.py | {
"start": 4959,
"end": 6922
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (SpeechT5Model,) if is_torch_available() else ()
pipeline_model_mapping = (
{"automatic-speech-recognition": SpeechT5ForSpeechToText, "feature-extraction": SpeechT5Model}
if is_torch_available()
else {}
)
is_encoder_decoder = True
test_resize_embeddings = False
def setUp(self):
self.model_tester = SpeechT5ModelTester(self)
self.config_tester = ConfigTester(self, config_class=SpeechT5Config, hidden_size=37)
def test_config(self):
self.config_tester.run_common_tests()
def test_model_forward(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model_forward(*config_and_inputs)
def test_forward_signature(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
signature = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
arg_names = [*signature.parameters.keys()]
expected_arg_names = [
"input_values",
"attention_mask",
"decoder_input_values",
"decoder_attention_mask",
]
expected_arg_names.extend(["encoder_outputs"])
self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names)
@unittest.skip(reason="Model has no input_embeds")
def test_inputs_embeds(self):
pass
@unittest.skip(reason="Model has no input_embeds")
def test_model_get_set_embeddings(self):
pass
@unittest.skip(reason="Decoder cannot keep gradients")
def test_retain_grad_hidden_states_attentions(self):
pass
@require_torch
| SpeechT5ModelTest |
python | vyperlang__vyper | vyper/builtins/functions.py | {
"start": 68098,
"end": 68168
} | class ____(_UnsafeMath):
_id = "unsafe_mul"
op = "mul"
| UnsafeMul |
python | ray-project__ray | python/ray/serve/_private/autoscaling_state.py | {
"start": 913,
"end": 26981
} | class ____:
"""Manages autoscaling for a single deployment."""
def __init__(self, deployment_id: DeploymentID):
self._deployment_id = deployment_id
# Map from handle ID to handle request metric report. Metrics
# are removed from this dict either when the actor on which the
# handle lived dies, or after a period of no updates.
self._handle_requests: Dict[str, HandleMetricReport] = dict()
# Map from replica ID to replica request metric report. Metrics
# are removed from this dict when a replica is stopped.
# Prometheus + Custom metrics from each replica are also included
self._replica_metrics: Dict[ReplicaID, ReplicaMetricReport] = dict()
self._deployment_info = None
self._config = None
self._policy: Optional[
Callable[[AutoscalingContext], Tuple[int, Optional[Dict[str, Any]]]]
] = None
# user defined policy returns a dictionary of state that is persisted between autoscaling decisions
# content of the dictionary is determined by the user defined policy
self._policy_state: Optional[Dict[str, Any]] = None
self._running_replicas: List[ReplicaID] = []
self._target_capacity: Optional[float] = None
self._target_capacity_direction: Optional[TargetCapacityDirection] = None
def register(self, info: DeploymentInfo, curr_target_num_replicas: int) -> int:
"""Registers an autoscaling deployment's info.
Returns the number of replicas the target should be set to.
"""
config = info.deployment_config.autoscaling_config
if config is None:
raise ValueError(
f"Autoscaling config is not set for deployment {self._deployment_id}"
)
if (
self._deployment_info is None or self._deployment_info.config_changed(info)
) and config.initial_replicas is not None:
target_num_replicas = config.initial_replicas
else:
target_num_replicas = curr_target_num_replicas
self._deployment_info = info
self._config = config
self._policy = self._config.policy.get_policy()
self._target_capacity = info.target_capacity
self._target_capacity_direction = info.target_capacity_direction
self._policy_state = {}
# Log when custom autoscaling policy is used for deployment
if not self._config.policy.is_default_policy_function():
logger.info(
f"Using custom autoscaling policy '{self._config.policy.policy_function}' "
f"for deployment '{self._deployment_id}'."
)
# Record telemetry for custom autoscaling policy usage
ServeUsageTag.CUSTOM_AUTOSCALING_POLICY_USED.record("1")
return self.apply_bounds(target_num_replicas)
def on_replica_stopped(self, replica_id: ReplicaID):
if replica_id in self._replica_metrics:
del self._replica_metrics[replica_id]
def get_num_replicas_lower_bound(self) -> int:
if self._config.initial_replicas is not None and (
self._target_capacity_direction == TargetCapacityDirection.UP
):
return get_capacity_adjusted_num_replicas(
self._config.initial_replicas,
self._target_capacity,
)
else:
return get_capacity_adjusted_num_replicas(
self._config.min_replicas,
self._target_capacity,
)
def get_num_replicas_upper_bound(self) -> int:
return get_capacity_adjusted_num_replicas(
self._config.max_replicas,
self._target_capacity,
)
def update_running_replica_ids(self, running_replicas: List[ReplicaID]):
"""Update cached set of running replica IDs for this deployment."""
self._running_replicas = running_replicas
def is_within_bounds(self, num_replicas_running_at_target_version: int):
"""Whether or not this deployment is within the autoscaling bounds.
Returns: True if the number of running replicas for the current
deployment version is within the autoscaling bounds. False
otherwise.
"""
return (
self.apply_bounds(num_replicas_running_at_target_version)
== num_replicas_running_at_target_version
)
def apply_bounds(self, num_replicas: int) -> int:
"""Clips a replica count with current autoscaling bounds.
This takes into account target capacity.
"""
return max(
self.get_num_replicas_lower_bound(),
min(self.get_num_replicas_upper_bound(), num_replicas),
)
def record_request_metrics_for_replica(
self, replica_metric_report: ReplicaMetricReport
) -> None:
"""Records average number of ongoing requests at a replica."""
replica_id = replica_metric_report.replica_id
send_timestamp = replica_metric_report.timestamp
if (
replica_id not in self._replica_metrics
or send_timestamp > self._replica_metrics[replica_id].timestamp
):
self._replica_metrics[replica_id] = replica_metric_report
def record_request_metrics_for_handle(
self,
handle_metric_report: HandleMetricReport,
) -> None:
"""Records average number of queued and running requests at a handle for this
deployment.
"""
handle_id = handle_metric_report.handle_id
send_timestamp = handle_metric_report.timestamp
if (
handle_id not in self._handle_requests
or send_timestamp > self._handle_requests[handle_id].timestamp
):
self._handle_requests[handle_id] = handle_metric_report
def drop_stale_handle_metrics(self, alive_serve_actor_ids: Set[str]) -> None:
"""Drops handle metrics that are no longer valid.
This includes handles that live on Serve Proxy or replica actors
that have died AND handles from which the controller hasn't
received an update for too long.
"""
timeout_s = max(
2 * self._config.metrics_interval_s,
RAY_SERVE_MIN_HANDLE_METRICS_TIMEOUT_S,
)
for handle_id, handle_metric in list(self._handle_requests.items()):
# Drop metrics for handles that are on Serve proxy/replica
# actors that have died
if (
handle_metric.is_serve_component_source
and handle_metric.actor_id is not None
and handle_metric.actor_id not in alive_serve_actor_ids
):
del self._handle_requests[handle_id]
if handle_metric.total_requests > 0:
logger.debug(
f"Dropping metrics for handle '{handle_id}' because the Serve "
f"actor it was on ({handle_metric.actor_id}) is no longer "
f"alive. It had {handle_metric.total_requests} ongoing requests"
)
# Drop metrics for handles that haven't sent an update in a while.
# This is expected behavior for handles that were on replicas or
# proxies that have been shut down.
elif time.time() - handle_metric.timestamp >= timeout_s:
del self._handle_requests[handle_id]
if handle_metric.total_requests > 0:
actor_id = handle_metric.actor_id
actor_info = f"on actor '{actor_id}' " if actor_id else ""
logger.info(
f"Dropping stale metrics for handle '{handle_id}' {actor_info}"
f"because no update was received for {timeout_s:.1f}s. "
f"Ongoing requests was: {handle_metric.total_requests}."
)
def get_decision_num_replicas(
self, curr_target_num_replicas: int, _skip_bound_check: bool = False
) -> int:
"""Decide the target number of replicas to autoscale to.
The decision is based off of the number of requests received
for this deployment. After the decision number of replicas is
returned by the policy, it is then bounded by the bounds min
and max adjusted by the target capacity and returned. If
`_skip_bound_check` is True, then the bounds are not applied.
"""
if self._policy is None:
raise ValueError(f"Policy is not set for deployment {self._deployment_id}.")
autoscaling_context = self.get_autoscaling_context(curr_target_num_replicas)
decision_num_replicas, self._policy_state = self._policy(autoscaling_context)
if _skip_bound_check:
return decision_num_replicas
return self.apply_bounds(decision_num_replicas)
def get_autoscaling_context(self, curr_target_num_replicas) -> AutoscalingContext:
return AutoscalingContext(
deployment_id=self._deployment_id,
deployment_name=self._deployment_id.name,
app_name=self._deployment_id.app_name,
current_num_replicas=len(self._running_replicas),
target_num_replicas=curr_target_num_replicas,
running_replicas=self._running_replicas,
total_num_requests=self.get_total_num_requests,
capacity_adjusted_min_replicas=self.get_num_replicas_lower_bound(),
capacity_adjusted_max_replicas=self.get_num_replicas_upper_bound(),
policy_state=(
self._policy_state.copy() if self._policy_state is not None else {}
),
current_time=time.time(),
config=self._config,
total_queued_requests=self._get_queued_requests,
aggregated_metrics=self._get_aggregated_custom_metrics,
raw_metrics=self._get_raw_custom_metrics,
last_scale_up_time=None,
last_scale_down_time=None,
)
def _collect_replica_running_requests(self) -> List[TimeSeries]:
"""Collect running requests timeseries from replicas for aggregation.
Returns:
List of timeseries data.
"""
timeseries_list = []
for replica_id in self._running_replicas:
replica_metric_report = self._replica_metrics.get(replica_id, None)
if (
replica_metric_report is not None
and RUNNING_REQUESTS_KEY in replica_metric_report.metrics
):
timeseries_list.append(
replica_metric_report.metrics[RUNNING_REQUESTS_KEY]
)
return timeseries_list
def _collect_handle_queued_requests(self) -> List[TimeSeries]:
"""Collect queued requests timeseries from all handles.
Returns:
List of timeseries data.
"""
timeseries_list = []
for handle_metric_report in self._handle_requests.values():
timeseries_list.append(handle_metric_report.queued_requests)
return timeseries_list
def _collect_handle_running_requests(self) -> List[TimeSeries]:
"""Collect running requests timeseries from handles when not collected on replicas.
Returns:
List of timeseries data.
Example:
If there are 2 handles, each managing 2 replicas, and the running requests metrics are:
- Handle 1: Replica 1: 5, Replica 2: 7
- Handle 2: Replica 1: 3, Replica 2: 1
and the timestamp is 0.1 and 0.2 respectively
Then the returned list will be:
[
[TimeStampedValue(timestamp=0.1, value=5.0)],
[TimeStampedValue(timestamp=0.2, value=7.0)],
[TimeStampedValue(timestamp=0.1, value=3.0)],
[TimeStampedValue(timestamp=0.2, value=1.0)]
]
"""
timeseries_list = []
for handle_metric in self._handle_requests.values():
for replica_id in self._running_replicas:
if (
RUNNING_REQUESTS_KEY not in handle_metric.metrics
or replica_id not in handle_metric.metrics[RUNNING_REQUESTS_KEY]
):
continue
timeseries_list.append(
handle_metric.metrics[RUNNING_REQUESTS_KEY][replica_id]
)
return timeseries_list
def _merge_and_aggregate_timeseries(
self,
timeseries_list: List[TimeSeries],
) -> float:
"""Aggregate and average a metric from timeseries data using instantaneous merge.
Args:
timeseries_list: A list of TimeSeries (TimeSeries), where each
TimeSeries represents measurements from a single source (replica, handle, etc.).
Each list is sorted by timestamp ascending.
Returns:
The time-weighted average of the metric
Example:
If the timeseries_list is:
[
[
TimeStampedValue(timestamp=0.1, value=5.0),
TimeStampedValue(timestamp=0.2, value=7.0),
],
[
TimeStampedValue(timestamp=0.2, value=3.0),
TimeStampedValue(timestamp=0.3, value=1.0),
]
]
Then the returned value will be:
(5.0*0.1 + 7.0*0.2 + 3.0*0.2 + 1.0*0.3) / (0.1 + 0.2 + 0.2 + 0.3) = 4.5 / 0.8 = 5.625
"""
if not timeseries_list:
return 0.0
# Use instantaneous merge approach - no arbitrary windowing needed
merged_timeseries = merge_instantaneous_total(timeseries_list)
if merged_timeseries:
# assume that the last recorded metric is valid for last_window_s seconds
last_metric_time = merged_timeseries[-1].timestamp
# we dont want to make any assumption about how long the last metric will be valid
# only conclude that the last metric is valid for last_window_s seconds that is the
# difference between the current time and the last metric recorded time
last_window_s = time.time() - last_metric_time
# adding a check to negative values caused by clock skew
# between replicas and controller. Also add a small epsilon to avoid division by zero
if last_window_s <= 0:
last_window_s = 1e-3
# Calculate the aggregated metric value
value = aggregate_timeseries(
merged_timeseries,
aggregation_function=self._config.aggregation_function,
last_window_s=last_window_s,
)
return value if value is not None else 0.0
return 0.0
def _calculate_total_requests_aggregate_mode(self) -> float:
"""Calculate total requests using aggregate metrics mode with timeseries data.
This method works with raw timeseries metrics data and performs aggregation
at the controller level, providing more accurate and stable metrics compared
to simple mode.
Processing Steps:
1. Collect raw timeseries data (eg: running request) from replicas (if available)
2. Collect queued requests from handles (always tracked at handle level)
3. Collect raw timeseries data (eg: running request) from handles (if not available from replicas)
4. Merge timeseries using instantaneous approach for mathematically correct totals
5. Calculate time-weighted average running requests from the merged timeseries
Key Differences from Simple Mode:
- Uses raw timeseries data instead of pre-aggregated metrics
- Performs instantaneous merging for exact gauge semantics
- Aggregates at the controller level rather than using pre-computed averages
- Uses time-weighted averaging over the look_back_period_s interval for accurate calculations
Metrics Collection:
Running requests are collected with either replica-level or handle-level metrics.
Queued requests are always collected from handles regardless of where
running requests are collected.
Timeseries Aggregation:
Raw timeseries data from multiple sources is merged using an instantaneous
approach that treats gauges as right-continuous step functions. This provides
mathematically correct totals without arbitrary windowing bias.
Example with Numbers:
Assume metrics_interval_s = 0.5s, current time = 2.0s
Step 1: Collect raw timeseries from 2 replicas (r1, r2)
replica_metrics = [
{"running_requests": [(t=0.2, val=5), (t=0.8, val=7), (t=1.5, val=6)]}, # r1
{"running_requests": [(t=0.1, val=3), (t=0.9, val=4), (t=1.4, val=8)]} # r2
]
Step 2: Collect queued requests from handles
handle_queued = 2 + 3 = 5 # total from all handles
Step 3: No handle metrics needed (replica metrics available)
handle_metrics = []
Step 4: Merge timeseries using instantaneous approach
# Create delta events: r1 starts at 5 (t=0.2), changes to 7 (t=0.8), then 6 (t=1.5)
# r2 starts at 3 (t=0.1), changes to 4 (t=0.9), then 8 (t=1.4)
# Merged instantaneous total: [(t=0.1, val=3), (t=0.2, val=8), (t=0.8, val=10), (t=0.9, val=11), (t=1.4, val=15), (t=1.5, val=14)]
merged_timeseries = {"running_requests": [(0.1, 3), (0.2, 8), (0.8, 10), (0.9, 11), (1.4, 15), (1.5, 14)]}
Step 5: Calculate time-weighted average over full timeseries (t=0.1 to t=1.5+0.5=2.0)
# Time-weighted calculation: (3*0.1 + 8*0.6 + 10*0.1 + 11*0.5 + 15*0.1 + 14*0.5) / 2.0 = 10.05
avg_running = 10.05
Final result: total_requests = avg_running + queued = 10.05 + 5 = 15.05
Returns:
Total number of requests (average running + queued) calculated from
timeseries data aggregation.
"""
# Collect replica-based running requests (returns List[TimeSeries])
replica_timeseries = self._collect_replica_running_requests()
metrics_collected_on_replicas = len(replica_timeseries) > 0
# Collect queued requests from handles (returns List[TimeSeries])
queued_timeseries = self._collect_handle_queued_requests()
if not metrics_collected_on_replicas:
# Collect handle-based running requests if not collected on replicas
handle_timeseries = self._collect_handle_running_requests()
else:
handle_timeseries = []
# Collect all timeseries for ongoing requests
ongoing_requests_timeseries = []
# Add replica timeseries
ongoing_requests_timeseries.extend(replica_timeseries)
# Add handle timeseries if replica metrics weren't collected
if not metrics_collected_on_replicas:
ongoing_requests_timeseries.extend(handle_timeseries)
# Add queued timeseries
ongoing_requests_timeseries.extend(queued_timeseries)
# Aggregate and add running requests to total
ongoing_requests = self._merge_and_aggregate_timeseries(
ongoing_requests_timeseries
)
return ongoing_requests
def _calculate_total_requests_simple_mode(self) -> float:
"""Calculate total requests using simple aggregated metrics mode.
This method works with pre-aggregated metrics that are computed by averaging
(or other functions) over the past look_back_period_s seconds.
Metrics Collection:
Metrics can be collected at two levels:
1. Replica level: Each replica reports one aggregated metric value
2. Handle level: Each handle reports metrics for multiple replicas
Replica-Level Metrics Example:
For 3 replicas (r1, r2, r3), metrics might look like:
{
"r1": 10,
"r2": 20,
"r3": 30
}
Total requests = 10 + 20 + 30 = 60
Handle-Level Metrics Example:
For 3 handles (h1, h2, h3), each managing 2 replicas:
- h1 manages r1, r2
- h2 manages r2, r3
- h3 manages r3, r1
Metrics structure:
{
"h1": {"r1": 10, "r2": 20},
"h2": {"r2": 20, "r3": 30},
"h3": {"r3": 30, "r1": 10}
}
Total requests = 10 + 20 + 20 + 30 + 30 + 10 = 120
Note: We can safely sum all handle metrics because each unique request
is counted only once across all handles (no double-counting).
Queued Requests:
Queued request metrics are always tracked at the handle level, regardless
of whether running request metrics are collected at replicas or handles.
Returns:
Total number of requests (running + queued) across all replicas/handles.
"""
total_requests = 0
for id in self._running_replicas:
if id in self._replica_metrics:
total_requests += self._replica_metrics[id].aggregated_metrics.get(
RUNNING_REQUESTS_KEY, 0
)
metrics_collected_on_replicas = total_requests > 0
# Add handle metrics
for handle_metric in self._handle_requests.values():
total_requests += handle_metric.aggregated_queued_requests
# Add running requests from handles if not collected on replicas
if not metrics_collected_on_replicas:
for replica_id in self._running_replicas:
if replica_id in handle_metric.aggregated_metrics.get(
RUNNING_REQUESTS_KEY, {}
):
total_requests += handle_metric.aggregated_metrics.get(
RUNNING_REQUESTS_KEY
).get(replica_id)
return total_requests
def get_total_num_requests(self) -> float:
"""Get average total number of requests aggregated over the past
`look_back_period_s` number of seconds.
If there are 0 running replicas, then returns the total number
of requests queued at handles
This code assumes that the metrics are either emmited on handles
or on replicas, but not both. Its the responsibility of the writer
to ensure enclusivity of the metrics.
"""
if RAY_SERVE_AGGREGATE_METRICS_AT_CONTROLLER:
return self._calculate_total_requests_aggregate_mode()
else:
return self._calculate_total_requests_simple_mode()
def get_replica_metrics(self) -> Dict[ReplicaID, List[TimeSeries]]:
"""Get the raw replica metrics dict."""
metric_values = defaultdict(list)
for id in self._running_replicas:
if id in self._replica_metrics and self._replica_metrics[id].metrics:
for k, v in self._replica_metrics[id].metrics.items():
metric_values[k].append(v)
return metric_values
def _get_queued_requests(self) -> float:
"""Calculate the total number of queued requests across all handles.
Returns:
Sum of queued requests at all handles. Uses aggregated values in simple mode,
or aggregates timeseries data in aggregate mode.
"""
if RAY_SERVE_AGGREGATE_METRICS_AT_CONTROLLER:
# Aggregate mode: collect and aggregate timeseries
queued_timeseries = self._collect_handle_queued_requests()
if not queued_timeseries:
return 0.0
return self._merge_and_aggregate_timeseries(queued_timeseries)
else:
# Simple mode: sum pre-aggregated values
return sum(
handle_metric.aggregated_queued_requests
for handle_metric in self._handle_requests.values()
)
def _get_aggregated_custom_metrics(self) -> Dict[str, Dict[ReplicaID, float]]:
"""Aggregate custom metrics from replica metric reports.
This method aggregates raw timeseries data from replicas on the controller,
similar to how ongoing requests are aggregated.
Returns:
Dict mapping metric name to dict of replica ID to aggregated metric value.
"""
aggregated_metrics = defaultdict(dict)
for replica_id in self._running_replicas:
replica_metric_report = self._replica_metrics.get(replica_id)
if replica_metric_report is None:
continue
for metric_name, timeseries in replica_metric_report.metrics.items():
# Aggregate the timeseries for this custom metric
aggregated_value = self._merge_and_aggregate_timeseries([timeseries])
aggregated_metrics[metric_name][replica_id] = aggregated_value
return dict(aggregated_metrics)
def _get_raw_custom_metrics(
self,
) -> Dict[str, Dict[ReplicaID, TimeSeries]]:
"""Extract raw custom metric values from replica metric reports.
Returns:
Dict mapping metric name to dict of replica ID to raw metric timeseries.
"""
raw_metrics = defaultdict(dict)
for replica_id in self._running_replicas:
replica_metric_report = self._replica_metrics.get(replica_id)
if replica_metric_report is None:
continue
for metric_name, timeseries in replica_metric_report.metrics.items():
# Extract values from TimeStampedValue list
raw_metrics[metric_name][replica_id] = timeseries
return dict(raw_metrics)
| DeploymentAutoscalingState |
python | milvus-io__pymilvus | pymilvus/orm/schema.py | {
"start": 30420,
"end": 36522
} | class ____:
def __init__(
self,
name: str,
function_type: FunctionType,
input_field_names: Union[str, List[str]],
output_field_names: Optional[Union[str, List[str]]] = None,
description: str = "",
params: Optional[Dict] = None,
):
if not isinstance(name, str):
raise ParamError(
message=f"The name of the function should be a string, but got {type(name)}"
)
if not isinstance(description, str):
raise ParamError(
message=f"The description of the function should be a string, but got {type(description)}"
)
if not isinstance(input_field_names, (str, list)):
raise ParamError(
message=f"The input field names of the function should be a string or a list of strings, but got {type(input_field_names)}"
)
self._name = name
self._description = description
input_field_names = (
[input_field_names] if isinstance(input_field_names, str) else input_field_names
)
if output_field_names is None:
output_field_names = []
if not isinstance(output_field_names, (str, list)):
raise ParamError(
message=f"The output field names of the function should be a string or a list of strings, but got {type(output_field_names)}"
)
output_field_names = (
[output_field_names] if isinstance(output_field_names, str) else output_field_names
)
try:
self._type = FunctionType(function_type)
except ValueError as err:
raise ParamError(message=ExceptionsMessage.UnknownFunctionType) from err
for field_name in list(input_field_names) + list(output_field_names):
if not isinstance(field_name, str):
raise ParamError(message=ExceptionsMessage.FunctionIncorrectInputOutputType)
if len(input_field_names) != len(set(input_field_names)):
raise ParamError(message=ExceptionsMessage.FunctionDuplicateInputs)
if len(output_field_names) != len(set(output_field_names)):
raise ParamError(message=ExceptionsMessage.FunctionDuplicateOutputs)
if set(input_field_names) & set(output_field_names):
raise ParamError(message=ExceptionsMessage.FunctionCommonInputOutput)
self._input_field_names = input_field_names
self._output_field_names = output_field_names
self._params = params if params is not None else {}
if not isinstance(self._params, dict):
raise ParamError(message="The parameters of the function should be a dictionary.")
@property
def name(self):
return self._name
@property
def description(self):
return self._description
@property
def type(self):
return self._type
@property
def input_field_names(self):
return self._input_field_names
@property
def output_field_names(self):
return self._output_field_names
@property
def params(self):
return self._params
def _check_bm25_function(self, schema: CollectionSchema):
if len(self._input_field_names) != 1 or len(self._output_field_names) != 1:
raise ParamError(message=ExceptionsMessage.BM25FunctionIncorrectInputOutputCount)
for field in schema.fields:
if field.name == self._input_field_names[0] and field.dtype != DataType.VARCHAR:
raise ParamError(message=ExceptionsMessage.BM25FunctionIncorrectInputFieldType)
if (
field.name == self._output_field_names[0]
and field.dtype != DataType.SPARSE_FLOAT_VECTOR
):
raise ParamError(message=ExceptionsMessage.BM25FunctionIncorrectOutputFieldType)
def _check_text_embedding_function(self, schema: CollectionSchema):
if len(self._input_field_names) != 1 or len(self._output_field_names) != 1:
raise ParamError(
message=ExceptionsMessage.TextEmbeddingFunctionIncorrectInputOutputCount
)
for field in schema.fields:
if field.name == self._input_field_names[0] and field.dtype != DataType.VARCHAR:
raise ParamError(
message=ExceptionsMessage.TextEmbeddingFunctionIncorrectInputFieldType
)
if field.name == self._output_field_names[0] and field.dtype not in [
DataType.FLOAT_VECTOR,
DataType.INT8_VECTOR,
]:
raise ParamError(
message=ExceptionsMessage.TextEmbeddingFunctionIncorrectOutputFieldType
)
def verify(self, schema: CollectionSchema):
if self._type == FunctionType.BM25:
self._check_bm25_function(schema)
elif self._type == FunctionType.TEXTEMBEDDING:
self._check_text_embedding_function(schema)
elif self._type == FunctionType.RANKER:
# We will not check the ranker function here.
pass
elif self._type == FunctionType.UNKNOWN:
raise ParamError(message=ExceptionsMessage.UnknownFunctionType)
@classmethod
def construct_from_dict(cls, raw: Dict):
return Function(
raw["name"],
raw["type"],
list(raw["input_field_names"]),
list(raw["output_field_names"]),
raw["description"],
raw["params"],
)
def __repr__(self) -> str:
return str(self.to_dict())
def to_dict(self):
return {
"name": self._name,
"description": self._description,
"type": self._type,
"input_field_names": self._input_field_names,
"output_field_names": self._output_field_names,
"params": self._params,
}
def __eq__(self, value: object) -> bool:
if not isinstance(value, Function):
return False
return self.to_dict() == value.to_dict()
| Function |
python | realpython__materials | django-todo-list/source_code_final/todo_app/models.py | {
"start": 427,
"end": 1012
} | class ____(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(null=True, blank=True)
created_date = models.DateTimeField(auto_now_add=True)
due_date = models.DateTimeField(default=one_week_hence)
todo_list = models.ForeignKey(ToDoList, on_delete=models.CASCADE)
def get_absolute_url(self):
return reverse(
"item-update", args=[str(self.todo_list.id), str(self.id)]
)
def __str__(self):
return f"{self.title}: due {self.due_date}"
class Meta:
ordering = ["due_date"]
| ToDoItem |
python | fastai__fastai | fastai/data/core.py | {
"start": 12395,
"end": 14815
} | class ____:
"Base class for lists with subsets"
_dl_type,_dbunch_type = TfmdDL,DataLoaders
def __init__(self, *args, dl_type=None, **kwargs):
if dl_type is not None: self._dl_type = dl_type
self.dataloaders = delegates(self._dl_type.__init__)(self.dataloaders)
super().__init__(*args, **kwargs)
@property
def n_subsets(self): return len(self.splits)
def _new(self, items, **kwargs): return super()._new(items, splits=self.splits, **kwargs)
def subset(self): raise NotImplemented
def dataloaders(self,
bs:int=64, # Batch size
shuffle_train:bool=None, # (Deprecated, use `shuffle`) Shuffle training `DataLoader`
shuffle:bool=True, # Shuffle training `DataLoader`
val_shuffle:bool=False, # Shuffle validation `DataLoader`
n:int=None, # Size of `Datasets` used to create `DataLoader`
path:str|Path='.', # Path to put in `DataLoaders`
dl_type:TfmdDL=None, # Type of `DataLoader`
dl_kwargs:list=None, # List of kwargs to pass to individual `DataLoader`s
device:torch.device=None, # Device to put `DataLoaders`
drop_last:bool=None, # Drop last incomplete batch, defaults to `shuffle`
val_bs:int=None, # Validation batch size, defaults to `bs`
**kwargs
) -> DataLoaders:
if shuffle_train is not None:
shuffle=shuffle_train
warnings.warn('`shuffle_train` is deprecated. Use `shuffle` instead.',DeprecationWarning)
if device is None: device=default_device()
if dl_kwargs is None: dl_kwargs = [{}] * self.n_subsets
if dl_type is None: dl_type = self._dl_type
if drop_last is None: drop_last = shuffle
val_kwargs={k[4:]:v for k,v in kwargs.items() if k.startswith('val_')}
def_kwargs = {'bs':bs,'shuffle':shuffle,'drop_last':drop_last,'n':n,'device':device}
dl = dl_type(self.subset(0), **merge(kwargs,def_kwargs, dl_kwargs[0]))
def_kwargs = {'bs':bs if val_bs is None else val_bs,'shuffle':val_shuffle,'n':None,'drop_last':False}
dls = [dl] + [dl.new(self.subset(i), **merge(kwargs,def_kwargs,val_kwargs,dl_kwargs[i]))
for i in range(1, self.n_subsets)]
return self._dbunch_type(*dls, path=path, device=device)
FilteredBase.train,FilteredBase.valid = add_props(lambda i,x: x.subset(i))
# %% ../../nbs/03_data.core.ipynb 53
| FilteredBase |
python | kamyu104__LeetCode-Solutions | Python/count-the-number-of-good-subsequences.py | {
"start": 71,
"end": 929
} | class ____(object):
def countGoodSubsequences(self, s):
"""
:type s: str
:rtype: int
"""
MOD = 10**9+7
fact, inv, inv_fact = [[1]*2 for _ in xrange(3)]
def nCr(n, k):
if not (0 <= k <= n):
return 0
while len(inv) <= n: # lazy initialization
fact.append(fact[-1]*len(inv) % MOD)
inv.append(inv[MOD%len(inv)]*(MOD-MOD//len(inv)) % MOD) # https://cp-algorithms.com/algebra/module-inverse.html
inv_fact.append(inv_fact[-1]*inv[-1] % MOD)
return (fact[n]*inv_fact[n-k] % MOD) * inv_fact[k] % MOD
cnt = collections.Counter(s)
return reduce(lambda total, k: (total+reduce(lambda total, x: total*(1+nCr(x, k))%MOD, cnt.itervalues(), 1)-1)%MOD, xrange(1, max(cnt.itervalues())+1), 0)
| Solution |
python | tensorflow__tensorflow | tensorflow/compiler/tests/reshape_op_test.py | {
"start": 997,
"end": 2213
} | class ____(xla_test.XLATestCase, parameterized.TestCase):
@parameterized.named_parameters(('32_bit_index', dtypes.int32),
('64_bit_index', dtypes.int64))
def testBasic(self, index_dtype):
for dtype in self.numeric_types:
with self.session():
i = array_ops.placeholder(dtype, shape=[2, 3])
with self.test_scope():
shape = constant_op.constant([3, 2], dtype=index_dtype)
o = array_ops.reshape(i, shape)
params = {
i: [[1, 2, 3], [4, 5, 6]],
}
result = o.eval(feed_dict=params)
self.assertAllEqual([[1, 2], [3, 4], [5, 6]], result)
def testInt64(self):
with self.session():
with self.test_scope():
x = array_ops.zeros([50000, 50000], dtype=dtypes.bool)
# Provide dimension larger than int32
y = array_ops.reshape(x, [50000**2])
self.assertEqual([50000**2], y.get_shape().as_list())
# Even if first dimension is within int32, ensure we correctly go to
# int64
y = array_ops.reshape(x, [1, 50000**2])
self.assertEqual([1, 50000**2], y.get_shape().as_list())
if __name__ == '__main__':
googletest.main()
| ReshapeTest |
python | tensorflow__tensorflow | tensorflow/python/compiler/tensorrt/model_tests/model_handler.py | {
"start": 5966,
"end": 6659
} | class ____(
collections.namedtuple("ModelConfig", [
"saved_model_dir", "saved_model_tags", "saved_model_signature_key",
"default_batch_size"
])):
"""Configurations for test models."""
def __new__(cls,
saved_model_dir: str,
saved_model_tags: Sequence[str] = (tag_constants.SERVING,),
saved_model_signature_key: str = (
signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY),
default_batch_size: int = 1):
return super(ModelConfig,
cls).__new__(cls, saved_model_dir, saved_model_tags,
saved_model_signature_key, default_batch_size)
| ModelConfig |
python | ZoranPandovski__al-go-rithms | greedy/kruskal's_algorithm/python/ArthurFortes/unionFind.py | {
"start": 232,
"end": 554
} | class ____(dict):
def add(self, item):
self[item] = item
def find(self, item):
parent = self[item]
while self[parent] != parent:
parent = self[parent]
self[item] = parent
return parent
def union(self, item1, item2):
self[item2] = self[item1] | unionFind |
python | HypothesisWorks__hypothesis | hypothesis-python/src/_hypothesis_pytestplugin.py | {
"start": 1612,
"end": 20408
} | class ____:
def __init__(self, config):
assert "hypothesis" in sys.modules
from hypothesis.reporting import default
self.report = default
self.config = config
self.results = []
def __call__(self, msg):
if self.config.getoption("capture", "fd") == "no":
self.report(msg)
if not isinstance(msg, str):
msg = repr(msg)
self.results.append(msg)
# Avoiding distutils.version.LooseVersion due to
# https://github.com/HypothesisWorks/hypothesis/issues/2490
if tuple(map(int, pytest.__version__.split(".")[:2])) < (4, 6): # pragma: no cover
import warnings
PYTEST_TOO_OLD_MESSAGE = """
You are using pytest version %s. Hypothesis tests work with any test
runner, but our pytest plugin requires pytest 4.6 or newer.
Note that the pytest developers no longer support your version either!
Disabling the Hypothesis pytest plugin...
"""
warnings.warn(PYTEST_TOO_OLD_MESSAGE % (pytest.__version__,), stacklevel=1)
else:
# Restart side-effect detection as early as possible, to maximize coverage. We
# need balanced increment/decrement in configure/sessionstart to support nested
# pytest (e.g. runpytest_inprocess), so this early increment in effect replaces
# the first one in pytest_configure.
if not os.environ.get("HYPOTHESIS_EXTEND_INITIALIZATION"):
_hypothesis_globals.in_initialization += 1
if "hypothesis" in sys.modules:
# Some other plugin has imported hypothesis, so we'll check if there
# have been undetected side-effects and warn if so.
from hypothesis.configuration import notice_initialization_restarted
notice_initialization_restarted()
def pytest_addoption(parser):
group = parser.getgroup("hypothesis", "Hypothesis")
group.addoption(
LOAD_PROFILE_OPTION,
action="store",
help="Load in a registered hypothesis.settings profile",
)
group.addoption(
VERBOSITY_OPTION,
action="store",
choices=_VERBOSITY_NAMES,
help="Override profile with verbosity setting specified",
)
group.addoption(
PRINT_STATISTICS_OPTION,
action="store_true",
help="Configure when statistics are printed",
default=False,
)
group.addoption(
SEED_OPTION,
action="store",
help="Set a seed to use for all Hypothesis tests",
)
group.addoption(
EXPLAIN_OPTION,
action="store_true",
help="Enable the `explain` phase for failing Hypothesis tests",
default=False,
)
def _any_hypothesis_option(config):
return bool(any(config.getoption(opt) for opt in _ALL_OPTIONS))
def pytest_report_header(config):
if not (
config.option.verbose >= 1
or "hypothesis" in sys.modules
or _any_hypothesis_option(config)
):
return None
from hypothesis import Verbosity, settings
if config.option.verbose < 1 and settings.default.verbosity < Verbosity.verbose:
return None
settings_str = settings.default.show_changed()
if settings_str != "":
settings_str = f" -> {settings_str}"
return (
f"hypothesis profile {settings.get_current_profile_name()!r}{settings_str}"
)
def pytest_configure(config):
config.addinivalue_line("markers", "hypothesis: Tests which use hypothesis.")
if not _any_hypothesis_option(config):
return
from hypothesis import Phase, Verbosity, core, settings
profile = config.getoption(LOAD_PROFILE_OPTION)
if profile:
settings.load_profile(profile)
verbosity_name = config.getoption(VERBOSITY_OPTION)
if verbosity_name and verbosity_name != settings.default.verbosity.name:
verbosity_value = Verbosity[verbosity_name]
name = (
f"{settings.get_current_profile_name()}-with-{verbosity_name}-verbosity"
)
# register_profile creates a new profile, exactly like the current one,
# with the extra values given (in this case 'verbosity')
settings.register_profile(name, verbosity=verbosity_value)
settings.load_profile(name)
if (
config.getoption(EXPLAIN_OPTION)
and Phase.explain not in settings.default.phases
):
name = f"{settings.get_current_profile_name()}-with-explain-phase"
phases = (*settings.default.phases, Phase.explain)
settings.register_profile(name, phases=phases)
settings.load_profile(name)
seed = config.getoption(SEED_OPTION)
if seed is not None:
try:
seed = int(seed)
except ValueError:
pass
core.global_force_seed = seed
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_call(item):
__tracebackhide__ = True
if not (hasattr(item, "obj") and "hypothesis" in sys.modules):
yield
return
from hypothesis import core, is_hypothesis_test
# See https://github.com/pytest-dev/pytest/issues/9159
core.pytest_shows_exceptiongroups = (
getattr(pytest, "version_tuple", ())[:2] >= (7, 2)
or item.config.getoption("tbstyle", "auto") == "native"
)
core.running_under_pytest = True
if not is_hypothesis_test(item.obj):
# If @given was not applied, check whether other hypothesis
# decorators were applied, and raise an error if they were.
# We add this frame of indirection to enable __tracebackhide__.
def raise_hypothesis_usage_error(msg):
raise InvalidArgument(msg)
if getattr(item.obj, "is_hypothesis_strategy_function", False):
from hypothesis.errors import InvalidArgument
raise_hypothesis_usage_error(
f"{item.nodeid} is a function that returns a Hypothesis strategy, "
"but pytest has collected it as a test function. This is useless "
"as the function body will never be executed. To define a test "
"function, use @given instead of @composite."
)
message = "Using `@%s` on a test without `@given` is completely pointless."
for name, attribute in [
("example", "hypothesis_explicit_examples"),
("seed", "_hypothesis_internal_use_seed"),
("settings", "_hypothesis_internal_settings_applied"),
("reproduce_example", "_hypothesis_internal_use_reproduce_failure"),
]:
if hasattr(item.obj, attribute):
from hypothesis.errors import InvalidArgument
raise_hypothesis_usage_error(message % (name,))
yield
return
from hypothesis import HealthCheck, settings as Settings
from hypothesis.internal.escalation import current_pytest_item
from hypothesis.internal.healthcheck import fail_health_check
from hypothesis.reporting import with_reporter
from hypothesis.statistics import collector, describe_statistics
# Retrieve the settings for this test from the test object, which
# is normally a Hypothesis wrapped_test wrapper. If this doesn't
# work, the test object is probably something weird
# (e.g a stateful test wrapper), so we skip the function-scoped
# fixture check.
settings = getattr(
item.obj, "_hypothesis_internal_use_settings", Settings.default
)
# Check for suspicious use of function-scoped fixtures, but only
# if the corresponding health check is not suppressed.
fixture_params = False
if not set(settings.suppress_health_check).issuperset(
{HealthCheck.function_scoped_fixture, HealthCheck.differing_executors}
):
# Warn about function-scoped fixtures, excluding autouse fixtures because
# the advice is probably not actionable and the status quo seems OK...
# See https://github.com/HypothesisWorks/hypothesis/issues/377 for detail.
argnames = None
for fx_defs in item._request._fixturemanager.getfixtureinfo(
node=item, func=item.function, cls=None
).name2fixturedefs.values():
if argnames is None:
argnames = frozenset(signature(item.function).parameters)
for fx in fx_defs:
fixture_params |= bool(fx.params)
if fx.argname not in argnames:
continue
active_fx = item._request._get_active_fixturedef(fx.argname)
if active_fx.scope == "function":
fail_health_check(
settings,
f"{item.nodeid!r} uses a function-scoped fixture {fx.argname!r}."
"\n\n"
"Function-scoped fixtures are not reset between inputs "
"generated by `@given(...)`, which is often surprising and "
"can cause subtle test bugs."
"\n\n"
"If you were expecting the fixture to run separately "
"for each generated input, then unfortunately you "
"will need to find a different way to achieve your "
"goal (for example, replacing the fixture with a similar "
"context manager inside of the test)."
"\n\n"
"If you are confident that your test will work correctly "
"even though the fixture is not reset between generated "
"inputs, you can suppress this health check with "
"@settings(suppress_health_check=[HealthCheck.function_scoped_fixture]). "
"See "
"https://hypothesis.readthedocs.io/en/latest/reference/api.html#hypothesis.HealthCheck "
"for details.",
HealthCheck.function_scoped_fixture,
)
if fixture_params or (item.get_closest_marker("parametrize") is not None):
# Disable the differing_executors health check due to false alarms:
# see https://github.com/HypothesisWorks/hypothesis/issues/3733
fn = getattr(item.obj, "__func__", item.obj)
fn._hypothesis_internal_use_settings = Settings(
parent=settings,
suppress_health_check={HealthCheck.differing_executors}
| set(settings.suppress_health_check),
)
# Give every parametrized test invocation a unique database key
key = item.nodeid.encode()
item.obj.hypothesis.inner_test._hypothesis_internal_add_digest = key
store = StoringReporter(item.config)
def note_statistics(stats):
stats["nodeid"] = item.nodeid
item.hypothesis_statistics = describe_statistics(stats)
with (
collector.with_value(note_statistics),
with_reporter(store),
current_pytest_item.with_value(item),
):
yield
if store.results:
item.hypothesis_report_information = "\n".join(store.results)
def _stash_get(config, key, default):
if hasattr(config, "stash"):
# pytest 7
return config.stash.get(key, default)
elif hasattr(config, "_store"):
# pytest 5.4
return config._store.get(key, default)
else:
return getattr(config, key, default)
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
report = (yield).get_result()
if hasattr(item, "hypothesis_report_information"):
report.sections.append(("Hypothesis", item.hypothesis_report_information))
if report.when != "teardown":
return
terminalreporter = item.config.pluginmanager.getplugin("terminalreporter")
if hasattr(item, "hypothesis_statistics"):
stats = item.hypothesis_statistics
stats_base64 = base64.b64encode(stats.encode()).decode()
name = "hypothesis-statistics-" + item.nodeid
# Include hypothesis information to the junit XML report.
#
# Note that when `pytest-xdist` is enabled, `xml_key` is not present in the
# stash, so we don't add anything to the junit XML report in that scenario.
# https://github.com/pytest-dev/pytest/issues/7767#issuecomment-1082436256
xml = _stash_get(item.config, xml_key, None)
if xml:
xml.add_global_property(name, stats_base64)
# If there's a terminal report, include our summary stats for each test
if terminalreporter is not None:
report.__dict__[STATS_KEY] = stats
# If there's an HTML report, include our summary stats for each test
pytest_html = item.config.pluginmanager.getplugin("html")
if pytest_html is not None: # pragma: no cover
report.extra = [
*getattr(report, "extra", []),
pytest_html.extras.text(stats, name="Hypothesis stats"),
]
# This doesn't intrinsically have anything to do with the terminalreporter;
# we're just cargo-culting a way to get strings back to a single function
# even if the test were distributed with pytest-xdist.
failing_examples = getattr(item, FAILING_EXAMPLES_KEY, None)
if failing_examples and terminalreporter is not None:
try:
from hypothesis.extra._patching import FAIL_MSG, get_patch_for
except ImportError:
return
# We'll save this as a triple of [filename, hunk_before, hunk_after].
triple = get_patch_for(item.obj, [(x, FAIL_MSG) for x in failing_examples])
if triple is not None:
report.__dict__[FAILING_EXAMPLES_KEY] = json.dumps(triple)
def pytest_terminal_summary(terminalreporter):
failing_examples = []
print_stats = terminalreporter.config.getoption(PRINT_STATISTICS_OPTION)
if print_stats:
terminalreporter.section("Hypothesis Statistics")
for reports in terminalreporter.stats.values():
for report in reports:
stats = report.__dict__.get(STATS_KEY)
if stats and print_stats:
terminalreporter.write_line(stats + "\n\n")
examples = report.__dict__.get(FAILING_EXAMPLES_KEY)
if examples:
failing_examples.append(json.loads(examples))
from hypothesis.internal.observability import _WROTE_TO
if _WROTE_TO:
terminalreporter.section("Hypothesis")
for fname in sorted(_WROTE_TO):
terminalreporter.write_line(f"observations written to {fname}")
if failing_examples:
# This must have been imported already to write the failing examples
from hypothesis.extra._patching import gc_patches, make_patch, save_patch
patch = make_patch(failing_examples)
try:
gc_patches()
fname = save_patch(patch)
except Exception:
# fail gracefully if we hit any filesystem or permissions problems
return
if not _WROTE_TO:
terminalreporter.section("Hypothesis")
terminalreporter.write_line(
f"`git apply {fname}` to add failing examples to your code."
)
def pytest_collection_modifyitems(items):
if "hypothesis" not in sys.modules:
return
from hypothesis import is_hypothesis_test
for item in items:
if isinstance(item, pytest.Function) and is_hypothesis_test(item.obj):
item.add_marker("hypothesis")
def pytest_sessionstart(session):
# Note: may be called multiple times, so we can go negative
_hypothesis_globals.in_initialization -= 1
# Monkeypatch some internals to prevent applying @pytest.fixture() to a
# function which has already been decorated with @hypothesis.given().
# (the reverse case is already an explicit error in Hypothesis)
# We do this here so that it catches people on old Pytest versions too.
from _pytest import fixtures
def _ban_given_call(self, function):
if "hypothesis" in sys.modules:
from hypothesis import is_hypothesis_test
if is_hypothesis_test(function):
raise RuntimeError(
f"Can't apply @pytest.fixture() to {function.__name__} because "
"it is already decorated with @hypothesis.given()"
)
return _orig_call(self, function)
_orig_call = fixtures.FixtureFunctionMarker.__call__
fixtures.FixtureFunctionMarker.__call__ = _ban_given_call # type: ignore
if int(pytest.__version__.split(".")[0]) >= 7: # pragma: no branch
# Hook has had this signature since Pytest 7.0, so skip on older versions
def pytest_ignore_collect(collection_path, config):
# Detect, warn about, and mititgate certain misconfigurations;
# this is mostly educational but can also speed up collection.
if (
(name := collection_path.name) == ".hypothesis"
and collection_path.is_dir()
and not any(fnmatch(name, p) for p in config.getini("norecursedirs"))
):
warnings.warn(
"Skipping collection of '.hypothesis' directory - this usually "
"means you've explicitly set the `norecursedirs` pytest config "
"option, replacing rather than extending the default ignores.",
stacklevel=1,
)
return True
return None # let other hooks decide
def load():
"""Required for `pluggy` to load a plugin from setuptools entrypoints."""
| StoringReporter |
python | pikepdf__pikepdf | src/pikepdf/models/metadata.py | {
"start": 9452,
"end": 9975
} | class ____(NamedTuple):
"""Map DocumentInfo keys to their XMP equivalents, along with converter."""
ns: str
key: str
name: Name
converter: type[Converter] | None
def ensure_loaded(fn):
"""Ensure the XMP has been loaded and parsed.
TODO: Can this be removed? Why allow the uninit'ed state to even exist?
"""
@wraps(fn)
def wrapper(self, *args, **kwargs):
if not self._xmp:
self._load()
return fn(self, *args, **kwargs)
return wrapper
| DocinfoMapping |
python | astropy__astropy | astropy/io/ascii/qdp.py | {
"start": 15158,
"end": 15368
} | class ____(basic.CommentedHeaderHeader):
"""
Header that uses the :class:`astropy.io.ascii.basic.QDPSplitter`.
"""
splitter_class = QDPSplitter
comment = "!"
write_comment = "!"
| QDPHeader |
python | keon__algorithms | tests/test_polynomial.py | {
"start": 129,
"end": 5370
} | class ____(unittest.TestCase):
def setUp(self):
self.p0 = Polynomial([
Monomial({})
])
self.p1 = Polynomial([
Monomial({}), Monomial({})
])
self.p2 = Polynomial([
Monomial({1: 1}, 2)
])
self.p3 = Polynomial([
Monomial({1: 1}, 2),
Monomial({1: 2, 2: -1}, 1.5)
])
self.p4 = Polynomial([
Monomial({2: 1, 3: 0}, Fraction(2, 3)),
Monomial({1: -1, 3: 2}, math.pi),
Monomial({1: -1, 3: 2}, 1)
])
self.p5 = Polynomial([
Monomial({150: 5, 170: 2, 10000:3}, 0),
Monomial({1: -1, 3: 2}, 1),
])
self.p6 = Polynomial([
2,
-3,
Fraction(1, 7),
2**math.pi,
Monomial({2: 3, 3: 1}, 1.25)
])
self.p7 = Polynomial([
Monomial({1: 1}, -2),
Monomial({1: 2, 2: -1}, -1.5)
])
self.m1 = Monomial({1: 2, 2: 3}, -1)
return
def test_polynomial_addition(self):
# The zero polynomials should add up to
# itselves only.
self.assertEqual(self.p0 + self.p1, self.p0)
self.assertEqual(self.p0 + self.p1, self.p1)
# Additive inverses should add up to the
# zero polynomial.
self.assertEqual(self.p3 + self.p7, self.p0)
self.assertEqual(self.p3 + self.p7, self.p1)
# Like terms should combine.
# The order of monomials should not matter.
self.assertEqual(self.p2 + self.p3, Polynomial([
Monomial({1: 1}, 4),
Monomial({1: 2, 2: -1}, 1.5)
]))
self.assertEqual(self.p2 + self.p3, Polynomial([
Monomial({1: 2, 2: -1}, 1.5),
Monomial({1: 1}, 4),
]))
# Another typical computation.
self.assertEqual(self.p5 + self.p6, Polynomial([
Monomial({}, 7.96783496993343),
Monomial({2: 3, 3: 1}, 1.25),
Monomial({1: -1, 3: 2})
]))
return
def test_polynomial_subtraction(self):
self.assertEqual(self.p3 - self.p2, Polynomial([
Monomial({1: 2, 2: -1}, 1.5)
]))
self.assertEqual(self.p3 - self.p3, Polynomial([]))
self.assertEqual(self.p2 - self.p3, Polynomial([
Monomial({1: 2, 2: -1}, -1.5)
]))
pass
def test_polynomial_multiplication(self):
self.assertEqual(self.p0 * self.p2, Polynomial([]))
self.assertEqual(self.p1 * self.p2, Polynomial([]))
self.assertEqual(self.p2 * self.p3, Polynomial([
Monomial({1: 2}, 4),
Monomial({1: 3, 2: -1}, Fraction(3, 1))
]))
return
def test_polynomial_variables(self):
# The zero polynomial has no variables.
self.assertEqual(self.p0.variables(), set())
self.assertEqual(self.p1.variables(), set())
# The total variables are the union of the variables
# from the monomials.
self.assertEqual(self.p4.variables(), {1, 2, 3})
# The monomials with coefficient 0 should be dropped.
self.assertEqual(self.p5.variables(), {1, 3})
return
def test_polynomial_subs(self):
# Anything substitued in the zero polynomial
# should evaluate to 0.
self.assertEqual(self.p1.subs(2), 0)
self.assertEqual(self.p0.subs(-101231), 0)
# Should raise a ValueError if not enough variables are supplied.
self.assertRaises(ValueError, lambda x, y: x.subs(y), self.p4, {1: 3, 2: 2})
self.assertRaises(ValueError, lambda x, y: x.subs(y), self.p4, {})
# Should work fine if a complete subsitution map is provided.
self.assertAlmostEqual(self.p4.subs({1: 1, 2: 1, 3: 1}), (1 + math.pi + Fraction(2, 3)), delta=1e-9)
# Should work fine if more than enough substitutions are provided.
self.assertAlmostEqual(self.p4.subs({1: 1, 2: 1, 3: 1, 4: 1}), (1 + math.pi + Fraction(2, 3)), delta=1e-9)
return
def test_polynomial_clone(self):
# The zero polynomial always clones to itself.
self.assertEqual(self.p0.clone(), self.p0)
self.assertEqual(self.p1.clone(), self.p0)
self.assertEqual(self.p0.clone(), self.p1)
self.assertEqual(self.p1.clone(), self.p1)
# The polynomial should clone nicely.
self.assertEqual(self.p4.clone(), self.p4)
# The monomial with a zero coefficient should be dropped
# in the clone.
self.assertEqual(self.p5.clone(), Polynomial([
Monomial({1: -1, 3: 2}, 1)
]))
return
def test_polynomial_long_division(self):
"""
Test polynomial long division
"""
# Dividend: 4a_1^3 + 3a_1^2 - 2a_1 + 5
dividend = Polynomial([
Monomial({1: 3}, 4), # 4(a_1)^3
Monomial({1: 2}, 3), # 3(a_1)^2
Monomial({1: 1}, -2), # -2(a_1)
Monomial({}, 5) # +5
])
# Divisor: 2a_1 - 1
divisor = Polynomial([
Monomial({1: 1}, 2), # 2(a_1)
Monomial({}, -1) # -1
])
# Expected Quotient: 2a_1^2 + (5/2)a_1 + 1/4
expected_quotient = Polynomial([
Monomial({1: 2}, 2), # 2(a_1)^2
Monomial({1: 1}, Fraction(5, 2)), # (5/2)(a_1)
Monomial({}, Fraction(1, 4)) # +1/4
])
# Expected Remainder: 21/4
expected_remainder = Polynomial([
Monomial({}, Fraction(21, 4)) # 21/4
])
quotient_long_div, remainder_long_div = dividend.poly_long_division(divisor)
quotient_truediv = dividend / divisor # Calls __truediv__, which returns only the quotient
# Check if quotient from poly_long_division matches expected
self.assertEqual(quotient_long_div, expected_quotient)
# Check if remainder from poly_long_division matches expected
self.assertEqual(remainder_long_div, expected_remainder)
# Check if quotient from __truediv__ matches quotient from poly_long_division
self.assertEqual(quotient_truediv, quotient_long_div)
return
| TestSuite |
python | numpy__numpy | numpy/_core/tests/test_numeric.py | {
"start": 77179,
"end": 77701
} | class ____:
def test_boolean(self):
a = rand(3, 5, 8)
V = rand(5, 8)
g1 = randint(0, 5, size=15)
g2 = randint(0, 8, size=15)
V[g1, g2] = -V[g1, g2]
assert_(
(np.array([a[0][V > 0], a[1][V > 0], a[2][V > 0]]) == a[:, V > 0]).all()
)
def test_boolean_edgecase(self):
a = np.array([], dtype='int32')
b = np.array([], dtype='bool')
c = a[b]
assert_equal(c, [])
assert_equal(c.dtype, np.dtype('int32'))
| TestIndex |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_column_values_to_be_dateutil_parseable.py | {
"start": 923,
"end": 6421
} | class ____(ColumnMapExpectation):
"""Expect the column entries to be parsable using dateutil.
ExpectColumnValuesToBeDateutilParseable is a \
Column Map Expectation
Args:
column (str): \
The column name.
Keyword Args:
mostly (None or a float between 0 and 1): \
Successful if at least mostly fraction of values match the expectation. \
For more detail, see [mostly](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#mostly).
Other Parameters:
result_format (str or None): \
Which output mode to use: BOOLEAN_ONLY, BASIC, COMPLETE, or SUMMARY. \
For more detail, see [result_format](https://docs.greatexpectations.io/docs/reference/expectations/result_format).
catch_exceptions (boolean or None): \
If True, then catch exceptions and include them as part of the result object. \
For more detail, see [catch_exceptions](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#catch_exceptions).
meta (dict or None): \
A JSON-serializable dictionary (nesting allowed) that will be included in the output without \
modification. For more detail, see [meta](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#meta).
severity (str or None): \
{FAILURE_SEVERITY_DESCRIPTION} \
For more detail, see [failure severity](https://docs.greatexpectations.io/docs/cloud/expectations/expectations_overview/#failure-severity).
Returns:
An [ExpectationSuiteValidationResult](https://docs.greatexpectations.io/docs/terms/validation_result)
Exact fields vary depending on the values passed to result_format, catch_exceptions, and meta.
""" # noqa: E501 # FIXME CoP
# This dictionary contains metadata for display in the public gallery
library_metadata = {
"maturity": "production",
"tags": ["core expectation", "column map expectation"],
"contributors": ["@great_expectations"],
"requirements": [],
"has_full_test_suite": True,
"manually_reviewed_code": True,
}
map_metric = "column_values.dateutil_parseable"
success_keys = ("mostly",)
args_keys = ("column",)
@classmethod
def _prescriptive_template(
cls,
renderer_configuration: RendererConfiguration,
) -> RendererConfiguration:
add_param_args: AddParamArgs = (
("column", RendererValueType.STRING),
("mostly", RendererValueType.NUMBER),
)
for name, param_type in add_param_args:
renderer_configuration.add_param(name=name, param_type=param_type)
params = renderer_configuration.params
template_str = "values must be parseable by dateutil"
if params.mostly and params.mostly.value < 1.0:
renderer_configuration = cls._add_mostly_pct_param(
renderer_configuration=renderer_configuration
)
template_str += ", at least $mostly_pct % of the time."
else:
template_str += "."
if renderer_configuration.include_column_name:
template_str = f"$column {template_str}"
renderer_configuration.template_str = template_str
return renderer_configuration
@classmethod
@renderer(renderer_type=LegacyRendererType.PRESCRIPTIVE)
@render_suite_parameter_string
def _prescriptive_renderer(
cls,
configuration: Optional[ExpectationConfiguration] = None,
result: Optional[ExpectationValidationResult] = None,
runtime_configuration: Optional[dict] = None,
**kwargs,
):
runtime_configuration = runtime_configuration or {}
include_column_name = runtime_configuration.get("include_column_name") is not False
styling = runtime_configuration.get("styling")
params = substitute_none_for_missing(
configuration.kwargs,
["column", "mostly", "row_condition", "condition_parser"],
)
template_str = "values must be parseable by dateutil"
if params["mostly"] is not None:
if isinstance(params["mostly"], (int, float)) and params["mostly"] < 1.0:
params["mostly_pct"] = num_to_str(params["mostly"] * 100, no_scientific=True)
# params["mostly_pct"] = "{:.14f}".format(params["mostly"]*100).rstrip("0").rstrip(".") # noqa: E501 # FIXME CoP
template_str += ", at least $mostly_pct % of the time."
else:
template_str += "."
if include_column_name:
template_str = f"$column {template_str}"
if params["row_condition"] is not None:
conditional_template_str = parse_row_condition_string(params["row_condition"])
template_str, styling = _style_row_condition(
conditional_template_str,
template_str,
params,
styling,
)
return [
RenderedStringTemplateContent(
**{
"content_block_type": "string_template",
"string_template": {
"template": template_str,
"params": params,
"styling": styling,
},
}
)
]
| ExpectColumnValuesToBeDateutilParseable |
python | django-guardian__django-guardian | example_project/posts/views.py | {
"start": 345,
"end": 801
} | class ____(ListView):
model = Post
context_object_name = "posts"
post_list = PostList.as_view()
@permission_required_or_403("posts.view_post", (Post, "slug", "slug"))
def post_detail(request, slug, **kwargs):
data = {
"post": get_object_or_404(Post, slug=slug),
"users": User.objects.all(),
"groups": Group.objects.all(),
}
return render(request, "posts/post_detail.html", data, RequestContext(request))
| PostList |
python | getsentry__sentry | tests/sentry/web/test_api.py | {
"start": 3161,
"end": 5039
} | class ____(TestCase):
@cached_property
def path(self) -> str:
return reverse("sentry-robots-txt")
def test_robots(self) -> None:
resp = self.client.get(self.path)
assert resp.status_code == 200
assert resp["Content-Type"] == "text/plain"
def test_self_hosted_mode(self) -> None:
with override_settings(SENTRY_MODE="self_hosted"):
response = self.client.get("/robots.txt")
assert response.status_code == 200
assert (
response.content
== b"""User-agent: *
Disallow: /
"""
)
assert response["Content-Type"] == "text/plain"
def test_saas_mode(self) -> None:
with override_settings(SENTRY_MODE="saas"):
response = self.client.get("/robots.txt")
assert response.status_code == 200
assert (
response.content
== b"""User-agent: *
Disallow: /api/
Allow: /
Sitemap: https://sentry.io/sitemap-index.xml
"""
)
assert response["Content-Type"] == "text/plain"
def test_region_domain(self) -> None:
HTTP_HOST = "us.testserver"
response = self.client.get("/robots.txt", HTTP_HOST=HTTP_HOST)
assert response.status_code == 200
assert (
response.content
== b"""User-agent: *
Disallow: /
"""
)
assert response["Content-Type"] == "text/plain"
def test_customer_domain(self) -> None:
HTTP_HOST = "albertos-apples.testserver"
response = self.client.get("/robots.txt", HTTP_HOST=HTTP_HOST)
assert response.status_code == 200
assert (
response.content
== b"""User-agent: *
Disallow: /
"""
)
assert response["Content-Type"] == "text/plain"
@region_silo_test(regions=create_test_regions("us", "eu"), include_monolith_run=True)
| RobotsTxtTest |
python | imageio__imageio | imageio/plugins/pillowmulti.py | {
"start": 3260,
"end": 11807
} | class ____: # pragma: no cover
"""Class that for helping write the animated GIF file. This is based on
code from images2gif.py (part of visvis). The version here is modified
to allow streamed writing.
"""
def __init__(
self,
file,
opt_subrectangle=True,
opt_loop=0,
opt_quantizer=0,
opt_palette_size=256,
):
self.fp = file
self.opt_subrectangle = opt_subrectangle
self.opt_loop = opt_loop
self.opt_quantizer = opt_quantizer
self.opt_palette_size = opt_palette_size
self._previous_image = None # as np array
self._global_palette = None # as bytes
self._count = 0
from PIL.GifImagePlugin import getdata
self.getdata = getdata
def add_image(self, im, duration, dispose):
# Prepare image
im_rect, rect = im, (0, 0)
if self.opt_subrectangle:
im_rect, rect = self.getSubRectangle(im)
im_pil = self.converToPIL(im_rect, self.opt_quantizer, self.opt_palette_size)
# Get pallette - apparently, this is the 3d element of the header
# (but it has not always been). Best we've got. Its not the same
# as im_pil.palette.tobytes().
from PIL.GifImagePlugin import getheader
palette = getheader(im_pil)[0][3]
# Write image
if self._count == 0:
self.write_header(im_pil, palette, self.opt_loop)
self._global_palette = palette
self.write_image(im_pil, palette, rect, duration, dispose)
# assert len(palette) == len(self._global_palette)
# Bookkeeping
self._previous_image = im
self._count += 1
def write_header(self, im, globalPalette, loop):
# Gather info
header = self.getheaderAnim(im)
appext = self.getAppExt(loop)
# Write
self.fp.write(header)
self.fp.write(globalPalette)
self.fp.write(appext)
def close(self):
self.fp.write(";".encode("utf-8")) # end gif
def write_image(self, im, palette, rect, duration, dispose):
fp = self.fp
# Gather local image header and data, using PIL's getdata. That
# function returns a list of bytes objects, but which parts are
# what has changed multiple times, so we put together the first
# parts until we have enough to form the image header.
data = self.getdata(im)
imdes = b""
while data and len(imdes) < 11:
imdes += data.pop(0)
assert len(imdes) == 11
# Make image descriptor suitable for using 256 local color palette
lid = self.getImageDescriptor(im, rect)
graphext = self.getGraphicsControlExt(duration, dispose)
# Write local header
if (palette != self._global_palette) or (dispose != 2):
# Use local color palette
fp.write(graphext)
fp.write(lid) # write suitable image descriptor
fp.write(palette) # write local color table
fp.write(b"\x08") # LZW minimum size code
else:
# Use global color palette
fp.write(graphext)
fp.write(imdes) # write suitable image descriptor
# Write image data
for d in data:
fp.write(d)
def getheaderAnim(self, im):
"""Get animation header. To replace PILs getheader()[0]"""
bb = b"GIF89a"
bb += intToBin(im.size[0])
bb += intToBin(im.size[1])
bb += b"\x87\x00\x00"
return bb
def getImageDescriptor(self, im, xy=None):
"""Used for the local color table properties per image.
Otherwise global color table applies to all frames irrespective of
whether additional colors comes in play that require a redefined
palette. Still a maximum of 256 color per frame, obviously.
Written by Ant1 on 2010-08-22
Modified by Alex Robinson in Janurari 2011 to implement subrectangles.
"""
# Defaule use full image and place at upper left
if xy is None:
xy = (0, 0)
# Image separator,
bb = b"\x2c"
# Image position and size
bb += intToBin(xy[0]) # Left position
bb += intToBin(xy[1]) # Top position
bb += intToBin(im.size[0]) # image width
bb += intToBin(im.size[1]) # image height
# packed field: local color table flag1, interlace0, sorted table0,
# reserved00, lct size111=7=2^(7 + 1)=256.
bb += b"\x87"
# LZW minimum size code now comes later, begining of [imagedata] blocks
return bb
def getAppExt(self, loop):
"""Application extension. This part specifies the amount of loops.
If loop is 0 or inf, it goes on infinitely.
"""
if loop == 1:
return b""
if loop == 0:
loop = 2**16 - 1
bb = b""
if loop != 0: # omit the extension if we would like a nonlooping gif
bb = b"\x21\xff\x0b" # application extension
bb += b"NETSCAPE2.0"
bb += b"\x03\x01"
bb += intToBin(loop)
bb += b"\x00" # end
return bb
def getGraphicsControlExt(self, duration=0.1, dispose=2):
"""Graphics Control Extension. A sort of header at the start of
each image. Specifies duration and transparancy.
Dispose
-------
* 0 - No disposal specified.
* 1 - Do not dispose. The graphic is to be left in place.
* 2 - Restore to background color. The area used by the graphic
must be restored to the background color.
* 3 - Restore to previous. The decoder is required to restore the
area overwritten by the graphic with what was there prior to
rendering the graphic.
* 4-7 -To be defined.
"""
bb = b"\x21\xf9\x04"
bb += chr((dispose & 3) << 2).encode("utf-8")
# low bit 1 == transparency,
# 2nd bit 1 == user input , next 3 bits, the low two of which are used,
# are dispose.
bb += intToBin(int(duration * 100 + 0.5)) # in 100th of seconds
bb += b"\x00" # no transparant color
bb += b"\x00" # end
return bb
def getSubRectangle(self, im):
"""Calculate the minimal rectangle that need updating. Returns
a two-element tuple containing the cropped image and an x-y tuple.
Calculating the subrectangles takes extra time, obviously. However,
if the image sizes were reduced, the actual writing of the GIF
goes faster. In some cases applying this method produces a GIF faster.
"""
# Cannot do subrectangle for first image
if self._count == 0:
return im, (0, 0)
prev = self._previous_image
# Get difference, sum over colors
diff = np.abs(im - prev)
if diff.ndim == 3:
diff = diff.sum(2)
# Get begin and end for both dimensions
X = np.argwhere(diff.sum(0))
Y = np.argwhere(diff.sum(1))
# Get rect coordinates
if X.size and Y.size:
x0, x1 = int(X[0]), int(X[-1] + 1)
y0, y1 = int(Y[0]), int(Y[-1] + 1)
else: # No change ... make it minimal
x0, x1 = 0, 2
y0, y1 = 0, 2
return im[y0:y1, x0:x1], (x0, y0)
def converToPIL(self, im, quantizer, palette_size=256):
"""Convert image to Paletted PIL image.
PIL used to not do a very good job at quantization, but I guess
this has improved a lot (at least in Pillow). I don't think we need
neuqant (and we can add it later if we really want).
"""
im_pil = ndarray_to_pil(im, "gif")
if quantizer in ("nq", "neuquant"):
# NeuQuant algorithm
nq_samplefac = 10 # 10 seems good in general
im_pil = im_pil.convert("RGBA") # NQ assumes RGBA
nqInstance = NeuQuant(im_pil, nq_samplefac) # Learn colors
im_pil = nqInstance.quantize(im_pil, colors=palette_size)
elif quantizer in (0, 1, 2):
# Adaptive PIL algorithm
if quantizer == 2:
im_pil = im_pil.convert("RGBA")
else:
im_pil = im_pil.convert("RGB")
im_pil = im_pil.quantize(colors=palette_size, method=quantizer)
else:
raise ValueError("Invalid value for quantizer: %r" % quantizer)
return im_pil
| GifWriter |
python | huggingface__transformers | src/transformers/models/glm4v/modeling_glm4v.py | {
"start": 63880,
"end": 77452
} | class ____(Glm4vPreTrainedModel, GenerationMixin):
_checkpoint_conversion_mapping = {}
_tied_weights_keys = {"lm_head.weight": "model.language_model.embed_tokens.weight"}
# Reference: fix gemma3 grad acc #37208
accepts_loss_kwargs = False
def __init__(self, config):
super().__init__(config)
self.model = Glm4vModel(config)
self.lm_head = nn.Linear(config.text_config.hidden_size, config.text_config.vocab_size, bias=False)
self.post_init()
def get_input_embeddings(self):
return self.model.get_input_embeddings()
def set_input_embeddings(self, value):
self.model.set_input_embeddings(value)
def get_video_features(
self, pixel_values_videos: torch.FloatTensor, video_grid_thw: Optional[torch.LongTensor] = None
):
return self.model.get_video_features(pixel_values_videos, video_grid_thw)
def get_image_features(self, pixel_values: torch.FloatTensor, image_grid_thw: Optional[torch.LongTensor] = None):
return self.model.get_image_features(pixel_values, image_grid_thw)
@can_return_tuple
@auto_docstring
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
labels: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.Tensor] = None,
pixel_values_videos: Optional[torch.FloatTensor] = None,
image_grid_thw: Optional[torch.LongTensor] = None,
video_grid_thw: Optional[torch.LongTensor] = None,
cache_position: Optional[torch.LongTensor] = None,
logits_to_keep: Union[int, torch.Tensor] = 0,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple, Glm4vCausalLMOutputWithPast]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
image_grid_thw (`torch.LongTensor` of shape `(num_images, 3)`, *optional*):
The temporal, height and width of feature shape of each image in LLM.
video_grid_thw (`torch.LongTensor` of shape `(num_videos, 3)`, *optional*):
The temporal, height and width of feature shape of each video in LLM.
Example:
```python
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, Glm4vForConditionalGeneration
>>> model = Glm4vForConditionalGeneration.from_pretrained("THUDM/GLM-4.1V-9B-Thinking")
>>> processor = AutoProcessor.from_pretrained("THUDM/GLM-4.1V-9B-Thinking")
>>> messages = [
{
"role": "user",
"content": [
{"type": "image"},
{"type": "text", "text": "What is shown in this image?"},
],
},
]
>>> url = "https://www.ilankelman.org/stopsigns/australia.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
>>> inputs = processor(text=[text], images=[image], vision_infos=[vision_infos])
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"The image shows a street scene with a red stop sign in the foreground. In the background, there is a large red gate with Chinese characters ..."
```"""
outputs = self.model(
input_ids=input_ids,
pixel_values=pixel_values,
pixel_values_videos=pixel_values_videos,
image_grid_thw=image_grid_thw,
video_grid_thw=video_grid_thw,
position_ids=position_ids,
attention_mask=attention_mask,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
cache_position=cache_position,
**kwargs,
)
hidden_states = outputs[0]
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
logits = self.lm_head(hidden_states[:, slice_indices, :])
loss = None
if labels is not None:
loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size)
return Glm4vCausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
rope_deltas=outputs.rope_deltas,
)
def prepare_inputs_for_generation(
self,
input_ids,
past_key_values=None,
attention_mask=None,
inputs_embeds=None,
cache_position=None,
position_ids=None,
use_cache=True,
pixel_values=None,
pixel_values_videos=None,
image_grid_thw=None,
video_grid_thw=None,
**kwargs,
):
# Overwritten -- in specific circumstances we don't want to forward image inputs to the model
model_inputs = super().prepare_inputs_for_generation(
input_ids,
past_key_values=past_key_values,
attention_mask=attention_mask,
inputs_embeds=inputs_embeds,
cache_position=cache_position,
position_ids=position_ids,
pixel_values=pixel_values,
pixel_values_videos=pixel_values_videos,
image_grid_thw=image_grid_thw,
video_grid_thw=video_grid_thw,
use_cache=use_cache,
**kwargs,
)
# GLM-4.1V position_ids are prepareed with rope_deltas in forward
model_inputs["position_ids"] = None
if cache_position[0] != 0:
model_inputs["pixel_values"] = None
model_inputs["pixel_values_videos"] = None
return model_inputs
def _get_image_nums_and_video_nums(
self,
input_ids: Optional[torch.LongTensor],
inputs_embeds: Optional[torch.Tensor] = None,
) -> tuple[torch.Tensor, torch.Tensor]:
"""
Get the number of images and videos for each sample to calculate the separation length of the sample tensor.
These parameters are not passed through the processor to avoid unpredictable impacts from interface modifications.
Args:
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
Returns:
image_nums (`torch.LongTensor` of shape `(batch_size, num_images_sample)`)
video_nums (`torch.LongTensor` of shape `(batch_size, num_videos_sample)`)
"""
if inputs_embeds is not None:
is_image = (
inputs_embeds
== self.get_input_embeddings()(
torch.tensor(self.config.image_start_token_id, dtype=torch.long, device=inputs_embeds.device)
)
)[..., 0]
is_video_start = (
inputs_embeds
== self.get_input_embeddings()(
torch.tensor(self.config.video_start_token_id, dtype=torch.long, device=inputs_embeds.device)
)
)[..., 0]
is_video_end = (
inputs_embeds
== self.get_input_embeddings()(
torch.tensor(self.config.video_end_token_id, dtype=torch.long, device=inputs_embeds.device)
)
)[..., 0]
else:
is_image = input_ids == self.config.image_start_token_id
is_video_start = input_ids == self.config.video_start_token_id
is_video_end = input_ids == self.config.video_end_token_id
# Cumulative sum to track if we're inside a video span
# We'll assume well-formed video tags (i.e. matching starts and ends)
video_level = torch.cumsum(is_video_start.int() - is_video_end.int(), dim=1)
inside_video = video_level > 0 # shape (batch_size, seq_length)
# Mask out image tokens that are inside video spans
standalone_images = is_image & (~inside_video)
# Count per batch
image_counts = standalone_images.sum(dim=1)
video_counts = is_video_start.sum(dim=1)
return image_counts, video_counts
def _expand_inputs_for_generation(
self,
expand_size: int = 1,
is_encoder_decoder: bool = False,
input_ids: Optional[torch.LongTensor] = None,
**model_kwargs,
) -> tuple[torch.LongTensor, dict[str, Any]]:
# Overwritten -- Support for expanding tensors without a batch size dimension
# e.g., pixel_values, image_grid_thw, pixel_values_videos, video_grid_thw, second_per_grid_t
# pixel_values.shape[0] is sum(seqlen_images for samples)
# image_grid_thw.shape[0] is sum(num_images for samples)
if expand_size == 1:
return input_ids, model_kwargs
visual_keys = ["pixel_values", "image_grid_thw", "pixel_values_videos", "video_grid_thw", "second_per_grid_ts"]
def _expand_dict_for_generation_visual(dict_to_expand):
image_grid_thw = model_kwargs.get("image_grid_thw", None)
video_grid_thw = model_kwargs.get("video_grid_thw", None)
image_nums, video_nums = self._get_image_nums_and_video_nums(
input_ids, inputs_embeds=model_kwargs.get("inputs_embeds", None)
)
def _repeat_interleave_samples(x, lengths, repeat_times):
samples = torch.split(x, lengths)
repeat_args = [repeat_times] + [1] * (x.dim() - 1)
result = torch.cat([sample.repeat(*repeat_args) for sample in samples], dim=0)
return result
for key in dict_to_expand:
if key == "pixel_values":
# split images into samples
samples = torch.split(image_grid_thw, list(image_nums))
# compute the sequence length of images for each sample
lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
dict_to_expand[key] = _repeat_interleave_samples(
dict_to_expand[key], lengths=lengths, repeat_times=expand_size
)
elif key == "image_grid_thw":
# get the num of images for each sample
lengths = list(image_nums)
dict_to_expand[key] = _repeat_interleave_samples(
dict_to_expand[key], lengths=lengths, repeat_times=expand_size
)
elif key == "pixel_values_videos":
samples = torch.split(video_grid_thw, list(video_nums))
lengths = [torch.prod(sample, dim=1).sum() for sample in samples]
dict_to_expand[key] = _repeat_interleave_samples(
dict_to_expand[key], lengths=lengths, repeat_times=expand_size
)
elif key == "video_grid_thw":
lengths = list(video_nums)
dict_to_expand[key] = _repeat_interleave_samples(
dict_to_expand[key], lengths=lengths, repeat_times=expand_size
)
elif key == "second_per_grid_ts":
dict_to_expand[key] = _repeat_interleave_samples(
dict_to_expand[key], lengths=list(video_nums), repeat_times=expand_size
)
return dict_to_expand
def _expand_dict_for_generation(dict_to_expand):
for key in dict_to_expand:
if (
key != "cache_position"
and dict_to_expand[key] is not None
and isinstance(dict_to_expand[key], torch.Tensor)
and key not in visual_keys
):
dict_to_expand[key] = dict_to_expand[key].repeat_interleave(expand_size, dim=0)
return dict_to_expand
model_kwargs = _expand_dict_for_generation_visual(model_kwargs)
if input_ids is not None:
input_ids = input_ids.repeat_interleave(expand_size, dim=0)
model_kwargs = _expand_dict_for_generation(model_kwargs)
if is_encoder_decoder:
if model_kwargs.get("encoder_outputs") is None:
raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.")
model_kwargs["encoder_outputs"] = _expand_dict_for_generation(model_kwargs["encoder_outputs"])
return input_ids, model_kwargs
__all__ = ["Glm4vForConditionalGeneration", "Glm4vModel", "Glm4vPreTrainedModel", "Glm4vTextModel", "Glm4vVisionModel"]
| Glm4vForConditionalGeneration |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_autofit12.py | {
"start": 315,
"end": 1307
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("autofit12.xlsx")
self.ignore_files = [
"xl/calcChain.xml",
"[Content_Types].xml",
"xl/_rels/workbook.xml.rels",
]
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.write_array_formula(0, 0, 2, 0, "{=SUM(B1:C1*B2:C2)}", None, 1000)
worksheet.write(0, 1, 20)
worksheet.write(1, 1, 30)
worksheet.write(2, 1, 40)
worksheet.write(0, 2, 10)
worksheet.write(1, 2, 40)
worksheet.write(2, 2, 20)
worksheet.autofit()
worksheet.write(1, 0, 1000)
worksheet.write(2, 0, 1000)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | django__django | tests/proxy_model_inheritance/app1/models.py | {
"start": 36,
"end": 102
} | class ____(NiceModel):
class Meta:
proxy = True
| ProxyModel |
python | django__django | tests/auth_tests/test_auth_backends.py | {
"start": 24329,
"end": 25171
} | class ____(BaseModelBackendTest, TestCase):
"""
Tests for the ModelBackend using the CustomPermissionsUser model.
As with the ExtensionUser test, this isn't a perfect test, because both
the User and CustomPermissionsUser are synchronized to the database,
which wouldn't ordinary happen in production.
"""
UserModel = CustomPermissionsUser
def create_users(self):
self.user = CustomPermissionsUser._default_manager.create_user(
email="test@example.com", password="test", date_of_birth=date(2006, 4, 25)
)
self.superuser = CustomPermissionsUser._default_manager.create_superuser(
email="test2@example.com", password="test", date_of_birth=date(1976, 11, 8)
)
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUser")
| CustomPermissionsUserModelBackendTest |
python | ansible__ansible | lib/ansible/_internal/_templating/_jinja_bits.py | {
"start": 17404,
"end": 23455
} | class ____(Lexer):
"""
Lexer override to escape backslashes in string constants within Jinja expressions; prevents Jinja from double-escaping them.
NOTE: This behavior is only applied to string constants within Jinja expressions (eg {{ "c:\newfile" }}), *not* statements ("{% set foo="c:\\newfile" %}").
This is useful when templates are sourced from YAML double-quoted strings, as it avoids having backslashes processed twice: first by the
YAML parser, and then again by the Jinja parser. Instead, backslashes are only processed by YAML.
Example YAML:
- debug:
msg: "Test Case 1\\3; {{ test1_name | regex_replace('^(.*)_name$', '\\1')}}"
Since the outermost YAML string is double-quoted, the YAML parser converts the double backslashes to single backslashes. Without escaping, Jinja
would see only a single backslash ('\1') while processing the embedded template expression, interpret it as an escape sequence, and convert it
to '\x01' (ASCII "SOH"). This is clearly not the intended `\1` backreference argument to the `regex_replace` filter (which would require the
double-escaped string '\\\\1' to yield the intended result).
Since the "\\3" in the input YAML was not part of a template expression, the YAML-parsed "\3" remains after Jinja rendering. This would be
confusing for playbook authors, as different escaping rules would be needed inside and outside the template expression.
When templates are not sourced from YAML, escaping backslashes will prevent use of backslash escape sequences such as "\n" and "\t".
See relevant Jinja lexer impl at e.g.: https://github.com/pallets/jinja/blob/3.1.2/src/jinja2/lexer.py#L646-L653.
"""
def tokeniter(self, *args, **kwargs) -> t.Iterator[t.Tuple[int, str, str]]:
"""Pre-escape backslashes in expression ({{ }}) raw string constants before Jinja's Lexer.wrap() can interpret them as ASCII escape sequences."""
token_stream = super().tokeniter(*args, **kwargs)
# if we have no context, Jinja's doing a nested compile at runtime (eg, import/include); historically, no backslash escaping is performed
if not (tcc := _TemplateCompileContext.current(optional=True)) or not tcc.escape_backslashes:
yield from token_stream
return
in_variable = False
for token in token_stream:
token_type = token[1]
if token_type == TOKEN_VARIABLE_BEGIN:
in_variable = True
elif token_type == TOKEN_VARIABLE_END:
in_variable = False
elif in_variable and token_type == TOKEN_STRING:
token = token[0], token_type, token[2].replace('\\', '\\\\')
yield token
def defer_template_error(ex: Exception, variable: t.Any, *, is_expression: bool) -> Marker:
if not ex.__traceback__:
raise AssertionError('ex must be a previously raised exception')
if isinstance(ex, MarkerError):
return ex.source
exception_to_raise = create_template_error(ex, variable, is_expression)
if exception_to_raise is ex:
return CapturedExceptionMarker(ex) # capture the previously raised exception
try:
raise exception_to_raise from ex # raise the newly synthesized exception before capturing it
except Exception as captured_ex:
return CapturedExceptionMarker(captured_ex)
def create_template_error(ex: Exception, variable: t.Any, is_expression: bool) -> AnsibleTemplateError:
if isinstance(ex, AnsibleTemplateError):
exception_to_raise = ex
else:
kind = "expression" if is_expression else "template"
ex_type = AnsibleTemplateError # always raise an AnsibleTemplateError/subclass
if isinstance(ex, RecursionError):
msg = f"Recursive loop detected in {kind}."
elif isinstance(ex, TemplateSyntaxError):
if (origin := Origin.get_tag(variable)) and origin.line_num is None and ex.lineno > 0:
# When there is an origin without a line number, use the line number provided by the Jinja syntax error.
# This should only occur on templates which represent the entire contents of a file.
# Templates loaded from within a file, such as YAML, will use the existing origin.
# It's not possible to combine origins here, due to potential layout differences between the original content and the parsed output.
# This can happen, for example, with YAML multi-line strings.
variable = origin.replace(line_num=ex.lineno, col_num=None).tag(variable)
msg = f"Syntax error in {kind}."
if is_expression and is_possibly_template(variable):
msg += " Template delimiters are not supported in expressions."
ex_type = AnsibleTemplateSyntaxError
else:
msg = f"Error rendering {kind}."
exception_to_raise = ex_type(msg, obj=variable)
if exception_to_raise.obj is None:
exception_to_raise.obj = TemplateContext.current().template_value
# DTFIX-FUTURE: Look through the TemplateContext hierarchy to find the most recent non-template
# caller and use that for origin when no origin is available on obj. This could be useful for situations where the template
# was embedded in a plugin, or a plugin is otherwise responsible for losing the origin and/or trust. We can't just use the first
# non-template caller as that will lead to false positives for re-entrant calls (e.g. template plugins that call into templar).
return exception_to_raise
_BUILTIN_FILTER_ALIASES: dict[str, str] = {}
_BUILTIN_TEST_ALIASES: dict[str, str] = {
'!=': 'ne',
'<': 'lt',
'<=': 'le',
'==': 'eq',
'>': 'gt',
'>=': 'ge',
}
_BUILTIN_FILTERS = filter_loader._wrap_funcs(defaults.DEFAULT_FILTERS, _BUILTIN_FILTER_ALIASES)
_BUILTIN_TESTS = test_loader._wrap_funcs(t.cast(dict[str, t.Callable], defaults.DEFAULT_TESTS), _BUILTIN_TEST_ALIASES)
| AnsibleLexer |
python | ray-project__ray | python/ray/autoscaler/v2/tests/test_reconciler.py | {
"start": 1542,
"end": 2742
} | class ____:
def __init__(self, configs=None):
if configs is None:
configs = {}
self._configs = configs
def get_node_type_configs(self):
return self._configs.get("node_type_configs", {})
def get_max_num_worker_nodes(self):
return self._configs.get("max_num_worker_nodes")
def get_max_num_nodes(self):
n = self._configs.get("max_num_worker_nodes")
return n + 1 if n is not None else None
def get_upscaling_speed(self):
return self._configs.get("upscaling_speed", 0.0)
def get_max_concurrent_launches(self):
return self._configs.get("max_concurrent_launches", 100)
def get_instance_reconcile_config(self):
return self._configs.get("instance_reconcile_config", InstanceReconcileConfig())
def disable_node_updaters(self):
return self._configs.get("disable_node_updaters", True)
def disable_launch_config_check(self):
return self._configs.get("disable_launch_config_check", False)
def get_idle_timeout_s(self):
return self._configs.get("idle_timeout_s", 999)
@property
def provider(self):
return Provider.UNKNOWN
| MockAutoscalingConfig |
python | ijl__orjson | test/test_dataclass.py | {
"start": 381,
"end": 474
} | class ____:
name: str
number: int
sub: Optional["Dataclass1"]
@dataclass
| Dataclass1 |
python | kamyu104__LeetCode-Solutions | Python/minimum-unlocked-indices-to-sort-nums.py | {
"start": 36,
"end": 564
} | class ____(object):
def minUnlockedIndices(self, nums, locked):
"""
:type nums: List[int]
:type locked: List[int]
:rtype: int
"""
result = mx = cnt = 0
for i in xrange(len(nums)):
if mx < nums[i]:
mx = nums[i]
cnt = 0
elif mx > nums[i]:
if mx != nums[i]+1:
return -1
result += cnt
cnt = 0
cnt += locked[i]
return result
| Solution |
python | django__django | django/test/utils.py | {
"start": 18467,
"end": 20458
} | class ____(override_settings):
"""
Like override_settings, but makes it possible to append, prepend, or remove
items instead of redefining the entire list.
"""
def __init__(self, *args, **kwargs):
if args:
# Hack used when instantiating from SimpleTestCase.setUpClass.
assert not kwargs
self.operations = args[0]
else:
assert not args
self.operations = list(kwargs.items())
super(override_settings, self).__init__()
def save_options(self, test_func):
if test_func._modified_settings is None:
test_func._modified_settings = self.operations
else:
# Duplicate list to prevent subclasses from altering their parent.
test_func._modified_settings = (
list(test_func._modified_settings) + self.operations
)
def enable(self):
self.options = {}
for name, operations in self.operations:
try:
# When called from SimpleTestCase.setUpClass, values may be
# overridden several times; cumulate changes.
value = self.options[name]
except KeyError:
value = list(getattr(settings, name, []))
for action, items in operations.items():
# items may be a single value or an iterable.
if isinstance(items, str):
items = [items]
if action == "append":
value += [item for item in items if item not in value]
elif action == "prepend":
value = [item for item in items if item not in value] + value
elif action == "remove":
value = [item for item in value if item not in items]
else:
raise ValueError("Unsupported action: %s" % action)
self.options[name] = value
super().enable()
| modify_settings |
python | plotly__plotly.py | plotly/graph_objs/scatterternary/_line.py | {
"start": 233,
"end": 8438
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterternary"
_path_str = "scatterternary.line"
_valid_props = {
"backoff",
"backoffsrc",
"color",
"dash",
"shape",
"smoothing",
"width",
}
@property
def backoff(self):
"""
Sets the line back off from the end point of the nth line
segment (in px). This option is useful e.g. to avoid overlap
with arrowhead markers. With "auto" the lines would trim before
markers if `marker.angleref` is set to "previous".
The 'backoff' property is a number and may be specified as:
- An int or float in the interval [0, inf]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|float|numpy.ndarray
"""
return self["backoff"]
@backoff.setter
def backoff(self, val):
self["backoff"] = val
@property
def backoffsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `backoff`.
The 'backoffsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["backoffsrc"]
@backoffsrc.setter
def backoffsrc(self, val):
self["backoffsrc"] = val
@property
def color(self):
"""
Sets the line color.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def dash(self):
"""
Sets the dash style of lines. Set to a dash type string
("solid", "dot", "dash", "longdash", "dashdot", or
"longdashdot") or a dash length list in px (eg
"5px,10px,2px,2px").
The 'dash' property is an enumeration that may be specified as:
- One of the following dash styles:
['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot']
- A string containing a dash length list in pixels or percentages
(e.g. '5px 10px 2px 2px', '5, 10, 2, 2', '10% 20% 40%', etc.)
Returns
-------
str
"""
return self["dash"]
@dash.setter
def dash(self, val):
self["dash"] = val
@property
def shape(self):
"""
Determines the line shape. With "spline" the lines are drawn
using spline interpolation. The other available values
correspond to step-wise line shapes.
The 'shape' property is an enumeration that may be specified as:
- One of the following enumeration values:
['linear', 'spline']
Returns
-------
Any
"""
return self["shape"]
@shape.setter
def shape(self, val):
self["shape"] = val
@property
def smoothing(self):
"""
Has an effect only if `shape` is set to "spline" Sets the
amount of smoothing. 0 corresponds to no smoothing (equivalent
to a "linear" shape).
The 'smoothing' property is a number and may be specified as:
- An int or float in the interval [0, 1.3]
Returns
-------
int|float
"""
return self["smoothing"]
@smoothing.setter
def smoothing(self, val):
self["smoothing"] = val
@property
def width(self):
"""
Sets the line width (in px).
The 'width' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["width"]
@width.setter
def width(self, val):
self["width"] = val
@property
def _prop_descriptions(self):
return """\
backoff
Sets the line back off from the end point of the nth
line segment (in px). This option is useful e.g. to
avoid overlap with arrowhead markers. With "auto" the
lines would trim before markers if `marker.angleref` is
set to "previous".
backoffsrc
Sets the source reference on Chart Studio Cloud for
`backoff`.
color
Sets the line color.
dash
Sets the dash style of lines. Set to a dash type string
("solid", "dot", "dash", "longdash", "dashdot", or
"longdashdot") or a dash length list in px (eg
"5px,10px,2px,2px").
shape
Determines the line shape. With "spline" the lines are
drawn using spline interpolation. The other available
values correspond to step-wise line shapes.
smoothing
Has an effect only if `shape` is set to "spline" Sets
the amount of smoothing. 0 corresponds to no smoothing
(equivalent to a "linear" shape).
width
Sets the line width (in px).
"""
def __init__(
self,
arg=None,
backoff=None,
backoffsrc=None,
color=None,
dash=None,
shape=None,
smoothing=None,
width=None,
**kwargs,
):
"""
Construct a new Line object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatterternary.Line`
backoff
Sets the line back off from the end point of the nth
line segment (in px). This option is useful e.g. to
avoid overlap with arrowhead markers. With "auto" the
lines would trim before markers if `marker.angleref` is
set to "previous".
backoffsrc
Sets the source reference on Chart Studio Cloud for
`backoff`.
color
Sets the line color.
dash
Sets the dash style of lines. Set to a dash type string
("solid", "dot", "dash", "longdash", "dashdot", or
"longdashdot") or a dash length list in px (eg
"5px,10px,2px,2px").
shape
Determines the line shape. With "spline" the lines are
drawn using spline interpolation. The other available
values correspond to step-wise line shapes.
smoothing
Has an effect only if `shape` is set to "spline" Sets
the amount of smoothing. 0 corresponds to no smoothing
(equivalent to a "linear" shape).
width
Sets the line width (in px).
Returns
-------
Line
"""
super().__init__("line")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.scatterternary.Line
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatterternary.Line`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("backoff", arg, backoff)
self._set_property("backoffsrc", arg, backoffsrc)
self._set_property("color", arg, color)
self._set_property("dash", arg, dash)
self._set_property("shape", arg, shape)
self._set_property("smoothing", arg, smoothing)
self._set_property("width", arg, width)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Line |
python | allegroai__clearml | clearml/backend_api/services/v2_13/projects.py | {
"start": 9823,
"end": 13131
} | class ____(NonStrictDataModel):
"""
:param total_runtime: Total run time of all tasks in project (in seconds)
:type total_runtime: int
:param status_count: Status counts
:type status_count: dict
"""
_schema = {
"properties": {
"status_count": {
"description": "Status counts",
"properties": {
"closed": {
"description": "Number of 'closed' tasks in project",
"type": "integer",
},
"created": {
"description": "Number of 'created' tasks in project",
"type": "integer",
},
"failed": {
"description": "Number of 'failed' tasks in project",
"type": "integer",
},
"in_progress": {
"description": "Number of 'in_progress' tasks in project",
"type": "integer",
},
"published": {
"description": "Number of 'published' tasks in project",
"type": "integer",
},
"queued": {
"description": "Number of 'queued' tasks in project",
"type": "integer",
},
"stopped": {
"description": "Number of 'stopped' tasks in project",
"type": "integer",
},
"unknown": {
"description": "Number of 'unknown' tasks in project",
"type": "integer",
},
},
"type": ["object", "null"],
},
"total_runtime": {
"description": "Total run time of all tasks in project (in seconds)",
"type": ["integer", "null"],
},
},
"type": "object",
}
def __init__(self, total_runtime: Optional[int] = None, status_count: Optional[dict] = None, **kwargs: Any) -> None:
super(StatsStatusCount, self).__init__(**kwargs)
self.total_runtime = total_runtime
self.status_count = status_count
@schema_property("total_runtime")
def total_runtime(self) -> Optional[int]:
return self._property_total_runtime
@total_runtime.setter
def total_runtime(self, value: Optional[int]) -> None:
if value is None:
self._property_total_runtime = None
return
if isinstance(value, float) and value.is_integer():
value = int(value)
self.assert_isinstance(value, "total_runtime", six.integer_types)
self._property_total_runtime = value
@schema_property("status_count")
def status_count(self) -> Optional[dict]:
return self._property_status_count
@status_count.setter
def status_count(self, value: Optional[dict]) -> None:
if value is None:
self._property_status_count = None
return
self.assert_isinstance(value, "status_count", (dict,))
self._property_status_count = value
| StatsStatusCount |
python | rq__rq | tests/test_cli.py | {
"start": 31948,
"end": 34857
} | class ____(CLITestCase):
def test_worker_pool_burst_and_num_workers(self):
"""rq worker-pool -u <url> -b -n 3"""
runner = CliRunner()
result = runner.invoke(main, ['worker-pool', '-u', self.redis_url, '-b', '-n', '3'])
self.assert_normal_execution(result)
def test_serializer_and_queue_argument(self):
"""rq worker-pool foo bar -u <url> -b"""
queue = Queue('foo', connection=self.connection, serializer=JSONSerializer)
job = queue.enqueue(say_hello, 'Hello')
queue = Queue('bar', connection=self.connection, serializer=JSONSerializer)
job_2 = queue.enqueue(say_hello, 'Hello')
runner = CliRunner()
runner.invoke(
main,
['worker-pool', 'foo', 'bar', '-u', self.redis_url, '-b', '--serializer', 'rq.serializers.JSONSerializer'],
)
self.assertEqual(job.get_status(refresh=True), JobStatus.FINISHED)
self.assertEqual(job_2.get_status(refresh=True), JobStatus.FINISHED)
def test_worker_class_argument(self):
"""rq worker-pool -u <url> -b --worker-class rq.Worker"""
runner = CliRunner()
result = runner.invoke(main, ['worker-pool', '-u', self.redis_url, '-b', '--worker-class', 'rq.Worker'])
self.assert_normal_execution(result)
result = runner.invoke(
main, ['worker-pool', '-u', self.redis_url, '-b', '--worker-class', 'rq.worker.SimpleWorker']
)
self.assert_normal_execution(result)
# This one fails because the worker class doesn't exist
result = runner.invoke(
main, ['worker-pool', '-u', self.redis_url, '-b', '--worker-class', 'rq.worker.NonExistantWorker']
)
self.assertNotEqual(result.exit_code, 0)
def test_job_class_argument(self):
"""rq worker-pool -u <url> -b --job-class rq.job.Job"""
runner = CliRunner()
result = runner.invoke(main, ['worker-pool', '-u', self.redis_url, '-b', '--job-class', 'rq.job.Job'])
self.assert_normal_execution(result)
# This one fails because Job class doesn't exist
result = runner.invoke(
main, ['worker-pool', '-u', self.redis_url, '-b', '--job-class', 'rq.job.NonExistantJob']
)
self.assertNotEqual(result.exit_code, 0)
def test_worker_pool_logging_options(self):
"""--quiet and --verbose logging options are supported"""
runner = CliRunner()
args = ['worker-pool', '-u', self.redis_url, '-b']
result = runner.invoke(main, args + ['--verbose'])
self.assert_normal_execution(result)
result = runner.invoke(main, args + ['--quiet'])
self.assert_normal_execution(result)
# --quiet and --verbose are mutually exclusive
result = runner.invoke(main, args + ['--quiet', '--verbose'])
self.assertNotEqual(result.exit_code, 0)
| WorkerPoolCLITestCase |
python | kamyu104__LeetCode-Solutions | Python/move-sub-tree-of-n-ary-tree.py | {
"start": 54,
"end": 251
} | class ____(object):
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
# one pass solution without recursion
| Node |
python | realpython__materials | python-protocol/adder_v3.py | {
"start": 30,
"end": 125
} | class ____(Protocol):
def add(self, x: int | float, y: int | float) -> int | float: ...
| Adder |
python | getsentry__sentry | tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py | {
"start": 756,
"end": 2127
} | class ____(TestCase):
BASE_PATH = "fixtures.safe_migrations_apps"
# abstract
app: str
migrate_from: str
migrate_to: str
def run_migration(self):
self._run_migration(self.app, self.migrate_from)
self._run_migration(self.app, self.migrate_to)
def _run_migration(self, app, migration_name):
with override_settings(
INSTALLED_APPS=(f"{self.BASE_PATH}.{self.app}",), MIGRATION_MODULES={}
):
executor = MigrationExecutor(connection)
migration = executor.loader.get_migration_by_prefix(app, migration_name)
executor.loader.build_graph()
target = [(migration.app_label, migration.name)]
executor.loader.project_state(target).apps
executor.migrate(target)
def sql_migrate(self, app, migration_name):
with override_settings(
INSTALLED_APPS=(f"{self.BASE_PATH}.{self.app}",), MIGRATION_MODULES={}
):
executor = MigrationExecutor(connection)
migration = executor.loader.get_migration_by_prefix(app, migration_name)
target = (app, migration.name)
plan = [(executor.loader.graph.nodes[target], None)]
sql_statements = executor.loader.collect_sql(plan) # type: ignore[attr-defined]
return "\n".join(sql_statements)
| BaseSafeMigrationTest |
python | ray-project__ray | python/ray/air/util/tensor_extensions/arrow.py | {
"start": 20005,
"end": 23552
} | class ____(
ArrowExtensionSerializeDeserializeCache, pa.ExtensionType
):
"""
Arrow ExtensionType for an array of fixed-shaped, homogeneous-typed
tensors.
This is the Arrow side of TensorDtype.
See Arrow extension type docs:
https://arrow.apache.org/docs/python/extending_types.html#defining-extension-types-user-defined-types
"""
def __init__(
self, shape: Tuple[int, ...], tensor_dtype: pa.DataType, ext_type_id: str
):
self._shape = shape
super().__init__(tensor_dtype, ext_type_id)
@property
def shape(self) -> Tuple[int, ...]:
"""
Shape of contained tensors.
"""
return self._shape
@property
def scalar_type(self) -> pa.DataType:
"""Returns the type of the underlying tensor elements."""
return self.storage_type.value_type
def to_pandas_dtype(self):
"""
Convert Arrow extension type to corresponding Pandas dtype.
Returns:
An instance of pd.api.extensions.ExtensionDtype.
"""
from ray.air.util.tensor_extensions.pandas import TensorDtype
return TensorDtype(self._shape, self.scalar_type.to_pandas_dtype())
def __reduce__(self):
return self.__arrow_ext_deserialize__, (
self.storage_type,
self.__arrow_ext_serialize__(),
)
def _arrow_ext_serialize_compute(self):
if ARROW_EXTENSION_SERIALIZATION_FORMAT == _SerializationFormat.CLOUDPICKLE:
return cloudpickle.dumps(self._shape)
elif ARROW_EXTENSION_SERIALIZATION_FORMAT == _SerializationFormat.JSON:
return json.dumps(self._shape).encode()
else:
raise ValueError(
f"Invalid serialization format: {ARROW_EXTENSION_SERIALIZATION_FORMAT}"
)
def __arrow_ext_class__(self):
"""
ExtensionArray subclass with custom logic for this array of tensors
type.
Returns:
A subclass of pd.api.extensions.ExtensionArray.
"""
return ArrowTensorArray
def __arrow_ext_scalar_class__(self):
"""
ExtensionScalar subclass with custom logic for this array of tensors type.
"""
return ArrowTensorScalar
def _extension_scalar_to_ndarray(self, scalar: "pa.ExtensionScalar") -> np.ndarray:
"""
Convert an ExtensionScalar to a tensor element.
"""
# Handle None/null values
if scalar.value is None:
return None
raw_values = scalar.value.values
shape = scalar.type.shape
value_type = raw_values.type
offset = raw_values.offset
data_buffer = raw_values.buffers()[1]
return _to_ndarray_helper(shape, value_type, offset, data_buffer)
def __str__(self) -> str:
return f"{self.__class__.__name__}(shape={self.shape}, dtype={self.storage_type.value_type})"
def __repr__(self) -> str:
return str(self)
def __eq__(self, other):
return (
isinstance(other, type(self))
and other.extension_name == self.extension_name
and other.shape == self.shape
and other.scalar_type == self.scalar_type
)
def __ne__(self, other):
# NOTE: We override ``__ne__`` to override base class' method
return not self.__eq__(other)
def __hash__(self) -> int:
return hash((self.extension_name, self.scalar_type, self._shape))
@PublicAPI(stability="beta")
| _BaseFixedShapeArrowTensorType |
python | getsentry__sentry | src/sentry/snuba/outcomes.py | {
"start": 6230,
"end": 7303
} | class ____(Dimension):
def resolve_filter(self, raw_filter: Sequence[str]) -> list[str]:
return [
"smart_rate_limit" if reason == "spike_protection" else reason for reason in raw_filter
]
def map_row(self, row: MutableMapping[str, Any]) -> None:
if "reason" in row:
row["reason"] = (
"spike_protection" if row["reason"] == "smart_rate_limit" else row["reason"]
) # return spike protection to be consistent with naming in other places
COLUMN_MAP = {
"sum(quantity)": QuantityField(),
"sum(times_seen)": TimesSeenField(),
}
DIMENSION_MAP: Mapping[str, Dimension] = {
"outcome": OutcomeDimension("outcome"),
"category": CategoryDimension("category"),
"reason": ReasonDimension("reason"),
"key_id": KeyDimension("key_id"),
}
GROUPBY_MAP = {
**DIMENSION_MAP,
"project": SimpleGroupBy("project_id", "project"),
}
# We don't have any scenarios where we need to group by key right now.
GROUPBY_MAP.pop("key_id")
TS_COL = "time"
ONE_HOUR = 3600
| ReasonDimension |
python | facebook__pyre-check | scripts/tests/compare_pysa_models_to_json_test.py | {
"start": 12645,
"end": 19814
} | class ____(unittest.TestCase):
def test_json_parameters_sources(self) -> None:
with patch("pathlib.Path.open", mock_open(read_data=TEST_JSON_FILE)):
self.assertEqual(
get_models_from_json_file("fakepath"),
{
"foo.bar.baz.loremipsum.FakeClass1.fake_render_function": {
"parameters": {},
"return_model": {
"sources": set(),
"sinks": {"ReturnedToUser"},
"tito": set(),
},
},
"foo.bar.baz.loremipsum.FakeClass2.fake_render_function": {
"parameters": {},
"return_model": {
"sources": set(),
"sinks": {"ReturnedToUser"},
"tito": set(),
},
},
"foo.bar.baz.loremipsum.FakeClass3.fake_render_function": {
"parameters": {},
"return_model": {
"sources": set(),
"sinks": {"ReturnedToUser"},
"tito": set(),
},
},
"foo.bar.baz.loremipsum.FakeClass4.fake_render_function": {
"parameters": {},
"return_model": {
"sources": set(),
"sinks": {"ReturnedToUser"},
"tito": set(),
},
},
"foo.bar.baz.loremipsum.FakeClass5.fake_render_function": {
"parameters": {},
"return_model": {
"sources": set(),
"sinks": {"ReturnedToUser"},
"tito": set(),
},
},
"foo.bar.baz.loremipsum.FakeClass6.Download.get": {
"parameters": {
"fmt": {
"sources": {
"UserControlled_Parameter",
"UserControlled",
},
"sinks": set(),
"tito": set(),
},
"fignum": {
"sources": {
"UserControlled_Parameter",
"UserControlled",
},
"sinks": set(),
"tito": set(),
},
},
"return_model": {
"sources": set(),
"sinks": set(),
"tito": set(),
},
},
"Obj{foo.bar.baz.FakeClass1.a}": {
"parameters": {},
"return_model": {
"sources": {
"UserControlled",
},
"sinks": set(),
"tito": set(),
},
},
"Obj{foo.bar.baz.FakeClass1.b}": {
"parameters": {},
"return_model": {
"sources": {
"UserControlled_Parameter",
"UserControlled",
},
"sinks": set(),
"tito": set(),
},
},
},
)
TEST_PYSA_FILE = """def foo.bar.baz.fake_method1(a, b, c: TaintSource[UserControlled, UserControlled_Parameter]) -> TaintSink[ReturnedToUser]: ...
def foo.bar.baz.fake_method2(a, b: TaintSource[UserControlled, UserControlled_Parameter]) -> TaintSink[ReturnedToUser]: ...
def foo.bar.baz.fake_method3(a, b: TaintSource[UserControlled, UserControlled_Parameter], c: TaintSource[UserControlled, UserControlled_Parameter]) -> TaintSink[ReturnedToUser]: ...
def foo.bar.baz.fake_method4(a, b: TaintSource[UserControlled, UserControlled_Parameter]) -> TaintSink[ReturnedToUser]: ...
foo.bar.baz.FakeClass1.a: TaintSource[UserControlled]
foo.bar.baz.FakeClass1.b: TaintSource[UserControlled, UserControlled_Parameter] = ...
def foo.bar.baz.fake_method5(a, b, c: TaintSource[UserControlled, UserControlled_Parameter], d: TaintSource[UserControlled, UserControlled_Parameter], _e: TaintSource[UserControlled, UserControlled_Parameter], _f: TaintSource[UserControlled, UserControlled_Parameter]) -> TaintSink[ReturnedToUser]: ...
def foo.bar.baz.fake_method6(_a) -> TaintSink[ReturnedToUser]: ...
def foo.bar.baz.fake_method7(a, b, c: TaintSource[UserControlled, UserControlled_Parameter], d: TaintSource[UserControlled, UserControlled_Parameter], e: TaintSource[UserControlled, UserControlled_Parameter], f: TaintSource[UserControlled, UserControlled_Parameter], g: TaintSource[UserControlled, UserControlled_Parameter], h: TaintSource[UserControlled, UserControlled_Parameter], i: TaintSource[UserControlled, UserControlled_Parameter], j: TaintSource[UserControlled, UserControlled_Parameter], k: TaintSource[UserControlled, UserControlled_Parameter], l: TaintSource[UserControlled, UserControlled_Parameter], m: TaintSource[UserControlled, UserControlled_Parameter]) -> TaintSink[ReturnedToUser]: ...
def foo.bar.baz.fake_method8(a, b, c: TaintSource[UserControlled, UserControlled_Parameter], d: TaintSource[UserControlled, UserControlled_Parameter], e: TaintSource[UserControlled, UserControlled_Parameter], f: TaintSource[UserControlled, UserControlled_Parameter], g: TaintSource[UserControlled, UserControlled_Parameter], h: TaintSource[UserControlled, UserControlled_Parameter], i: TaintSource[UserControlled, UserControlled_Parameter], j: TaintSource[UserControlled, UserControlled_Parameter], k: TaintSource[UserControlled, UserControlled_Parameter], l: TaintSource[UserControlled, UserControlled_Parameter], m: TaintSource[UserControlled, UserControlled_Parameter], n: TaintSource[UserControlled, UserControlled_Parameter], o: TaintSource[UserControlled, UserControlled_Parameter], p: TaintSource[UserControlled, UserControlled_Parameter], q: TaintSource[UserControlled, UserControlled_Parameter], r: TaintSource[UserControlled, UserControlled_Parameter], s: TaintSource[UserControlled, UserControlled_Parameter], t: TaintSource[UserControlled, UserControlled_Parameter]) -> TaintSink[ReturnedToUser]: ...
def foo.bar.baz.fake_method9(a, b, c, d) -> TaintSink[ResponseAfterPOSTRateLimit]: ...
def foo.bar.baz.fake_method9(a: TaintSource[UserControlled], b, c: TaintSource[UserControlled], d): ...
"""
| GetModelsFromJsonFileTest |
python | ansible__ansible | lib/ansible/module_utils/facts/system/pkg_mgr.py | {
"start": 2389,
"end": 2704
} | class ____(BaseFactCollector):
name = 'pkg_mgr'
_fact_ids = set() # type: t.Set[str]
_platform = 'OpenBSD'
def collect(self, module=None, collected_facts=None):
return {'pkg_mgr': 'openbsd_pkg'}
# the fact ends up being 'pkg_mgr' so stick with that naming/spelling
| OpenBSDPkgMgrFactCollector |
python | numba__numba | numba/tests/npyufunc/test_vectorize_decor.py | {
"start": 2565,
"end": 3103
} | class ____(unittest.TestCase, CheckWarningsMixin):
"""
Test passing the nopython argument to the vectorize decorator.
"""
def _test_target_nopython(self, target, warnings, with_sig=True):
a = np.array([2.0], dtype=np.float32)
b = np.array([3.0], dtype=np.float32)
sig = [float32(float32, float32)]
args = with_sig and [sig] or []
with self.check_warnings(warnings):
f = vectorize(*args, target=target, nopython=True)(vector_add)
f(a, b)
| BaseVectorizeNopythonArg |
python | pytorch__pytorch | torch/_inductor/codegen/halide.py | {
"start": 1951,
"end": 2095
} | class ____(RuntimeError):
def __init__(self, thing) -> None:
super().__init__(f"halide backend does not support: {thing}")
| Unsupported |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-google-ads/unit_tests/test_streams.py | {
"start": 1839,
"end": 2861
} | class ____(GoogleAds):
count = 0
def parse_single_result(self, schema, result):
return result
def send_request(self, query: str, customer_id: str, login_customer_id: str = "none"):
self.count += 1
if self.count == 1:
return mock_response_1()
else:
return mock_response_2()
def mock_response_fails_1():
yield [
{"segments.date": "2021-01-01", "click_view.gclid": "1"},
{"segments.date": "2021-01-02", "click_view.gclid": "2"},
{"segments.date": "2021-01-03", "click_view.gclid": "3"},
{"segments.date": "2021-01-03", "click_view.gclid": "4"},
]
raise exception
def mock_response_fails_2():
yield [
{"segments.date": "2021-01-03", "click_view.gclid": "3"},
{"segments.date": "2021-01-03", "click_view.gclid": "4"},
{"segments.date": "2021-01-03", "click_view.gclid": "5"},
{"segments.date": "2021-01-03", "click_view.gclid": "6"},
]
raise exception
| MockGoogleAds |
python | ipython__ipython | IPython/core/doctb.py | {
"start": 2149,
"end": 15617
} | class ____(TBTools):
"""
A stripped down version of Verbose TB, simplified to not have too much information when
running doctests
"""
tb_highlight = ""
tb_highlight_style = "default"
tb_offset: int
long_header: bool
include_vars: bool
_mode: str
def __init__(
self,
# TODO: no default ?
theme_name: str = "linux",
call_pdb: bool = False,
ostream: Any = None,
tb_offset: int = 0,
long_header: bool = False,
include_vars: bool = True,
check_cache: Callable[[], None] | None = None,
debugger_cls: type | None = None,
):
"""Specify traceback offset, headers and color scheme.
Define how many frames to drop from the tracebacks. Calling it with
tb_offset=1 allows use of this handler in interpreters which will have
their own code at the top of the traceback (VerboseTB will first
remove that frame before printing the traceback info)."""
assert isinstance(theme_name, str)
super().__init__(
theme_name=theme_name,
call_pdb=call_pdb,
ostream=ostream,
debugger_cls=debugger_cls,
)
self.tb_offset = tb_offset
self.long_header = long_header
self.include_vars = include_vars
# By default we use linecache.checkcache, but the user can provide a
# different check_cache implementation. This was formerly used by the
# IPython kernel for interactive code, but is no longer necessary.
if check_cache is None:
check_cache = linecache.checkcache
self.check_cache = check_cache
self.skip_hidden = True
def format_record(self, frame_info: FrameInfo) -> str:
"""Format a single stack frame"""
assert isinstance(frame_info, FrameInfo)
if isinstance(frame_info._sd, stack_data.RepeatedFrames):
return theme_table[self._theme_name].format(
[
(Token, " "),
(
Token.ExcName,
"[... skipping similar frames: %s]" % frame_info.description,
),
(Token, "\n"),
]
)
indent: str = " " * INDENT_SIZE
assert isinstance(frame_info.lineno, int)
args, varargs, varkw, locals_ = inspect.getargvalues(frame_info.frame)
if frame_info.executing is not None:
func = frame_info.executing.code_qualname()
else:
func = "?"
if func == "<module>":
call = ""
else:
# Decide whether to include variable details or not
var_repr = eqrepr if self.include_vars else nullrepr
try:
scope = inspect.formatargvalues(
args, varargs, varkw, locals_, formatvalue=var_repr
)
assert isinstance(scope, str)
call = theme_table[self._theme_name].format(
[(Token, "in "), (Token.VName, func), (Token.ValEm, scope)]
)
except KeyError:
# This happens in situations like errors inside generator
# expressions, where local variables are listed in the
# line, but can't be extracted from the frame. I'm not
# 100% sure this isn't actually a bug in inspect itself,
# but since there's no info for us to compute with, the
# best we can do is report the failure and move on. Here
# we must *not* call any traceback construction again,
# because that would mess up use of %debug later on. So we
# simply report the failure and move on. The only
# limitation will be that this frame won't have locals
# listed in the call signature. Quite subtle problem...
# I can't think of a good way to validate this in a unit
# test, but running a script consisting of:
# dict( (k,v.strip()) for (k,v) in range(10) )
# will illustrate the error, if this exception catch is
# disabled.
call = theme_table[self._theme_name].format(
[
(Token, "in "),
(Token.VName, func),
(Token.ValEm, "(***failed resolving arguments***)"),
]
)
lvals_toks: list[TokenStream] = []
if self.include_vars:
try:
# we likely want to fix stackdata at some point, but
# still need a workaround.
fibp = frame_info.variables_in_executing_piece
for var in fibp:
lvals_toks.append(
[
(Token, var.name),
(Token, " "),
(Token.ValEm, "= "),
(Token.ValEm, repr(var.value)),
]
)
except Exception:
lvals_toks.append(
[
(
Token,
"Exception trying to inspect frame. No more locals available.",
),
]
)
assert frame_info._sd is not None
result = theme_table[self._theme_name].format(
_tokens_filename(True, frame_info.filename, lineno=frame_info.lineno)
)
result += ", " if call else ""
result += f"{call}\n"
result += theme_table[self._theme_name].format(
_format_traceback_lines(
frame_info.lines,
theme_table[self._theme_name],
self.has_colors,
lvals_toks,
)
)
return result
def prepare_header(self, etype: str) -> str:
width = min(75, get_terminal_size()[0])
head = theme_table[self._theme_name].format(
[
(
Token,
"Traceback (most recent call last):",
),
(Token, " "),
]
)
return head
def format_exception(self, etype: Any, evalue: Any) -> Any:
# Get (safely) a string form of the exception info
try:
etype_str, evalue_str = map(str, (etype, evalue))
except:
# User exception is improperly defined.
etype, evalue = str, sys.exc_info()[:2]
etype_str, evalue_str = map(str, (etype, evalue))
# PEP-678 notes
notes = getattr(evalue, "__notes__", [])
if not isinstance(notes, Sequence) or isinstance(notes, (str, bytes)):
notes = [_safe_string(notes, "__notes__", func=repr)]
# ... and format it
return [
theme_table[self._theme_name].format(
[(Token.ExcName, etype_str), (Token, ": "), (Token, evalue_str)]
),
*(
theme_table[self._theme_name].format([(Token, _safe_string(n, "note"))])
for n in notes
),
]
def format_exception_as_a_whole(
self,
etype: type,
evalue: Optional[BaseException],
etb: Optional[TracebackType],
context: int,
tb_offset: Optional[int],
) -> list[list[str]]:
"""Formats the header, traceback and exception message for a single exception.
This may be called multiple times by Python 3 exception chaining
(PEP 3134).
"""
# some locals
orig_etype = etype
try:
etype = etype.__name__ # type: ignore[assignment]
except AttributeError:
pass
tb_offset = self.tb_offset if tb_offset is None else tb_offset
assert isinstance(tb_offset, int)
head = self.prepare_header(str(etype))
assert context == 1, context
records = self.get_records(etb, context, tb_offset) if etb else []
frames = []
skipped = 0
nskipped = len(records) - 1
frames.append(self.format_record(records[0]))
if nskipped:
frames.append(
theme_table[self._theme_name].format(
[
(Token, "\n"),
(Token, " "),
(Token, "[... %s skipped frames]" % nskipped),
(Token, "\n"),
(Token, "\n"),
]
)
)
formatted_exception = self.format_exception(etype, evalue)
return [[head] + frames + formatted_exception]
def get_records(self, etb: TracebackType, context: int, tb_offset: int) -> Any:
assert context == 1, context
assert etb is not None
context = context - 1
after = context // 2
before = context - after
if self.has_colors:
base_style = theme_table[self._theme_name].as_pygments_style()
style = stack_data.style_with_executing_node(base_style, self.tb_highlight)
formatter = Terminal256Formatter(style=style)
else:
formatter = None
options = stack_data.Options(
before=before,
after=after,
pygments_formatter=formatter,
)
# Let's estimate the amount of code we will have to parse/highlight.
cf: Optional[TracebackType] = etb
max_len = 0
tbs = []
while cf is not None:
try:
mod = inspect.getmodule(cf.tb_frame)
if mod is not None:
mod_name = mod.__name__
root_name, *_ = mod_name.split(".")
if root_name == "IPython":
cf = cf.tb_next
continue
max_len = get_line_number_of_frame(cf.tb_frame)
except OSError:
max_len = 0
max_len = max(max_len, max_len)
tbs.append(cf)
cf = getattr(cf, "tb_next", None)
res = list(stack_data.FrameInfo.stack_data(etb, options=options))[tb_offset:]
res2 = [FrameInfo._from_stack_data_FrameInfo(r) for r in res]
return res2
def structured_traceback(
self,
etype: type,
evalue: Optional[BaseException],
etb: Optional[TracebackType] = None,
tb_offset: Optional[int] = None,
context: int = 1,
) -> list[str]:
"""Return a nice text document describing the traceback."""
assert context > 0
assert context == 1, context
formatted_exceptions: list[list[str]] = self.format_exception_as_a_whole(
etype, evalue, etb, context, tb_offset
)
termsize = min(75, get_terminal_size()[0])
theme = theme_table[self._theme_name]
structured_traceback_parts: list[str] = []
chained_exceptions_tb_offset = 0
lines_of_context = 3
exception = self.get_parts_of_chained_exception(evalue)
if exception:
assert evalue is not None
formatted_exceptions += self.prepare_chained_exception_message(
evalue.__cause__
)
etype, evalue, etb = exception
else:
evalue = None
chained_exc_ids = set()
while evalue:
formatted_exceptions += self.format_exception_as_a_whole(
etype, evalue, etb, lines_of_context, chained_exceptions_tb_offset
)
exception = self.get_parts_of_chained_exception(evalue)
if exception and id(exception[1]) not in chained_exc_ids:
chained_exc_ids.add(
id(exception[1])
) # trace exception to avoid infinite 'cause' loop
formatted_exceptions += self.prepare_chained_exception_message(
evalue.__cause__
)
etype, evalue, etb = exception
else:
evalue = None
# we want to see exceptions in a reversed order:
# the first exception should be on top
for fx in reversed(formatted_exceptions):
structured_traceback_parts += fx
return structured_traceback_parts
def debugger(self, force: bool = False) -> None:
raise RuntimeError("canot rundebugger in Docs mode")
def handler(self, info: tuple[Any, Any, Any] | None = None) -> None:
(etype, evalue, etb) = info or sys.exc_info()
self.tb = etb
ostream = self.ostream
ostream.flush()
ostream.write(self.text(etype, evalue, etb)) # type:ignore[arg-type]
ostream.write("\n")
ostream.flush()
# Changed so an instance can just be called as VerboseTB_inst() and print
# out the right info on its own.
def __call__(self, etype: Any = None, evalue: Any = None, etb: Any = None) -> None:
"""This hook can replace sys.excepthook (for Python 2.1 or higher)."""
if etb is None:
self.handler()
else:
self.handler((etype, evalue, etb))
try:
self.debugger()
except KeyboardInterrupt:
print("\nKeyboardInterrupt")
| DocTB |
python | apache__airflow | airflow-core/tests/unit/utils/test_process_utils.py | {
"start": 6484,
"end": 7953
} | class ____:
def test_should_update_variable_and_restore_state_when_exit(self):
with mock.patch.dict("os.environ", {"TEST_NOT_EXISTS": "BEFORE", "TEST_EXISTS": "BEFORE"}):
del os.environ["TEST_NOT_EXISTS"]
assert os.environ["TEST_EXISTS"] == "BEFORE"
assert "TEST_NOT_EXISTS" not in os.environ
with process_utils.patch_environ({"TEST_NOT_EXISTS": "AFTER", "TEST_EXISTS": "AFTER"}):
assert os.environ["TEST_NOT_EXISTS"] == "AFTER"
assert os.environ["TEST_EXISTS"] == "AFTER"
assert os.environ["TEST_EXISTS"] == "BEFORE"
assert "TEST_NOT_EXISTS" not in os.environ
def test_should_restore_state_when_exception(self):
with mock.patch.dict("os.environ", {"TEST_NOT_EXISTS": "BEFORE", "TEST_EXISTS": "BEFORE"}):
del os.environ["TEST_NOT_EXISTS"]
assert os.environ["TEST_EXISTS"] == "BEFORE"
assert "TEST_NOT_EXISTS" not in os.environ
with suppress(AirflowException):
with process_utils.patch_environ({"TEST_NOT_EXISTS": "AFTER", "TEST_EXISTS": "AFTER"}):
assert os.environ["TEST_NOT_EXISTS"] == "AFTER"
assert os.environ["TEST_EXISTS"] == "AFTER"
raise AirflowException("Unknown exception")
assert os.environ["TEST_EXISTS"] == "BEFORE"
assert "TEST_NOT_EXISTS" not in os.environ
| TestPatchEnviron |
python | pola-rs__polars | py-polars/src/polars/io/iceberg/dataset.py | {
"start": 17813,
"end": 18005
} | class ____(ABC):
@abstractmethod
def to_lazyframe(self) -> pl.LazyFrame: ...
@property
@abstractmethod
def snapshot_id_key(self) -> str: ...
@dataclass
| _ResolvedScanDataBase |
python | openai__openai-python | src/openai/types/responses/response_output_message_param.py | {
"start": 499,
"end": 1148
} | class ____(TypedDict, total=False):
id: Required[str]
"""The unique ID of the output message."""
content: Required[Iterable[Content]]
"""The content of the output message."""
role: Required[Literal["assistant"]]
"""The role of the output message. Always `assistant`."""
status: Required[Literal["in_progress", "completed", "incomplete"]]
"""The status of the message input.
One of `in_progress`, `completed`, or `incomplete`. Populated when input items
are returned via API.
"""
type: Required[Literal["message"]]
"""The type of the output message. Always `message`."""
| ResponseOutputMessageParam |
python | vyperlang__vyper | vyper/semantics/types/subscriptable.py | {
"start": 3192,
"end": 4794
} | class ____(_SubscriptableT):
"""
Private base class for sequence types (i.e., index is an int)
Arguments
---------
length : int
Number of items in the type.
"""
_equality_attrs: tuple = ("value_type", "length")
_is_array_type: bool = True
def __init__(self, value_type: VyperType, length: int):
if not 0 < length < 2**256:
raise InvalidType("Array length is invalid")
if length >= 2**64:
vyper_warn(VyperWarning("Use of large arrays can be unsafe!"))
super().__init__(UINT256_T, value_type)
self.length = length
@property
def count(self):
"""
Alias for API compatibility
"""
return self.length
def validate_index_type(self, node):
# TODO break this cycle
from vyper.semantics.analysis.utils import validate_expected_type
node = node.reduced()
if isinstance(node, vy_ast.Int):
if node.value < 0:
raise ArrayIndexException("Vyper does not support negative indexing", node)
if node.value >= self.length:
raise ArrayIndexException("Index out of range", node)
validate_expected_type(node, IntegerT.any())
def get_subscripted_type(self, node):
return self.value_type
# override value at `k` with `val`, but inserting it before other keys
# for formatting reasons. besides insertion order, equivalent to
# `{k: val, **xs}`
def _set_first_key(xs: Dict[str, Any], k: str, val: Any) -> dict:
xs.pop(k, None)
return {k: val, **xs}
| _SequenceT |
python | nryoung__algorithms | tests/test_shuffling.py | {
"start": 225,
"end": 617
} | class ____(ShufflingAlgorithmTestCase):
"""
Tests Knuth shuffle on a small range from 0-9
"""
def test_knuthshuffle(self):
self.shuffle = knuth.shuffle(list(range(10)))
self.not_shuffled = 0
for i in self.sorted:
if i == self.shuffle[i]:
self.not_shuffled += 1
self.assertGreater(5, self.not_shuffled)
| TestKnuthShuffle |
python | numba__numba | numba/core/untyped_passes.py | {
"start": 71669,
"end": 72088
} | class ____(FunctionPass):
"""Perform CFG simplification"""
_name = "simplify_cfg"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
blks = state.func_ir.blocks
new_blks = simplify_CFG(blks)
state.func_ir.blocks = new_blks
mutated = blks != new_blks
return mutated
@register_pass(mutates_CFG=False, analysis_only=False)
| SimplifyCFG |
python | getsentry__sentry-python | sentry_sdk/integrations/grpc/aio/client.py | {
"start": 384,
"end": 1283
} | class ____:
@staticmethod
def _update_client_call_details_metadata_from_scope(
client_call_details: ClientCallDetails,
) -> ClientCallDetails:
if client_call_details.metadata is None:
client_call_details = client_call_details._replace(metadata=Metadata())
elif not isinstance(client_call_details.metadata, Metadata):
# This is a workaround for a GRPC bug, which was fixed in grpcio v1.60.0
# See https://github.com/grpc/grpc/issues/34298.
client_call_details = client_call_details._replace(
metadata=Metadata.from_tuple(client_call_details.metadata)
)
for (
key,
value,
) in sentry_sdk.get_current_scope().iter_trace_propagation_headers():
client_call_details.metadata.add(key, value)
return client_call_details
| ClientInterceptor |
python | davidhalter__jedi | jedi/inference/gradual/generics.py | {
"start": 1209,
"end": 2702
} | class ____(_AbstractGenericManager):
def __init__(self, context_of_index, index_value):
self._context_of_index = context_of_index
self._index_value = index_value
@memoize_method
def __getitem__(self, index):
return self._tuple()[index]()
def __len__(self):
return len(self._tuple())
@memoize_method
@to_tuple
def _tuple(self):
def lambda_scoping_in_for_loop_sucks(lazy_value):
return lambda: ValueSet(_resolve_forward_references(
self._context_of_index,
lazy_value.infer()
))
if isinstance(self._index_value, SequenceLiteralValue):
for lazy_value in self._index_value.py__iter__(contextualized_node=None):
yield lambda_scoping_in_for_loop_sucks(lazy_value)
else:
yield lambda: ValueSet(_resolve_forward_references(
self._context_of_index,
ValueSet([self._index_value])
))
@to_tuple
def to_tuple(self):
for callable_ in self._tuple():
yield callable_()
def is_homogenous_tuple(self):
if isinstance(self._index_value, SequenceLiteralValue):
entries = self._index_value.get_tree_entries()
if len(entries) == 2 and entries[1] == '...':
return True
return False
def __repr__(self):
return '<LazyG>[%s]' % (', '.join(repr(x) for x in self.to_tuple()))
| LazyGenericManager |
python | giampaolo__psutil | tests/test_osx.py | {
"start": 1949,
"end": 6548
} | class ____(PsutilTestCase):
# --- disk
@retry_on_failure()
def test_disks(self):
# test psutil.disk_usage() and psutil.disk_partitions()
# against "df -a"
def df(path):
out = sh(f'df -k "{path}"').strip()
lines = out.split('\n')
lines.pop(0)
line = lines.pop(0)
dev, total, used, free = line.split()[:4]
if dev == 'none':
dev = ''
total = int(total) * 1024
used = int(used) * 1024
free = int(free) * 1024
return dev, total, used, free
for part in psutil.disk_partitions(all=False):
usage = psutil.disk_usage(part.mountpoint)
dev, total, used, free = df(part.mountpoint)
assert part.device == dev
assert usage.total == total
assert abs(usage.free - free) < TOLERANCE_DISK_USAGE
assert abs(usage.used - used) < TOLERANCE_DISK_USAGE
# --- cpu
def test_cpu_count_logical(self):
num = sysctl("sysctl hw.logicalcpu")
assert num == psutil.cpu_count(logical=True)
def test_cpu_count_cores(self):
num = sysctl("sysctl hw.physicalcpu")
assert num == psutil.cpu_count(logical=False)
# TODO: remove this once 1892 is fixed
@pytest.mark.skipif(MACOS and AARCH64, reason="skipped due to #1892")
def test_cpu_freq(self):
freq = psutil.cpu_freq()
assert freq.current * 1000 * 1000 == sysctl("sysctl hw.cpufrequency")
assert freq.min * 1000 * 1000 == sysctl("sysctl hw.cpufrequency_min")
assert freq.max * 1000 * 1000 == sysctl("sysctl hw.cpufrequency_max")
# --- virtual mem
def test_vmem_total(self):
sysctl_hwphymem = sysctl('sysctl hw.memsize')
assert sysctl_hwphymem == psutil.virtual_memory().total
@pytest.mark.skipif(
CI_TESTING and MACOS and AARCH64,
reason="skipped on MACOS + ARM64 + CI_TESTING",
)
@retry_on_failure()
def test_vmem_free(self):
vmstat_val = vm_stat("free")
psutil_val = psutil.virtual_memory().free
assert abs(psutil_val - vmstat_val) < TOLERANCE_SYS_MEM
@pytest.mark.skipif(
CI_TESTING and MACOS and AARCH64,
reason="skipped on MACOS + ARM64 + CI_TESTING",
)
@retry_on_failure()
def test_vmem_active(self):
vmstat_val = vm_stat("active")
psutil_val = psutil.virtual_memory().active
assert abs(psutil_val - vmstat_val) < TOLERANCE_SYS_MEM
# XXX: fails too often
@pytest.mark.skipif(CI_TESTING, reason="skipped on CI_TESTING")
@retry_on_failure()
def test_vmem_inactive(self):
vmstat_val = vm_stat("inactive")
psutil_val = psutil.virtual_memory().inactive
assert abs(psutil_val - vmstat_val) < TOLERANCE_SYS_MEM
@retry_on_failure()
def test_vmem_wired(self):
vmstat_val = vm_stat("wired")
psutil_val = psutil.virtual_memory().wired
assert abs(psutil_val - vmstat_val) < TOLERANCE_SYS_MEM
# --- swap mem
@retry_on_failure()
def test_swapmem_sin(self):
vmstat_val = vm_stat("Pageins")
psutil_val = psutil.swap_memory().sin
assert abs(psutil_val - vmstat_val) < TOLERANCE_SYS_MEM
@retry_on_failure()
def test_swapmem_sout(self):
vmstat_val = vm_stat("Pageout")
psutil_val = psutil.swap_memory().sout
assert abs(psutil_val - vmstat_val) < TOLERANCE_SYS_MEM
# --- network
def test_net_if_stats(self):
for name, stats in psutil.net_if_stats().items():
try:
out = sh(f"ifconfig {name}")
except RuntimeError:
pass
else:
assert stats.isup == ('RUNNING' in out), out
assert stats.mtu == int(re.findall(r'mtu (\d+)', out)[0])
# --- sensors_battery
@pytest.mark.skipif(not HAS_BATTERY, reason="no battery")
def test_sensors_battery(self):
out = sh("pmset -g batt")
percent = re.search(r"(\d+)%", out).group(1)
drawing_from = re.search(r"Now drawing from '([^']+)'", out).group(1)
power_plugged = drawing_from == "AC Power"
psutil_result = psutil.sensors_battery()
assert psutil_result.power_plugged == power_plugged
assert psutil_result.percent == int(percent)
# --- others
def test_boot_time(self):
out = sh('sysctl kern.boottime')
a = float(re.search(r"sec\s*=\s*(\d+)", out).groups(0)[0])
b = psutil.boot_time()
assert a == b
| TestSystemAPIs |
python | facebookresearch__faiss | tests/test_refine.py | {
"start": 2161,
"end": 4613
} | class ____(unittest.TestCase):
def do_test(self, factory_string):
ds = datasets.SyntheticDataset(32, 256, 100, 40)
index = faiss.index_factory(32, factory_string)
index.train(ds.get_train())
index.add(ds.get_database())
# Set nprobe on the base index (for IndexRefine, nprobe belongs to
# the IVF base index)
if hasattr(index, 'base_index') and hasattr(
index.base_index, 'nprobe'):
index.base_index.nprobe = 4
elif hasattr(index, 'nprobe'):
index.nprobe = 4
xq = ds.get_queries()
# do a search with k_factor = 1
D1, I1 = index.search(xq, 10)
inter1 = faiss.eval_intersection(I1, ds.get_groundtruth(10))
# do a search with k_factor = 1.5
params = faiss.IndexRefineSearchParameters(k_factor=1.1)
D2, I2 = index.search(xq, 10, params=params)
inter2 = faiss.eval_intersection(I2, ds.get_groundtruth(10))
# do a search with k_factor = 2
params = faiss.IndexRefineSearchParameters(k_factor=2)
D3, I3 = index.search(xq, 10, params=params)
inter3 = faiss.eval_intersection(I3, ds.get_groundtruth(10))
# make sure that the recall rate increases with k_factor
self.assertGreater(inter2, inter1)
self.assertGreater(inter3, inter2)
# make sure that the baseline k_factor is unchanged
self.assertEqual(index.k_factor, 1)
# try passing params for the baseline index, change nprobe
base_params = faiss.IVFSearchParameters(nprobe=10)
params = faiss.IndexRefineSearchParameters(k_factor=1, base_index_params=base_params)
D4, I4 = index.search(xq, 10, params=params)
inter4 = faiss.eval_intersection(I4, ds.get_groundtruth(10))
base_params = faiss.IVFSearchParameters(nprobe=2)
params = faiss.IndexRefineSearchParameters(k_factor=1, base_index_params=base_params)
D5, I5 = index.search(xq, 10, params=params)
inter5 = faiss.eval_intersection(I5, ds.get_groundtruth(10))
# make sure that the recall rate changes
self.assertNotEqual(inter4, inter5)
def test_rflat(self):
# flat is handled by the IndexRefineFlat class
self.do_test("IVF8,PQ2x4np,RFlat")
def test_refine_sq8(self):
# this case uses the IndexRefine class
self.do_test("IVF8,PQ2x4np,Refine(SQ8)")
| TestIndexRefineSearchParams |
python | langchain-ai__langchain | libs/partners/prompty/langchain_prompty/core.py | {
"start": 5650,
"end": 5975
} | class ____(abc.ABC):
"""Base class for all invokers."""
def __init__(self, prompty: Prompty) -> None:
self.prompty = prompty
@abc.abstractmethod
def invoke(self, data: BaseModel) -> BaseModel:
pass
def __call__(self, data: BaseModel) -> BaseModel:
return self.invoke(data)
| Invoker |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/instance/methods/daemon_methods.py | {
"start": 453,
"end": 4774
} | class ____:
"""Mixin class containing daemon-related functionality for DagsterInstance.
This class provides methods for daemon management, heartbeats, and status monitoring.
All methods are implemented as instance methods that DagsterInstance inherits.
"""
# Abstract properties that DagsterInstance provides
@property
@abstractmethod
def run_storage(self) -> "RunStorage": ...
@property
@abstractmethod
def is_ephemeral(self) -> bool: ...
@property
@abstractmethod
def scheduler(self) -> Optional["Scheduler"]: ...
@property
@abstractmethod
def run_coordinator(self) -> "RunCoordinator": ...
@property
@abstractmethod
def run_monitoring_enabled(self) -> bool: ...
@property
@abstractmethod
def run_retries_enabled(self) -> bool: ...
@property
@abstractmethod
def auto_materialize_enabled(self) -> bool: ...
@property
@abstractmethod
def auto_materialize_use_sensors(self) -> bool: ...
@property
@abstractmethod
def freshness_enabled(self) -> bool: ...
def add_daemon_heartbeat(self, daemon_heartbeat: "DaemonHeartbeat") -> None:
"""Called on a regular interval by the daemon."""
self.run_storage.add_daemon_heartbeat(daemon_heartbeat)
def get_daemon_heartbeats(self) -> Mapping[str, "DaemonHeartbeat"]:
"""Latest heartbeats of all daemon types."""
return self.run_storage.get_daemon_heartbeats()
def wipe_daemon_heartbeats(self) -> None:
self.run_storage.wipe_daemon_heartbeats()
def get_required_daemon_types(self) -> Sequence[str]:
from dagster._core.run_coordinator import QueuedRunCoordinator
from dagster._core.scheduler import DagsterDaemonScheduler
from dagster._daemon.asset_daemon import AssetDaemon
from dagster._daemon.auto_run_reexecution.event_log_consumer import EventLogConsumerDaemon
from dagster._daemon.daemon import (
BackfillDaemon,
MonitoringDaemon,
SchedulerDaemon,
SensorDaemon,
)
from dagster._daemon.freshness import FreshnessDaemon
from dagster._daemon.run_coordinator.queued_run_coordinator_daemon import (
QueuedRunCoordinatorDaemon,
)
if self.is_ephemeral:
return []
daemons = [SensorDaemon.daemon_type(), BackfillDaemon.daemon_type()]
if isinstance(self.scheduler, DagsterDaemonScheduler):
daemons.append(SchedulerDaemon.daemon_type())
if isinstance(self.run_coordinator, QueuedRunCoordinator):
daemons.append(QueuedRunCoordinatorDaemon.daemon_type())
if self.run_monitoring_enabled:
daemons.append(MonitoringDaemon.daemon_type())
if self.run_retries_enabled:
daemons.append(EventLogConsumerDaemon.daemon_type())
if self.auto_materialize_enabled or self.auto_materialize_use_sensors:
daemons.append(AssetDaemon.daemon_type())
if self.freshness_enabled:
daemons.append(FreshnessDaemon.daemon_type())
return daemons
def get_daemon_statuses(
self, daemon_types: Optional[Sequence[str]] = None
) -> Mapping[str, "DaemonStatus"]:
"""Get the current status of the daemons. If daemon_types aren't provided, defaults to all
required types. Returns a dict of daemon type to status.
"""
from typing import cast
import dagster._check as check
from dagster._daemon.controller import get_daemon_statuses
check.opt_sequence_param(daemon_types, "daemon_types", of_type=str)
# Cast is safe since this mixin is only used by DagsterInstance
return get_daemon_statuses(
cast("DagsterInstance", self),
daemon_types=daemon_types or self.get_required_daemon_types(),
ignore_errors=True,
)
@property
def daemon_skip_heartbeats_without_errors(self) -> bool:
# If enabled, daemon threads won't write heartbeats unless they encounter an error. This is
# enabled in cloud, where we don't need to use heartbeats to check if daemons are running, but
# do need to surface errors to users. This is an optimization to reduce DB writes.
return False
| DaemonMethods |
python | ray-project__ray | doc/source/serve/doc_code/managing_deployments.py | {
"start": 402,
"end": 1451
} | class ____:
pass
serve.run(SimpleDeployment.bind())
# You can also use Deployment.options() to change options without redefining
# the class. This is useful for programmatically updating deployments.
serve.run(SimpleDeployment.options(num_replicas=2).bind())
# __updating_a_deployment_end__
# __scaling_out_start__
# Create with a single replica.
@serve.deployment(num_replicas=1)
def func(*args):
pass
serve.run(func.bind())
# Scale up to 3 replicas.
serve.run(func.options(num_replicas=3).bind())
# Scale back down to 1 replica.
serve.run(func.options(num_replicas=1).bind())
# __scaling_out_end__
# __autoscaling_start__
@serve.deployment(
autoscaling_config={
"min_replicas": 1,
"initial_replicas": 2,
"max_replicas": 5,
"target_ongoing_requests": 10,
}
)
def func(_):
time.sleep(1)
return ""
serve.run(
func.bind()
) # The func deployment will now autoscale based on requests demand.
# __autoscaling_end__
# __configure_parallism_start__
@serve.deployment
| SimpleDeployment |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/exc.py | {
"start": 24982,
"end": 25222
} | class ____(Warning):
"""warning for a condition detected during tests that is non-fatal
Currently outside of SAWarning so that we can work around tools like
Alembic doing the wrong thing with warnings.
"""
| SATestSuiteWarning |
python | pypa__pip | src/pip/_internal/operations/prepare.py | {
"start": 3037,
"end": 7254
} | class ____:
path: str
content_type: str | None = None
def __post_init__(self) -> None:
if self.content_type is None:
# Try to guess the file's MIME type. If the system MIME tables
# can't be loaded, give up.
try:
self.content_type = mimetypes.guess_type(self.path)[0]
except OSError:
pass
def get_http_url(
link: Link,
download: Downloader,
download_dir: str | None = None,
hashes: Hashes | None = None,
) -> File:
temp_dir = TempDirectory(kind="unpack", globally_managed=True)
# If a download dir is specified, is the file already downloaded there?
already_downloaded_path = None
if download_dir:
already_downloaded_path = _check_download_dir(link, download_dir, hashes)
if already_downloaded_path:
from_path = already_downloaded_path
content_type = None
else:
# let's download to a tmp dir
from_path, content_type = download(link, temp_dir.path)
if hashes:
hashes.check_against_path(from_path)
return File(from_path, content_type)
def get_file_url(
link: Link, download_dir: str | None = None, hashes: Hashes | None = None
) -> File:
"""Get file and optionally check its hash."""
# If a download dir is specified, is the file already there and valid?
already_downloaded_path = None
if download_dir:
already_downloaded_path = _check_download_dir(link, download_dir, hashes)
if already_downloaded_path:
from_path = already_downloaded_path
else:
from_path = link.file_path
# If --require-hashes is off, `hashes` is either empty, the
# link's embedded hash, or MissingHashes; it is required to
# match. If --require-hashes is on, we are satisfied by any
# hash in `hashes` matching: a URL-based or an option-based
# one; no internet-sourced hash will be in `hashes`.
if hashes:
hashes.check_against_path(from_path)
return File(from_path, None)
def unpack_url(
link: Link,
location: str,
download: Downloader,
verbosity: int,
download_dir: str | None = None,
hashes: Hashes | None = None,
) -> File | None:
"""Unpack link into location, downloading if required.
:param hashes: A Hashes object, one of whose embedded hashes must match,
or HashMismatch will be raised. If the Hashes is empty, no matches are
required, and unhashable types of requirements (like VCS ones, which
would ordinarily raise HashUnsupported) are allowed.
"""
# non-editable vcs urls
if link.is_vcs:
unpack_vcs_link(link, location, verbosity=verbosity)
return None
assert not link.is_existing_dir()
# file urls
if link.is_file:
file = get_file_url(link, download_dir, hashes=hashes)
# http urls
else:
file = get_http_url(
link,
download,
download_dir,
hashes=hashes,
)
# unpack the archive to the build dir location. even when only downloading
# archives, they have to be unpacked to parse dependencies, except wheels
if not link.is_wheel:
unpack_file(file.path, location, file.content_type)
return file
def _check_download_dir(
link: Link,
download_dir: str,
hashes: Hashes | None,
warn_on_hash_mismatch: bool = True,
) -> str | None:
"""Check download_dir for previously downloaded file with correct hash
If a correct file is found return its path else None
"""
download_path = os.path.join(download_dir, link.filename)
if not os.path.exists(download_path):
return None
# If already downloaded, does its hash match?
logger.info("File was already downloaded %s", download_path)
if hashes:
try:
hashes.check_against_path(download_path)
except HashMismatch:
if warn_on_hash_mismatch:
logger.warning(
"Previously-downloaded file %s has bad hash. Re-downloading.",
download_path,
)
os.unlink(download_path)
return None
return download_path
| File |
python | ApeWorX__ape | src/ape/managers/_deploymentscache.py | {
"start": 280,
"end": 870
} | class ____(BaseModel):
"""
A single deployment of a contract in a network.
"""
address: AddressType
transaction_hash: Optional[str] = None
def __getitem__(self, key: str):
# Mainly exists for backwards compat.
if key == "address":
return self.address
elif key == "transaction_hash":
return self.transaction_hash
raise KeyError(key)
def get(self, key: str):
# Mainly exists for backwards compat.
try:
return self[key]
except KeyError:
return None
| Deployment |
python | kubernetes-client__python | kubernetes/client/models/v1_persistent_volume_claim_spec.py | {
"start": 383,
"end": 13431
} | 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 = {
'access_modes': 'list[str]',
'data_source': 'V1TypedLocalObjectReference',
'data_source_ref': 'V1TypedObjectReference',
'resources': 'V1VolumeResourceRequirements',
'selector': 'V1LabelSelector',
'storage_class_name': 'str',
'volume_attributes_class_name': 'str',
'volume_mode': 'str',
'volume_name': 'str'
}
attribute_map = {
'access_modes': 'accessModes',
'data_source': 'dataSource',
'data_source_ref': 'dataSourceRef',
'resources': 'resources',
'selector': 'selector',
'storage_class_name': 'storageClassName',
'volume_attributes_class_name': 'volumeAttributesClassName',
'volume_mode': 'volumeMode',
'volume_name': 'volumeName'
}
def __init__(self, access_modes=None, data_source=None, data_source_ref=None, resources=None, selector=None, storage_class_name=None, volume_attributes_class_name=None, volume_mode=None, volume_name=None, local_vars_configuration=None): # noqa: E501
"""V1PersistentVolumeClaimSpec - 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._access_modes = None
self._data_source = None
self._data_source_ref = None
self._resources = None
self._selector = None
self._storage_class_name = None
self._volume_attributes_class_name = None
self._volume_mode = None
self._volume_name = None
self.discriminator = None
if access_modes is not None:
self.access_modes = access_modes
if data_source is not None:
self.data_source = data_source
if data_source_ref is not None:
self.data_source_ref = data_source_ref
if resources is not None:
self.resources = resources
if selector is not None:
self.selector = selector
if storage_class_name is not None:
self.storage_class_name = storage_class_name
if volume_attributes_class_name is not None:
self.volume_attributes_class_name = volume_attributes_class_name
if volume_mode is not None:
self.volume_mode = volume_mode
if volume_name is not None:
self.volume_name = volume_name
@property
def access_modes(self):
"""Gets the access_modes of this V1PersistentVolumeClaimSpec. # noqa: E501
accessModes contains the desired access modes the volume should have. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modes-1 # noqa: E501
:return: The access_modes of this V1PersistentVolumeClaimSpec. # noqa: E501
:rtype: list[str]
"""
return self._access_modes
@access_modes.setter
def access_modes(self, access_modes):
"""Sets the access_modes of this V1PersistentVolumeClaimSpec.
accessModes contains the desired access modes the volume should have. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modes-1 # noqa: E501
:param access_modes: The access_modes of this V1PersistentVolumeClaimSpec. # noqa: E501
:type: list[str]
"""
self._access_modes = access_modes
@property
def data_source(self):
"""Gets the data_source of this V1PersistentVolumeClaimSpec. # noqa: E501
:return: The data_source of this V1PersistentVolumeClaimSpec. # noqa: E501
:rtype: V1TypedLocalObjectReference
"""
return self._data_source
@data_source.setter
def data_source(self, data_source):
"""Sets the data_source of this V1PersistentVolumeClaimSpec.
:param data_source: The data_source of this V1PersistentVolumeClaimSpec. # noqa: E501
:type: V1TypedLocalObjectReference
"""
self._data_source = data_source
@property
def data_source_ref(self):
"""Gets the data_source_ref of this V1PersistentVolumeClaimSpec. # noqa: E501
:return: The data_source_ref of this V1PersistentVolumeClaimSpec. # noqa: E501
:rtype: V1TypedObjectReference
"""
return self._data_source_ref
@data_source_ref.setter
def data_source_ref(self, data_source_ref):
"""Sets the data_source_ref of this V1PersistentVolumeClaimSpec.
:param data_source_ref: The data_source_ref of this V1PersistentVolumeClaimSpec. # noqa: E501
:type: V1TypedObjectReference
"""
self._data_source_ref = data_source_ref
@property
def resources(self):
"""Gets the resources of this V1PersistentVolumeClaimSpec. # noqa: E501
:return: The resources of this V1PersistentVolumeClaimSpec. # noqa: E501
:rtype: V1VolumeResourceRequirements
"""
return self._resources
@resources.setter
def resources(self, resources):
"""Sets the resources of this V1PersistentVolumeClaimSpec.
:param resources: The resources of this V1PersistentVolumeClaimSpec. # noqa: E501
:type: V1VolumeResourceRequirements
"""
self._resources = resources
@property
def selector(self):
"""Gets the selector of this V1PersistentVolumeClaimSpec. # noqa: E501
:return: The selector of this V1PersistentVolumeClaimSpec. # noqa: E501
:rtype: V1LabelSelector
"""
return self._selector
@selector.setter
def selector(self, selector):
"""Sets the selector of this V1PersistentVolumeClaimSpec.
:param selector: The selector of this V1PersistentVolumeClaimSpec. # noqa: E501
:type: V1LabelSelector
"""
self._selector = selector
@property
def storage_class_name(self):
"""Gets the storage_class_name of this V1PersistentVolumeClaimSpec. # noqa: E501
storageClassName is the name of the StorageClass required by the claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#class-1 # noqa: E501
:return: The storage_class_name of this V1PersistentVolumeClaimSpec. # noqa: E501
:rtype: str
"""
return self._storage_class_name
@storage_class_name.setter
def storage_class_name(self, storage_class_name):
"""Sets the storage_class_name of this V1PersistentVolumeClaimSpec.
storageClassName is the name of the StorageClass required by the claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#class-1 # noqa: E501
:param storage_class_name: The storage_class_name of this V1PersistentVolumeClaimSpec. # noqa: E501
:type: str
"""
self._storage_class_name = storage_class_name
@property
def volume_attributes_class_name(self):
"""Gets the volume_attributes_class_name of this V1PersistentVolumeClaimSpec. # noqa: E501
volumeAttributesClassName may be used to set the VolumeAttributesClass used by this claim. If specified, the CSI driver will create or update the volume with the attributes defined in the corresponding VolumeAttributesClass. This has a different purpose than storageClassName, it can be changed after the claim is created. An empty string or nil value indicates that no VolumeAttributesClass will be applied to the claim. If the claim enters an Infeasible error state, this field can be reset to its previous value (including nil) to cancel the modification. If the resource referred to by volumeAttributesClass does not exist, this PersistentVolumeClaim will be set to a Pending state, as reflected by the modifyVolumeStatus field, until such as a resource exists. More info: https://kubernetes.io/docs/concepts/storage/volume-attributes-classes/ # noqa: E501
:return: The volume_attributes_class_name of this V1PersistentVolumeClaimSpec. # noqa: E501
:rtype: str
"""
return self._volume_attributes_class_name
@volume_attributes_class_name.setter
def volume_attributes_class_name(self, volume_attributes_class_name):
"""Sets the volume_attributes_class_name of this V1PersistentVolumeClaimSpec.
volumeAttributesClassName may be used to set the VolumeAttributesClass used by this claim. If specified, the CSI driver will create or update the volume with the attributes defined in the corresponding VolumeAttributesClass. This has a different purpose than storageClassName, it can be changed after the claim is created. An empty string or nil value indicates that no VolumeAttributesClass will be applied to the claim. If the claim enters an Infeasible error state, this field can be reset to its previous value (including nil) to cancel the modification. If the resource referred to by volumeAttributesClass does not exist, this PersistentVolumeClaim will be set to a Pending state, as reflected by the modifyVolumeStatus field, until such as a resource exists. More info: https://kubernetes.io/docs/concepts/storage/volume-attributes-classes/ # noqa: E501
:param volume_attributes_class_name: The volume_attributes_class_name of this V1PersistentVolumeClaimSpec. # noqa: E501
:type: str
"""
self._volume_attributes_class_name = volume_attributes_class_name
@property
def volume_mode(self):
"""Gets the volume_mode of this V1PersistentVolumeClaimSpec. # noqa: E501
volumeMode defines what type of volume is required by the claim. Value of Filesystem is implied when not included in claim spec. # noqa: E501
:return: The volume_mode of this V1PersistentVolumeClaimSpec. # noqa: E501
:rtype: str
"""
return self._volume_mode
@volume_mode.setter
def volume_mode(self, volume_mode):
"""Sets the volume_mode of this V1PersistentVolumeClaimSpec.
volumeMode defines what type of volume is required by the claim. Value of Filesystem is implied when not included in claim spec. # noqa: E501
:param volume_mode: The volume_mode of this V1PersistentVolumeClaimSpec. # noqa: E501
:type: str
"""
self._volume_mode = volume_mode
@property
def volume_name(self):
"""Gets the volume_name of this V1PersistentVolumeClaimSpec. # noqa: E501
volumeName is the binding reference to the PersistentVolume backing this claim. # noqa: E501
:return: The volume_name of this V1PersistentVolumeClaimSpec. # noqa: E501
:rtype: str
"""
return self._volume_name
@volume_name.setter
def volume_name(self, volume_name):
"""Sets the volume_name of this V1PersistentVolumeClaimSpec.
volumeName is the binding reference to the PersistentVolume backing this claim. # noqa: E501
:param volume_name: The volume_name of this V1PersistentVolumeClaimSpec. # noqa: E501
:type: str
"""
self._volume_name = volume_name
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, V1PersistentVolumeClaimSpec):
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, V1PersistentVolumeClaimSpec):
return True
return self.to_dict() != other.to_dict()
| V1PersistentVolumeClaimSpec |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefault2.py | {
"start": 2309,
"end": 2416
} | class ____[**P = int]: ...
# This should generate an error because ParamSpec must be a list of types.
| ClassP6 |
python | django__django | django/contrib/postgres/fields/ranges.py | {
"start": 11044,
"end": 11211
} | class ____(models.Transform):
lookup_name = "lower_inf"
function = "LOWER_INF"
output_field = models.BooleanField()
@RangeField.register_lookup
| LowerInfinite |
python | sqlalchemy__sqlalchemy | test/sql/test_operators.py | {
"start": 71440,
"end": 73773
} | class ____(fixtures.TestBase, testing.AssertsCompiledSQL):
__dialect__ = "default"
table1 = table("mytable", column("myid", Integer))
def test_is_distinct_from(self):
self.assert_compile(
self.table1.c.myid.is_distinct_from(1),
"mytable.myid IS DISTINCT FROM :myid_1",
)
def test_is_distinct_from_sqlite(self):
self.assert_compile(
self.table1.c.myid.is_distinct_from(1),
"mytable.myid IS NOT ?",
dialect=sqlite.dialect(),
)
def test_is_distinct_from_postgresql(self):
self.assert_compile(
self.table1.c.myid.is_distinct_from(1),
"mytable.myid IS DISTINCT FROM %(myid_1)s",
dialect=postgresql.dialect(),
)
def test_not_is_distinct_from(self):
self.assert_compile(
~self.table1.c.myid.is_distinct_from(1),
"mytable.myid IS NOT DISTINCT FROM :myid_1",
)
def test_not_is_distinct_from_postgresql(self):
self.assert_compile(
~self.table1.c.myid.is_distinct_from(1),
"mytable.myid IS NOT DISTINCT FROM %(myid_1)s",
dialect=postgresql.dialect(),
)
def test_is_not_distinct_from(self):
self.assert_compile(
self.table1.c.myid.is_not_distinct_from(1),
"mytable.myid IS NOT DISTINCT FROM :myid_1",
)
def test_is_not_distinct_from_sqlite(self):
self.assert_compile(
self.table1.c.myid.is_not_distinct_from(1),
"mytable.myid IS ?",
dialect=sqlite.dialect(),
)
def test_is_not_distinct_from_postgresql(self):
self.assert_compile(
self.table1.c.myid.is_not_distinct_from(1),
"mytable.myid IS NOT DISTINCT FROM %(myid_1)s",
dialect=postgresql.dialect(),
)
def test_not_is_not_distinct_from(self):
self.assert_compile(
~self.table1.c.myid.is_not_distinct_from(1),
"mytable.myid IS DISTINCT FROM :myid_1",
)
def test_not_is_not_distinct_from_postgresql(self):
self.assert_compile(
~self.table1.c.myid.is_not_distinct_from(1),
"mytable.myid IS DISTINCT FROM %(myid_1)s",
dialect=postgresql.dialect(),
)
| IsDistinctFromTest |
python | huggingface__transformers | tests/trainer/test_trainer.py | {
"start": 11197,
"end": 21978
} | class ____(PreTrainedConfig):
def __init__(self, a=0, b=0, double_output=False, random_torch=True, **kwargs):
super().__init__(**kwargs)
self.a = a
self.b = b
self.double_output = double_output
self.random_torch = random_torch
self.hidden_size = 1
if is_torch_available():
class SampleIterableDataset(IterableDataset):
def __init__(self, a=2, b=3, length=64, seed=42, label_names=None):
self.dataset = RegressionDataset(a=a, b=b, length=length, seed=seed, label_names=label_names)
def __iter__(self):
for i in range(len(self.dataset)):
yield self.dataset[i]
class FiniteIterableDataset(SampleIterableDataset):
def __init__(self, a=2, b=3, length=64, seed=42, label_names=None):
super().__init__(a, b, length, seed, label_names)
self.current_sample = 0
def __iter__(self):
while self.current_sample < len(self.dataset):
yield self.dataset[self.current_sample]
self.current_sample += 1
class MultiLoader:
def __init__(self, loaders):
self.loaders = loaders
def __len__(self):
return sum(len(loader) for loader in self.loaders)
def __iter__(self):
for loader in self.loaders:
yield from loader
class CustomDataloaderTrainer(Trainer):
def get_train_dataloader(self):
dataloaders = [super().get_train_dataloader(), super().get_train_dataloader()]
return MultiLoader(dataloaders)
def get_eval_dataloader(self, eval_dataset):
dataloaders = [super().get_eval_dataloader(eval_dataset), super().get_eval_dataloader(eval_dataset)]
return MultiLoader(dataloaders)
class RegressionModel(nn.Module):
def __init__(self, a=0, b=0, double_output=False):
super().__init__()
self.a = nn.Parameter(torch.tensor(a).float())
self.b = nn.Parameter(torch.tensor(b).float())
self.double_output = double_output
self.config = None
def forward(self, input_x, labels=None, **kwargs):
y = input_x * self.a + self.b
if labels is None:
return (y, y) if self.double_output else (y,)
loss = nn.functional.mse_loss(y, labels)
return (loss, y, y) if self.double_output else (loss, y)
class RegressionDictModel(nn.Module):
def __init__(self, a=0, b=0):
super().__init__()
self.a = nn.Parameter(torch.tensor(a).float())
self.b = nn.Parameter(torch.tensor(b).float())
self.config = None
def forward(self, input_x, labels=None, **kwargs):
y = input_x * self.a + self.b
result = {"output": y}
if labels is not None:
result["loss"] = nn.functional.mse_loss(y, labels)
return result
class RegressionPreTrainedModel(PreTrainedModel):
config_class = RegressionModelConfig
base_model_prefix = "regression"
def __init__(self, config):
super().__init__(config)
self.a = nn.Parameter(torch.tensor(config.a).float())
self.b = nn.Parameter(torch.tensor(config.b).float())
self.double_output = config.double_output
self.post_init()
def forward(self, input_x, labels=None, **kwargs):
y = input_x * self.a + self.b
if labels is None:
return (y, y) if self.double_output else (y,)
loss = nn.functional.mse_loss(y, labels)
return (loss, y, y) if self.double_output else (loss, y)
class RegressionPreTrainedModelWithGradientCheckpointing(PreTrainedModel):
config_class = RegressionModelConfig
base_model_prefix = "regression"
supports_gradient_checkpointing = True
def __init__(self, config):
super().__init__(config)
self.layers = nn.ModuleList([nn.Linear(config.hidden_size, config.hidden_size) for _ in range(4)])
self.head = nn.Linear(config.hidden_size, 1)
self.gradient_checkpointing = False
self.double_output = config.double_output
self.post_init()
def forward(self, input_x, labels=None, **kwargs):
y = input_x.unsqueeze(0)
for layer in self.layers:
if self.training and self.gradient_checkpointing:
outputs = self._gradient_checkpointing_func(layer.__call__, y)
else:
outputs = layer(y)
y = outputs * 3
logits = self.head(y)
if labels is None:
return (logits, logits) if self.double_output else (logits,)
loss = nn.functional.mse_loss(logits, labels)
return (loss, y, y) if self.double_output else (loss, y)
class RegressionRandomPreTrainedModel(PreTrainedModel):
config_class = RegressionModelConfig
base_model_prefix = "regression"
def __init__(self, config):
super().__init__(config)
self.a = nn.Parameter(torch.tensor(config.a).float())
self.b = nn.Parameter(torch.tensor(config.b).float())
self.random_torch = config.random_torch
self.post_init()
def forward(self, input_x, labels=None, **kwargs):
y = input_x * self.a + self.b
if self.random_torch:
torch_rand = torch.randn(1).squeeze()
np_rand = np.random.rand()
rand_rand = random.random()
if self.random_torch:
y += 0.05 * torch_rand
y += 0.05 * torch.tensor(np_rand + rand_rand)
if labels is None:
return (y,)
loss = nn.functional.mse_loss(y, labels)
return (loss, y)
class BasicTextGenerationModel(nn.Module):
def __init__(self, vocab_size, hidden_size):
super().__init__()
self.embedding = nn.Embedding(vocab_size, hidden_size)
self.lstm = nn.LSTM(hidden_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, vocab_size)
def forward(self, input_ids, labels=None, **kwargs):
embedded = self.embedding(input_ids)
lstm_out, _ = self.lstm(embedded)
logits = self.fc(lstm_out)
if labels is None:
return logits
loss = nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), labels.view(-1))
return loss, logits
def create_dummy_dataset_for_text_generation(vocab_size, seq_length, num_samples):
import numpy as np
# Create random input sequences
input_ids = np.random.randint(0, vocab_size, (num_samples, seq_length))
# Create a datasets.Dataset
dataset = datasets.Dataset.from_dict({"input_ids": input_ids, "labels": input_ids})
return dataset
class TstLayer(nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.linear1 = nn.Linear(hidden_size, hidden_size)
self.ln1 = nn.LayerNorm(hidden_size)
self.linear2 = nn.Linear(hidden_size, hidden_size)
self.ln2 = nn.LayerNorm(hidden_size)
self.bias = nn.Parameter(torch.zeros(hidden_size))
def forward(self, x):
h = self.ln1(nn.functional.relu(self.linear1(x)))
h = nn.functional.relu(self.linear2(x))
return self.ln2(x + h + self.bias)
def get_regression_trainer(
a=0,
b=0,
double_output=False,
train_len=64,
eval_len=64,
pretrained=True,
keep_report_to=False,
output_dir=None,
**kwargs,
):
label_names = kwargs.get("label_names")
gradient_checkpointing = kwargs.get("gradient_checkpointing", False)
train_dataset = RegressionDataset(length=train_len, label_names=label_names)
eval_dataset = RegressionDataset(length=eval_len, label_names=label_names)
model_init = kwargs.pop("model_init", None)
if model_init is not None:
model = None
else:
if pretrained:
config = RegressionModelConfig(a=a, b=b, double_output=double_output)
# We infer the correct model class if one uses gradient_checkpointing or not
target_cls = (
RegressionPreTrainedModel
if not gradient_checkpointing
else RegressionPreTrainedModelWithGradientCheckpointing
)
model = target_cls(config)
else:
model = RegressionModel(a=a, b=b, double_output=double_output)
compute_metrics = kwargs.pop("compute_metrics", None)
data_collator = kwargs.pop("data_collator", None)
optimizers = kwargs.pop("optimizers", (None, None))
preprocess_logits_for_metrics = kwargs.pop("preprocess_logits_for_metrics", None)
assert output_dir is not None, "output_dir should be specified for testing"
args = RegressionTrainingArguments(output_dir, a=a, b=b, keep_report_to=keep_report_to, **kwargs)
trainer = Trainer(
model,
args,
data_collator=data_collator,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
compute_metrics=compute_metrics,
optimizers=optimizers,
model_init=model_init,
preprocess_logits_for_metrics=preprocess_logits_for_metrics,
)
# TODO: loss function defined in RegressionModel doesn't accept num_item_per_batch, to fix later
trainer.model_accepts_loss_kwargs = False
return trainer
def get_language_model_trainer(**kwargs):
dataset = datasets.load_dataset("fka/awesome-chatgpt-prompts")
model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2")
tokenizer.pad_token = tokenizer.eos_token
def _tokenize_function(examples):
model_inputs = tokenizer(examples["prompt"], padding="max_length", truncation=True)
model_inputs["labels"] = np.array(model_inputs["input_ids"]).astype(np.int64)
return model_inputs
tokenized_datasets = dataset.map(_tokenize_function, batched=True)
training_args = TrainingArguments(**kwargs)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets["train"],
)
return trainer
| RegressionModelConfig |
python | fastapi__sqlmodel | docs_src/advanced/decimal/tutorial001_py310.py | {
"start": 100,
"end": 1597
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
money: Decimal = Field(default=0, max_digits=5, decimal_places=3)
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
def create_db_and_tables():
SQLModel.metadata.create_all(engine)
def create_heroes():
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson", money=1.1)
hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador", money=0.001)
hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48, money=2.2)
with Session(engine) as session:
session.add(hero_1)
session.add(hero_2)
session.add(hero_3)
session.commit()
def select_heroes():
with Session(engine) as session:
statement = select(Hero).where(Hero.name == "Deadpond")
results = session.exec(statement)
hero_1 = results.one()
print("Hero 1:", hero_1)
statement = select(Hero).where(Hero.name == "Rusty-Man")
results = session.exec(statement)
hero_2 = results.one()
print("Hero 2:", hero_2)
total_money = hero_1.money + hero_2.money
print(f"Total money: {total_money}")
def main():
create_db_and_tables()
create_heroes()
select_heroes()
if __name__ == "__main__":
main()
| Hero |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/document_summary/base.py | {
"start": 1648,
"end": 11215
} | class ____(BaseIndex[IndexDocumentSummary]):
"""
Document Summary Index.
Args:
response_synthesizer (BaseSynthesizer): A response synthesizer for generating
summaries.
summary_query (str): The query to use to generate the summary for each document.
show_progress (bool): Whether to show tqdm progress bars.
Defaults to False.
embed_summaries (bool): Whether to embed the summaries.
This is required for running the default embedding-based retriever.
Defaults to True.
"""
index_struct_cls = IndexDocumentSummary
def __init__(
self,
nodes: Optional[Sequence[BaseNode]] = None,
objects: Optional[Sequence[IndexNode]] = None,
index_struct: Optional[IndexDocumentSummary] = None,
llm: Optional[LLM] = None,
embed_model: Optional[BaseEmbedding] = None,
storage_context: Optional[StorageContext] = None,
response_synthesizer: Optional[BaseSynthesizer] = None,
summary_query: str = DEFAULT_SUMMARY_QUERY,
show_progress: bool = False,
embed_summaries: bool = True,
**kwargs: Any,
) -> None:
"""Initialize params."""
self._llm = llm or Settings.llm
self._embed_model = embed_model or Settings.embed_model
self._response_synthesizer = response_synthesizer or get_response_synthesizer(
llm=self._llm, response_mode=ResponseMode.TREE_SUMMARIZE
)
self._summary_query = summary_query
self._embed_summaries = embed_summaries
super().__init__(
nodes=nodes,
index_struct=index_struct,
storage_context=storage_context,
show_progress=show_progress,
objects=objects,
**kwargs,
)
@property
def vector_store(self) -> BasePydanticVectorStore:
return self._vector_store
def as_retriever(
self,
retriever_mode: Union[str, _RetrieverMode] = _RetrieverMode.EMBEDDING,
**kwargs: Any,
) -> BaseRetriever:
"""
Get retriever.
Args:
retriever_mode (Union[str, DocumentSummaryRetrieverMode]): A retriever mode.
Defaults to DocumentSummaryRetrieverMode.EMBEDDING.
"""
from llama_index.core.indices.document_summary.retrievers import (
DocumentSummaryIndexEmbeddingRetriever,
DocumentSummaryIndexLLMRetriever,
)
LLMRetriever = DocumentSummaryIndexLLMRetriever
EmbeddingRetriever = DocumentSummaryIndexEmbeddingRetriever
if retriever_mode == _RetrieverMode.EMBEDDING:
if not self._embed_summaries:
raise ValueError(
"Cannot use embedding retriever if embed_summaries is False"
)
return EmbeddingRetriever(
self,
object_map=self._object_map,
embed_model=self._embed_model,
**kwargs,
)
if retriever_mode == _RetrieverMode.LLM:
return LLMRetriever(
self, object_map=self._object_map, llm=self._llm, **kwargs
)
else:
raise ValueError(f"Unknown retriever mode: {retriever_mode}")
def get_document_summary(self, doc_id: str) -> str:
"""
Get document summary by doc id.
Args:
doc_id (str): A document id.
"""
if doc_id not in self._index_struct.doc_id_to_summary_id:
raise ValueError(f"doc_id {doc_id} not in index")
summary_id = self._index_struct.doc_id_to_summary_id[doc_id]
return self.docstore.get_node(summary_id).get_content()
def _add_nodes_to_index(
self,
index_struct: IndexDocumentSummary,
nodes: Sequence[BaseNode],
show_progress: bool = False,
) -> None:
"""Add nodes to index."""
doc_id_to_nodes = defaultdict(list)
for node in nodes:
if node.ref_doc_id is None:
raise ValueError(
"ref_doc_id of node cannot be None when building a document "
"summary index"
)
doc_id_to_nodes[node.ref_doc_id].append(node)
summary_node_dict = {}
items = doc_id_to_nodes.items()
iterable_with_progress = get_tqdm_iterable(
items, show_progress, "Summarizing documents"
)
for doc_id, nodes in iterable_with_progress:
print(f"current doc id: {doc_id}")
nodes_with_scores = [NodeWithScore(node=n) for n in nodes]
# get the summary for each doc_id
summary_response = self._response_synthesizer.synthesize(
query=self._summary_query,
nodes=nodes_with_scores,
)
summary_response = cast(Response, summary_response)
docid_first_node = doc_id_to_nodes.get(doc_id, [TextNode()])[0]
summary_node_dict[doc_id] = TextNode(
text=summary_response.response,
relationships={
NodeRelationship.SOURCE: RelatedNodeInfo(node_id=doc_id)
},
metadata=docid_first_node.metadata,
excluded_embed_metadata_keys=docid_first_node.excluded_embed_metadata_keys,
excluded_llm_metadata_keys=docid_first_node.excluded_llm_metadata_keys,
)
self.docstore.add_documents([summary_node_dict[doc_id]])
logger.info(
f"> Generated summary for doc {doc_id}: {summary_response.response}"
)
for doc_id, nodes in doc_id_to_nodes.items():
index_struct.add_summary_and_nodes(summary_node_dict[doc_id], nodes)
if self._embed_summaries:
summary_nodes = list(summary_node_dict.values())
id_to_embed_map = embed_nodes(
summary_nodes, self._embed_model, show_progress=show_progress
)
summary_nodes_with_embedding = []
for node in summary_nodes:
node_with_embedding = node.model_copy()
node_with_embedding.embedding = id_to_embed_map[node.node_id]
summary_nodes_with_embedding.append(node_with_embedding)
self._vector_store.add(summary_nodes_with_embedding)
def _build_index_from_nodes(
self,
nodes: Sequence[BaseNode],
**build_kwargs: Any,
) -> IndexDocumentSummary:
"""Build index from nodes."""
# first get doc_id to nodes_dict, generate a summary for each doc_id,
# then build the index struct
index_struct = IndexDocumentSummary()
self._add_nodes_to_index(index_struct, nodes, self._show_progress)
return index_struct
def _insert(self, nodes: Sequence[BaseNode], **insert_kwargs: Any) -> None:
"""Insert a document."""
self._add_nodes_to_index(self._index_struct, nodes)
def _delete_node(self, node_id: str, **delete_kwargs: Any) -> None:
pass
def delete_nodes(
self,
node_ids: List[str],
delete_from_docstore: bool = False,
**delete_kwargs: Any,
) -> None:
"""
Delete a list of nodes from the index.
Args:
node_ids (List[str]): A list of node_ids from the nodes to delete
"""
index_nodes = self._index_struct.node_id_to_summary_id.keys()
for node in node_ids:
if node not in index_nodes:
logger.warning(f"node_id {node} not found, will not be deleted.")
node_ids.remove(node)
self._index_struct.delete_nodes(node_ids)
remove_summary_ids = [
summary_id
for summary_id in self._index_struct.summary_id_to_node_ids
if len(self._index_struct.summary_id_to_node_ids[summary_id]) == 0
]
remove_docs = [
doc_id
for doc_id in self._index_struct.doc_id_to_summary_id
if self._index_struct.doc_id_to_summary_id[doc_id] in remove_summary_ids
]
for doc_id in remove_docs:
self.delete_ref_doc(doc_id)
def delete_ref_doc(
self, ref_doc_id: str, delete_from_docstore: bool = False, **delete_kwargs: Any
) -> None:
"""
Delete a document from the index.
All nodes in the index related to the document will be deleted.
"""
ref_doc_info = self.docstore.get_ref_doc_info(ref_doc_id)
if ref_doc_info is None:
logger.warning(f"ref_doc_id {ref_doc_id} not found, nothing deleted.")
return
self._index_struct.delete(ref_doc_id)
self._vector_store.delete(ref_doc_id)
if delete_from_docstore:
self.docstore.delete_ref_doc(ref_doc_id, raise_error=False)
self._storage_context.index_store.add_index_struct(self._index_struct)
@property
def ref_doc_info(self) -> Dict[str, RefDocInfo]:
"""Retrieve a dict mapping of ingested documents and their nodes+metadata."""
ref_doc_ids = list(self._index_struct.doc_id_to_summary_id.keys())
all_ref_doc_info = {}
for ref_doc_id in ref_doc_ids:
ref_doc_info = self.docstore.get_ref_doc_info(ref_doc_id)
if not ref_doc_info:
continue
all_ref_doc_info[ref_doc_id] = ref_doc_info
return all_ref_doc_info
# legacy
GPTDocumentSummaryIndex = DocumentSummaryIndex
| DocumentSummaryIndex |
python | getsentry__sentry | tests/sentry/workflow_engine/buffer/test_batch_client.py | {
"start": 237,
"end": 9276
} | class ____:
@pytest.fixture
def mock_buffer(self):
"""Create a mock buffer for testing."""
return Mock(spec=RedisHashSortedSetBuffer)
@pytest.fixture
def buffer_keys(self):
"""Create test buffer keys."""
return ["test_key_1", "test_key_2"]
@pytest.fixture
def delayed_workflow_client(self, mock_buffer):
"""Create a DelayedWorkflowClient with mocked buffer."""
return DelayedWorkflowClient(buf=mock_buffer)
@pytest.fixture
def workflow_client_with_keys(self, mock_buffer, buffer_keys):
"""Create a DelayedWorkflowClient with mocked buffer and specific keys."""
return DelayedWorkflowClient(buf=mock_buffer, buffer_keys=buffer_keys)
def test_mark_project_ids_as_processed(
self, workflow_client_with_keys, mock_buffer, buffer_keys
):
"""Test mark_project_ids_as_processed with mocked RedisHashSortedSetBuffer."""
# Mock the conditional_delete_from_sorted_sets return value
# Return value is dict[str, list[int]] where keys are buffer keys and values are deleted project IDs
mock_return_value = {
"test_key_1": [123, 456],
"test_key_2": [789],
}
mock_buffer.conditional_delete_from_sorted_sets.return_value = mock_return_value
# Input data: project_id -> max_timestamp mapping
project_id_max_timestamps = {
123: 1000.5,
456: 2000.0,
789: 1500.75,
}
# Call the method
result = workflow_client_with_keys.mark_project_ids_as_processed(project_id_max_timestamps)
# Verify the mock was called with the correct arguments
mock_buffer.conditional_delete_from_sorted_sets.assert_called_once_with(
tuple(buffer_keys), # DelayedWorkflowClient stores keys as tuple
[(123, 1000.5), (456, 2000.0), (789, 1500.75)],
)
# Verify the result is the union of all deleted project IDs
expected_result = [123, 456, 789]
assert sorted(result) == sorted(expected_result)
def test_mark_project_ids_as_processed_empty_input(
self, workflow_client_with_keys, mock_buffer, buffer_keys
):
"""Test mark_project_ids_as_processed with empty input."""
# Mock return value for empty input
mock_buffer.conditional_delete_from_sorted_sets.return_value = {
"test_key_1": [],
"test_key_2": [],
}
# Empty input
project_id_max_timestamps: dict[int, float] = {}
# Call the method
result = workflow_client_with_keys.mark_project_ids_as_processed(project_id_max_timestamps)
# Verify the mock was called with empty member list
mock_buffer.conditional_delete_from_sorted_sets.assert_called_once_with(
tuple(buffer_keys),
[],
)
# Result should be empty
assert result == []
def test_mark_project_ids_as_processed_partial_deletion(
self, workflow_client_with_keys, mock_buffer, buffer_keys
):
"""Test mark_project_ids_as_processed when only some project IDs are deleted."""
# Mock return value where only some project IDs are actually deleted
mock_return_value = {
"test_key_1": [123], # Only project 123 was deleted from this key
"test_key_2": [], # No projects deleted from this key
}
mock_buffer.conditional_delete_from_sorted_sets.return_value = mock_return_value
# Input with multiple project IDs
project_id_max_timestamps = {
123: 1000.5,
456: 2000.0, # This one won't be deleted (perhaps timestamp is too old)
}
# Call the method
result = workflow_client_with_keys.mark_project_ids_as_processed(project_id_max_timestamps)
# Verify the mock was called with all input project IDs
mock_buffer.conditional_delete_from_sorted_sets.assert_called_once_with(
tuple(buffer_keys),
[(123, 1000.5), (456, 2000.0)],
)
# Result should only contain the actually deleted project IDs
assert result == [123]
def test_mark_project_ids_as_processed_deduplicates_results(
self, workflow_client_with_keys, mock_buffer, buffer_keys
):
"""Test that mark_project_ids_as_processed deduplicates project IDs from multiple keys."""
# Mock return value where the same project ID appears in multiple keys
mock_return_value = {
"test_key_1": [123, 456],
"test_key_2": [456, 789], # 456 appears in both keys
}
mock_buffer.conditional_delete_from_sorted_sets.return_value = mock_return_value
# Input data
project_id_max_timestamps = {
123: 1000.5,
456: 2000.0,
789: 1500.75,
}
# Call the method
result = workflow_client_with_keys.mark_project_ids_as_processed(project_id_max_timestamps)
# Verify the result deduplicates project ID 456
expected_result = [123, 456, 789]
assert sorted(result) == sorted(expected_result)
assert len(result) == 3 # Should have exactly 3 unique project IDs
def test_fetch_updates(self, delayed_workflow_client, mock_buffer):
"""Test fetching cohort updates from buffer."""
expected_updates = CohortUpdates(values={1: 100.0})
mock_buffer.get_parsed_key.return_value = expected_updates
result = delayed_workflow_client.fetch_updates()
mock_buffer.get_parsed_key.assert_called_once_with(
"WORKFLOW_ENGINE_COHORT_UPDATES", CohortUpdates
)
assert result == expected_updates
def test_persist_updates(self, delayed_workflow_client, mock_buffer):
"""Test persisting cohort updates to buffer."""
updates = CohortUpdates(values={1: 100.0, 2: 200.0})
delayed_workflow_client.persist_updates(updates)
mock_buffer.put_parsed_key.assert_called_once_with(
"WORKFLOW_ENGINE_COHORT_UPDATES", updates
)
def test_fetch_updates_missing_key(self, delayed_workflow_client, mock_buffer):
"""Test fetching cohort updates when key doesn't exist (returns None)."""
mock_buffer.get_parsed_key.return_value = None
result = delayed_workflow_client.fetch_updates()
mock_buffer.get_parsed_key.assert_called_once_with(
"WORKFLOW_ENGINE_COHORT_UPDATES", CohortUpdates
)
assert isinstance(result, CohortUpdates)
assert result.values == {} # Should be default empty dict
def test_add_project_ids(self, delayed_workflow_client, mock_buffer):
"""Test adding project IDs to a random shard."""
project_ids = [1, 2, 3]
delayed_workflow_client.add_project_ids(project_ids)
# Should call push_to_sorted_set with one of the buffer keys
assert mock_buffer.push_to_sorted_set.call_count == 1
call_args = mock_buffer.push_to_sorted_set.call_args
assert call_args[1]["value"] == project_ids
# Key should be one of the expected buffer keys
called_key = call_args[1]["key"]
expected_keys = DelayedWorkflowClient._get_buffer_keys()
assert called_key in expected_keys
def test_get_project_ids(self, delayed_workflow_client, mock_buffer):
"""Test getting project IDs within score range."""
expected_result = {1: [100.0], 2: [200.0]}
mock_buffer.bulk_get_sorted_set.return_value = expected_result
result = delayed_workflow_client.get_project_ids(min=0.0, max=300.0)
mock_buffer.bulk_get_sorted_set.assert_called_once_with(
tuple(DelayedWorkflowClient._get_buffer_keys()),
min=0.0,
max=300.0,
)
assert result == expected_result
def test_clear_project_ids(self, delayed_workflow_client, mock_buffer):
"""Test clearing project IDs within score range."""
delayed_workflow_client.clear_project_ids(min=0.0, max=300.0)
mock_buffer.delete_keys.assert_called_once_with(
tuple(DelayedWorkflowClient._get_buffer_keys()),
min=0.0,
max=300.0,
)
def test_get_buffer_keys(self):
"""Test that buffer keys are generated correctly."""
keys = DelayedWorkflowClient._get_buffer_keys()
assert len(keys) == 8 # _BUFFER_SHARDS
assert keys[0] == "workflow_engine_delayed_processing_buffer" # shard 0
assert keys[1] == "workflow_engine_delayed_processing_buffer:1" # shard 1
assert keys[7] == "workflow_engine_delayed_processing_buffer:7" # shard 7
def test_for_project(self, delayed_workflow_client, mock_buffer):
"""Test creating a project-specific client."""
project_id = 123
project_client = delayed_workflow_client.for_project(project_id)
assert project_client.project_id == project_id
assert project_client._buffer == mock_buffer
| TestDelayedWorkflowClient |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/vertex_ai/test_hyperparameter_tuning_job.py | {
"start": 4677,
"end": 7740
} | class ____:
def setup_method(self):
with mock.patch(
BASE_STRING.format("GoogleBaseHook.__init__"), new=mock_base_gcp_hook_default_project_id
):
self.hook = HyperparameterTuningJobHook(gcp_conn_id=TEST_GCP_CONN_ID)
@mock.patch(HYPERPARAMETER_TUNING_JOB_HOOK_STRING.format("get_job_service_client"))
def test_delete_hyperparameter_tuning_job(self, mock_client) -> None:
self.hook.delete_hyperparameter_tuning_job(
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
hyperparameter_tuning_job=TEST_HYPERPARAMETER_TUNING_JOB_ID,
)
mock_client.assert_called_once_with(TEST_REGION)
mock_client.return_value.delete_hyperparameter_tuning_job.assert_called_once_with(
request=dict(
name=mock_client.return_value.hyperparameter_tuning_job_path.return_value,
),
metadata=(),
retry=DEFAULT,
timeout=None,
)
mock_client.return_value.hyperparameter_tuning_job_path.assert_called_once_with(
TEST_PROJECT_ID,
TEST_REGION,
TEST_HYPERPARAMETER_TUNING_JOB_ID,
)
@mock.patch(HYPERPARAMETER_TUNING_JOB_HOOK_STRING.format("get_job_service_client"))
def test_get_hyperparameter_tuning_job(self, mock_client) -> None:
self.hook.get_hyperparameter_tuning_job(
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
hyperparameter_tuning_job=TEST_HYPERPARAMETER_TUNING_JOB_ID,
)
mock_client.assert_called_once_with(TEST_REGION)
mock_client.return_value.get_hyperparameter_tuning_job.assert_called_once_with(
request=dict(
name=mock_client.return_value.hyperparameter_tuning_job_path.return_value,
),
metadata=(),
retry=DEFAULT,
timeout=None,
)
mock_client.return_value.hyperparameter_tuning_job_path.assert_called_once_with(
TEST_PROJECT_ID,
TEST_REGION,
TEST_HYPERPARAMETER_TUNING_JOB_ID,
)
@mock.patch(HYPERPARAMETER_TUNING_JOB_HOOK_STRING.format("get_job_service_client"))
def test_list_hyperparameter_tuning_jobs(self, mock_client) -> None:
self.hook.list_hyperparameter_tuning_jobs(
project_id=TEST_PROJECT_ID,
region=TEST_REGION,
)
mock_client.assert_called_once_with(TEST_REGION)
mock_client.return_value.list_hyperparameter_tuning_jobs.assert_called_once_with(
request=dict(
parent=mock_client.return_value.common_location_path.return_value,
filter=None,
page_size=None,
page_token=None,
read_mask=None,
),
metadata=(),
retry=DEFAULT,
timeout=None,
)
mock_client.return_value.common_location_path.assert_called_once_with(TEST_PROJECT_ID, TEST_REGION)
| TestHyperparameterTuningJobWithDefaultProjectIdHook |
python | sympy__sympy | sympy/stats/symbolic_multivariate_probability.py | {
"start": 6730,
"end": 10450
} | class ____(Covariance, MatrixExpr):
"""
Covariance of a random matrix probability expression.
Examples
========
>>> from sympy.stats import CrossCovarianceMatrix
>>> from sympy.stats.rv import RandomMatrixSymbol
>>> from sympy import symbols, MatrixSymbol
>>> k = symbols("k")
>>> A, B = MatrixSymbol("A", k, k), MatrixSymbol("B", k, k)
>>> C, D = MatrixSymbol("C", k, k), MatrixSymbol("D", k, k)
>>> X, Y = RandomMatrixSymbol("X", k, 1), RandomMatrixSymbol("Y", k, 1)
>>> Z, W = RandomMatrixSymbol("Z", k, 1), RandomMatrixSymbol("W", k, 1)
>>> CrossCovarianceMatrix(X, Y)
CrossCovarianceMatrix(X, Y)
>>> CrossCovarianceMatrix(X, Y).shape
(k, k)
To expand the covariance in its expression, use ``expand()``:
>>> CrossCovarianceMatrix(X + Y, Z).expand()
CrossCovarianceMatrix(X, Z) + CrossCovarianceMatrix(Y, Z)
>>> CrossCovarianceMatrix(A*X, Y).expand()
A*CrossCovarianceMatrix(X, Y)
>>> CrossCovarianceMatrix(A*X, B.T*Y).expand()
A*CrossCovarianceMatrix(X, Y)*B
>>> CrossCovarianceMatrix(A*X + B*Y, C.T*Z + D.T*W).expand()
A*CrossCovarianceMatrix(X, W)*D + A*CrossCovarianceMatrix(X, Z)*C + B*CrossCovarianceMatrix(Y, W)*D + B*CrossCovarianceMatrix(Y, Z)*C
"""
def __new__(cls, arg1, arg2, condition=None):
arg1 = _sympify(arg1)
arg2 = _sympify(arg2)
if (1 not in arg1.shape) or (1 not in arg2.shape) or (arg1.shape[1] != arg2.shape[1]):
raise ShapeError("Expression is not a vector")
shape = (arg1.shape[0], arg2.shape[0]) if arg1.shape[1] == 1 and arg2.shape[1] == 1 \
else (1, 1)
if condition:
obj = Expr.__new__(cls, arg1, arg2, condition)
else:
obj = Expr.__new__(cls, arg1, arg2)
obj._shape = shape
obj._condition = condition
return obj
@property
def shape(self):
return self._shape
def expand(self, **hints):
arg1 = self.args[0]
arg2 = self.args[1]
condition = self._condition
if arg1 == arg2:
return VarianceMatrix(arg1, condition).expand()
if not is_random(arg1) or not is_random(arg2):
return ZeroMatrix(*self.shape)
if isinstance(arg1, RandomSymbol) and isinstance(arg2, RandomSymbol):
return CrossCovarianceMatrix(arg1, arg2, condition)
coeff_rv_list1 = self._expand_single_argument(arg1.expand())
coeff_rv_list2 = self._expand_single_argument(arg2.expand())
addends = [a*CrossCovarianceMatrix(r1, r2, condition=condition)*b.transpose()
for (a, r1) in coeff_rv_list1 for (b, r2) in coeff_rv_list2]
return Add.fromiter(addends)
@classmethod
def _expand_single_argument(cls, expr):
# return (coefficient, random_symbol) pairs:
if isinstance(expr, RandomSymbol):
return [(S.One, expr)]
elif isinstance(expr, Add):
outval = []
for a in expr.args:
if isinstance(a, (Mul, MatMul)):
outval.append(cls._get_mul_nonrv_rv_tuple(a))
elif is_random(a):
outval.append((S.One, a))
return outval
elif isinstance(expr, (Mul, MatMul)):
return [cls._get_mul_nonrv_rv_tuple(expr)]
elif is_random(expr):
return [(S.One, expr)]
@classmethod
def _get_mul_nonrv_rv_tuple(cls, m):
rv = []
nonrv = []
for a in m.args:
if is_random(a):
rv.append(a)
else:
nonrv.append(a)
return (Mul.fromiter(nonrv), Mul.fromiter(rv))
| CrossCovarianceMatrix |
python | PyCQA__pylint | tests/functional/u/use/use_maxsplit_arg.py | {
"start": 1435,
"end": 2491
} | class ____():
class_str = '1,2,3'
def __init__(self):
self.my_str = '1,2,3'
def get_string(self) -> str:
return self.my_str
# Class attributes
get_first = Foo.class_str.split(',')[0] # [use-maxsplit-arg]
get_last = Foo.class_str.split(',')[-1] # [use-maxsplit-arg]
get_first = Foo.class_str.rsplit(',')[0] # [use-maxsplit-arg]
get_last = Foo.class_str.rsplit(',')[-1] # [use-maxsplit-arg]
get_mid = Foo.class_str.split(',')[1]
get_mid = Foo.class_str.split(',')[-2]
# Test with accessors
test = Foo()
get_first = test.get_string().split(',')[0] # [use-maxsplit-arg]
get_last = test.get_string().split(',')[-1] # [use-maxsplit-arg]
get_mid = test.get_string().split(',')[1]
get_mid = test.get_string().split(',')[-2]
# Test with iterating over strings
list_of_strs = ["a", "b", "c", "d", "e", "f"]
for s in list_of_strs:
print(s.split(" ")[0]) # [use-maxsplit-arg]
print(s.split(" ")[-1]) # [use-maxsplit-arg]
print(s.split(" ")[-2])
# Test warning messages (matching and replacing .split / .rsplit)
| Foo |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/test_system_message.py | {
"start": 24857,
"end": 27614
} | class ____:
"""Test metadata merging behavior when updating system messages."""
@pytest.mark.parametrize(
"metadata_type,initial_metadata,update_metadata,expected_result",
[
# additional_kwargs merging
(
"additional_kwargs",
{"key1": "value1", "shared": "original"},
{"key2": "value2", "shared": "updated"},
{"key1": "value1", "key2": "value2", "shared": "updated"},
),
# response_metadata merging
(
"response_metadata",
{"model": "gpt-4", "region": "us-east"},
{"tokens": 100, "region": "eu-west"},
{"model": "gpt-4", "tokens": 100, "region": "eu-west"},
),
],
ids=["additional_kwargs", "response_metadata"],
)
def test_metadata_merge_across_updates(
self, metadata_type, initial_metadata, update_metadata, expected_result
) -> None:
"""Test that metadata merges correctly when updating system message."""
base_message = SystemMessage(
content="Base",
**{metadata_type: initial_metadata},
)
def update_middleware(request: ModelRequest, handler) -> ModelResponse:
"""Update system message, merging metadata."""
current_metadata = getattr(request.system_message, metadata_type)
new_metadata = {**current_metadata, **update_metadata}
new_request = request.override(
system_message=SystemMessage(content="Updated", **{metadata_type: new_metadata})
)
return handler(new_request)
model = GenericFakeChatModel(messages=iter([AIMessage(content="response")]))
request = ModelRequest(
model=model,
system_message=base_message,
messages=[],
tool_choice=None,
tools=[],
response_format=None,
state=cast("AgentState", {"messages": []}), # type: ignore[name-defined]
runtime=_fake_runtime(),
)
captured_request = None
def mock_handler(req: ModelRequest) -> ModelResponse:
nonlocal captured_request
captured_request = req
return ModelResponse(result=[AIMessage(content="response")])
update_middleware(request, mock_handler)
assert captured_request is not None
assert getattr(captured_request.system_message, metadata_type) == expected_result
# =============================================================================
# Dynamic System Prompt Middleware Tests
# =============================================================================
| TestMetadataMerging |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_self/SLF001_1.py | {
"start": 767,
"end": 858
} | class ____(type):
@classmethod
def f(mcs):
cls = mcs()
cls._value = 1
| M |
python | huggingface__transformers | src/transformers/models/data2vec/modeling_data2vec_audio.py | {
"start": 37675,
"end": 42633
} | class ____(Data2VecAudioPreTrainedModel):
def __init__(self, config):
super().__init__(config)
if hasattr(config, "add_adapter") and config.add_adapter:
raise ValueError(
"Sequence classification does not support the use of Data2VecAudio adapters (config.add_adapter=True)"
)
self.data2vec_audio = Data2VecAudioModel(config)
num_layers = config.num_hidden_layers + 1 # transformer layers + input embeddings
if config.use_weighted_layer_sum:
self.layer_weights = nn.Parameter(torch.ones(num_layers) / num_layers)
self.projector = nn.Linear(config.hidden_size, config.classifier_proj_size)
self.classifier = nn.Linear(config.classifier_proj_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
def freeze_feature_encoder(self):
"""
Calling this function will disable the gradient computation for the feature encoder so that its parameter will
not be updated during training.
"""
self.data2vec_audio.feature_extractor._freeze_parameters()
def freeze_base_model(self):
"""
Calling this function will disable the gradient computation for the base model so that its parameters will not
be updated during training. Only the classification head will be updated.
"""
for param in self.data2vec_audio.parameters():
param.requires_grad = False
@auto_docstring
def forward(
self,
input_values: Optional[torch.Tensor],
attention_mask: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
labels: Optional[torch.Tensor] = None,
) -> Union[tuple, SequenceClassifierOutput]:
r"""
input_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
(`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
into a tensor of type `torch.FloatTensor`. See [`Data2VecAudioProcessor.__call__`] for details.
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
output_hidden_states = True if self.config.use_weighted_layer_sum else output_hidden_states
outputs = self.data2vec_audio(
input_values,
attention_mask=attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
if self.config.use_weighted_layer_sum:
hidden_states = outputs[_HIDDEN_STATES_START_POSITION]
hidden_states = torch.stack(hidden_states, dim=1)
norm_weights = nn.functional.softmax(self.layer_weights, dim=-1)
hidden_states = (hidden_states * norm_weights.view(-1, 1, 1)).sum(dim=1)
else:
hidden_states = outputs[0]
hidden_states = self.projector(hidden_states)
if attention_mask is None:
pooled_output = hidden_states.mean(dim=1)
else:
padding_mask = self._get_feature_vector_attention_mask(hidden_states.shape[1], attention_mask)
expand_padding_mask = padding_mask.unsqueeze(-1).repeat(1, 1, hidden_states.shape[2])
hidden_states[~expand_padding_mask] = 0.0
pooled_output = hidden_states.sum(dim=1) / padding_mask.sum(dim=1).view(-1, 1)
logits = self.classifier(pooled_output)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
if not return_dict:
output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@auto_docstring
| Data2VecAudioForSequenceClassification |
python | sympy__sympy | sympy/testing/tests/test_code_quality.py | {
"start": 4871,
"end": 19213
} | class ____(ast.NodeVisitor):
"""return the line number corresponding to the
line on which a bare expression appears if it is a binary op
or a comparison that is not in a with block.
EXAMPLES
========
>>> import ast
>>> class _Visit(ast.NodeVisitor):
... def visit_Expr(self, node):
... if isinstance(node.value, (ast.BinOp, ast.Compare)):
... print(node.lineno)
... def visit_With(self, node):
... pass # no checking there
...
>>> code='''x = 1 # line 1
... for i in range(3):
... x == 2 # <-- 3
... if x == 2:
... x == 3 # <-- 5
... x + 1 # <-- 6
... x = 1
... if x == 1:
... print(1)
... while x != 1:
... x == 1 # <-- 11
... with raises(TypeError):
... c == 1
... raise TypeError
... assert x == 1
... '''
>>> _Visit().visit(ast.parse(code))
3
5
6
11
"""
def visit_Expr(self, node):
if isinstance(node.value, (ast.BinOp, ast.Compare)):
assert None, message_bare_expr % ('', node.lineno)
def visit_With(self, node):
pass
BareExpr = _Visit()
def line_with_bare_expr(code):
"""return None or else 0-based line number of code on which
a bare expression appeared.
"""
tree = ast.parse(code)
try:
BareExpr.visit(tree)
except AssertionError as msg:
assert msg.args
msg = msg.args[0]
assert msg.startswith(message_bare_expr.split(':', 1)[0])
return int(msg.rsplit(' ', 1)[1].rstrip('.')) # the line number
def test_files():
"""
This test tests all files in SymPy and checks that:
o no lines contains a trailing whitespace
o no lines end with \r\n
o no line uses tabs instead of spaces
o that the file ends with a single newline
o there are no general or string exceptions
o there are no old style raise statements
o name of arg-less test suite functions start with _ or test_
o no duplicate function names that start with test_
o no assignments to self variable in class methods
o no lines contain ".func is" except in the test suite
o there is no do-nothing expression like `a == b` or `x + 1`
"""
def test(fname):
with open(fname, encoding="utf8") as test_file:
test_this_file(fname, test_file)
with open(fname, encoding='utf8') as test_file:
_test_this_file_encoding(fname, test_file)
def test_this_file(fname, test_file):
idx = None
code = test_file.read()
test_file.seek(0) # restore reader to head
py = fname if sep not in fname else fname.rsplit(sep, 1)[-1]
if py.startswith('test_'):
idx = line_with_bare_expr(code)
if idx is not None:
assert False, message_bare_expr % (fname, idx + 1)
line = None # to flag the case where there were no lines in file
tests = 0
test_set = set()
for idx, line in enumerate(test_file):
if test_file_re.match(fname):
if test_suite_def_re.match(line):
assert False, message_test_suite_def % (fname, idx + 1)
if test_ok_def_re.match(line):
tests += 1
test_set.add(line[3:].split('(')[0].strip())
if len(test_set) != tests:
assert False, message_duplicate_test % (fname, idx + 1)
if line.endswith((" \n", "\t\n")):
assert False, message_space % (fname, idx + 1)
if line.endswith("\r\n"):
assert False, message_carriage % (fname, idx + 1)
if tab_in_leading(line):
assert False, message_tabs % (fname, idx + 1)
if str_raise_re.search(line):
assert False, message_str_raise % (fname, idx + 1)
if gen_raise_re.search(line):
assert False, message_gen_raise % (fname, idx + 1)
if (implicit_test_re.search(line) and
not list(filter(lambda ex: ex in fname, import_exclude))):
assert False, message_implicit % (fname, idx + 1)
if func_is_re.search(line) and not test_file_re.search(fname):
assert False, message_func_is % (fname, idx + 1)
result = old_raise_re.search(line)
if result is not None:
assert False, message_old_raise % (
fname, idx + 1, result.group(2))
if line is not None:
if line == '\n' and idx > 0:
assert False, message_multi_eof % (fname, idx + 1)
elif not line.endswith('\n'):
# eof newline check
assert False, message_eof % (fname, idx + 1)
# Files to test at top level
top_level_files = [join(TOP_PATH, file) for file in [
"isympy.py",
"build.py",
"setup.py",
]]
# Files to exclude from all tests
exclude = {
"%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevparser.py" % sepd,
"%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlexer.py" % sepd,
"%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlistener.py" % sepd,
"%(sep)ssympy%(sep)sparsing%(sep)slatex%(sep)s_antlr%(sep)slatexparser.py" % sepd,
"%(sep)ssympy%(sep)sparsing%(sep)slatex%(sep)s_antlr%(sep)slatexlexer.py" % sepd,
}
# Files to exclude from the implicit import test
import_exclude = {
# glob imports are allowed in top-level __init__.py:
"%(sep)ssympy%(sep)s__init__.py" % sepd,
# these __init__.py should be fixed:
# XXX: not really, they use useful import pattern (DRY)
"%(sep)svector%(sep)s__init__.py" % sepd,
"%(sep)smechanics%(sep)s__init__.py" % sepd,
"%(sep)squantum%(sep)s__init__.py" % sepd,
"%(sep)spolys%(sep)s__init__.py" % sepd,
"%(sep)spolys%(sep)sdomains%(sep)s__init__.py" % sepd,
# interactive SymPy executes ``from sympy import *``:
"%(sep)sinteractive%(sep)ssession.py" % sepd,
# isympy.py executes ``from sympy import *``:
"%(sep)sisympy.py" % sepd,
# these two are import timing tests:
"%(sep)sbin%(sep)ssympy_time.py" % sepd,
"%(sep)sbin%(sep)ssympy_time_cache.py" % sepd,
# Taken from Python stdlib:
"%(sep)sparsing%(sep)ssympy_tokenize.py" % sepd,
# this one should be fixed:
"%(sep)splotting%(sep)spygletplot%(sep)s" % sepd,
# False positive in the docstring
"%(sep)sbin%(sep)stest_external_imports.py" % sepd,
"%(sep)sbin%(sep)stest_submodule_imports.py" % sepd,
# These are deprecated stubs that can be removed at some point:
"%(sep)sutilities%(sep)sruntests.py" % sepd,
"%(sep)sutilities%(sep)spytest.py" % sepd,
"%(sep)sutilities%(sep)srandtest.py" % sepd,
"%(sep)sutilities%(sep)stmpfiles.py" % sepd,
"%(sep)sutilities%(sep)squality_unicode.py" % sepd,
}
check_files(top_level_files, test)
check_directory_tree(BIN_PATH, test, {"~", ".pyc", ".sh"}, "*")
check_directory_tree(SYMPY_PATH, test, exclude)
check_directory_tree(EXAMPLES_PATH, test, exclude)
def _with_space(c):
# return c with a random amount of leading space
return random.randint(0, 10)*' ' + c
def test_raise_statement_regular_expression():
candidates_ok = [
"some text # raise Exception, 'text'",
"raise ValueError('text') # raise Exception, 'text'",
"raise ValueError('text')",
"raise ValueError",
"raise ValueError('text')",
"raise ValueError('text') #,",
# Talking about an exception in a docstring
''''"""This function will raise ValueError, except when it doesn't"""''',
"raise (ValueError('text')",
]
str_candidates_fail = [
"raise 'exception'",
"raise 'Exception'",
'raise "exception"',
'raise "Exception"',
"raise 'ValueError'",
]
gen_candidates_fail = [
"raise Exception('text') # raise Exception, 'text'",
"raise Exception('text')",
"raise Exception",
"raise Exception('text')",
"raise Exception('text') #,",
"raise Exception, 'text'",
"raise Exception, 'text' # raise Exception('text')",
"raise Exception, 'text' # raise Exception, 'text'",
">>> raise Exception, 'text'",
">>> raise Exception, 'text' # raise Exception('text')",
">>> raise Exception, 'text' # raise Exception, 'text'",
]
old_candidates_fail = [
"raise Exception, 'text'",
"raise Exception, 'text' # raise Exception('text')",
"raise Exception, 'text' # raise Exception, 'text'",
">>> raise Exception, 'text'",
">>> raise Exception, 'text' # raise Exception('text')",
">>> raise Exception, 'text' # raise Exception, 'text'",
"raise ValueError, 'text'",
"raise ValueError, 'text' # raise Exception('text')",
"raise ValueError, 'text' # raise Exception, 'text'",
">>> raise ValueError, 'text'",
">>> raise ValueError, 'text' # raise Exception('text')",
">>> raise ValueError, 'text' # raise Exception, 'text'",
"raise(ValueError,",
"raise (ValueError,",
"raise( ValueError,",
"raise ( ValueError,",
"raise(ValueError ,",
"raise (ValueError ,",
"raise( ValueError ,",
"raise ( ValueError ,",
]
for c in candidates_ok:
assert str_raise_re.search(_with_space(c)) is None, c
assert gen_raise_re.search(_with_space(c)) is None, c
assert old_raise_re.search(_with_space(c)) is None, c
for c in str_candidates_fail:
assert str_raise_re.search(_with_space(c)) is not None, c
for c in gen_candidates_fail:
assert gen_raise_re.search(_with_space(c)) is not None, c
for c in old_candidates_fail:
assert old_raise_re.search(_with_space(c)) is not None, c
def test_implicit_imports_regular_expression():
candidates_ok = [
"from sympy import something",
">>> from sympy import something",
"from sympy.somewhere import something",
">>> from sympy.somewhere import something",
"import sympy",
">>> import sympy",
"import sympy.something.something",
"... import sympy",
"... import sympy.something.something",
"... from sympy import something",
"... from sympy.somewhere import something",
">> from sympy import *", # To allow 'fake' docstrings
"# from sympy import *",
"some text # from sympy import *",
]
candidates_fail = [
"from sympy import *",
">>> from sympy import *",
"from sympy.somewhere import *",
">>> from sympy.somewhere import *",
"... from sympy import *",
"... from sympy.somewhere import *",
]
for c in candidates_ok:
assert implicit_test_re.search(_with_space(c)) is None, c
for c in candidates_fail:
assert implicit_test_re.search(_with_space(c)) is not None, c
def test_test_suite_defs():
candidates_ok = [
" def foo():\n",
"def foo(arg):\n",
"def _foo():\n",
"def test_foo():\n",
]
candidates_fail = [
"def foo():\n",
"def foo() :\n",
"def foo( ):\n",
"def foo():\n",
]
for c in candidates_ok:
assert test_suite_def_re.search(c) is None, c
for c in candidates_fail:
assert test_suite_def_re.search(c) is not None, c
def test_test_duplicate_defs():
candidates_ok = [
"def foo():\ndef foo():\n",
"def test():\ndef test_():\n",
"def test_():\ndef test__():\n",
]
candidates_fail = [
"def test_():\ndef test_ ():\n",
"def test_1():\ndef test_1():\n",
]
ok = (None, 'check')
def check(file):
tests = 0
test_set = set()
for idx, line in enumerate(file.splitlines()):
if test_ok_def_re.match(line):
tests += 1
test_set.add(line[3:].split('(')[0].strip())
if len(test_set) != tests:
return False, message_duplicate_test % ('check', idx + 1)
return None, 'check'
for c in candidates_ok:
assert check(c) == ok
for c in candidates_fail:
assert check(c) != ok
def test_find_self_assignments():
candidates_ok = [
"class A(object):\n def foo(self, arg): arg = self\n",
"class A(object):\n def foo(self, arg): self.prop = arg\n",
"class A(object):\n def foo(self, arg): obj, obj2 = arg, self\n",
"class A(object):\n @classmethod\n def bar(cls, arg): arg = cls\n",
"class A(object):\n def foo(var, arg): arg = var\n",
]
candidates_fail = [
"class A(object):\n def foo(self, arg): self = arg\n",
"class A(object):\n def foo(self, arg): obj, self = arg, arg\n",
"class A(object):\n def foo(self, arg):\n if arg: self = arg",
"class A(object):\n @classmethod\n def foo(cls, arg): cls = arg\n",
"class A(object):\n def foo(var, arg): var = arg\n",
]
for c in candidates_ok:
assert find_self_assignments(c) == []
for c in candidates_fail:
assert find_self_assignments(c) != []
def test_test_unicode_encoding():
unicode_whitelist = ['foo']
unicode_strict_whitelist = ['bar']
fname = 'abc'
test_file = ['α']
raises(AssertionError, lambda: _test_this_file_encoding(
fname, test_file, unicode_whitelist, unicode_strict_whitelist))
fname = 'abc'
test_file = ['abc']
_test_this_file_encoding(
fname, test_file, unicode_whitelist, unicode_strict_whitelist)
fname = 'foo'
test_file = ['abc']
raises(AssertionError, lambda: _test_this_file_encoding(
fname, test_file, unicode_whitelist, unicode_strict_whitelist))
fname = 'bar'
test_file = ['abc']
_test_this_file_encoding(
fname, test_file, unicode_whitelist, unicode_strict_whitelist)
| _Visit |
python | walkccc__LeetCode | solutions/3513. Number of Unique XOR Triplets I/3513.py | {
"start": 0,
"end": 158
} | class ____:
def uniqueXorTriplets(self, nums: list[int]) -> int:
n = len(nums)
if n < 3:
return n
return 1 << (int(math.log2(n)) + 1)
| Solution |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/ndb/async/app_async.py | {
"start": 669,
"end": 738
} | class ____(ndb.Model):
view_counter = ndb.IntegerProperty()
| Account |
python | keon__algorithms | tests/test_graph.py | {
"start": 4514,
"end": 5037
} | class ____(unittest.TestCase):
"""
Test for the file def maximum_flow_bfs.py
Arguments:
unittest {[type]} -- [description]
"""
def test_maximum_flow_bfs(self):
graph = [
[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]
]
maximum_flow = maximum_flow_bfs(graph)
self.assertEqual(maximum_flow, 23)
| TestMaximum_Flow_Bfs |
python | Pylons__pyramid | tests/test_scripts/test_prequest.py | {
"start": 63,
"end": 8832
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.scripts.prequest import PRequestCommand
return PRequestCommand
def _makeOne(self, argv, headers=None):
cmd = self._getTargetClass()(argv)
def helloworld(environ, start_request):
self._environ = environ
self._path_info = environ['PATH_INFO']
start_request('200 OK', headers or [])
return [b'abc']
self.loader = dummy.DummyLoader(app=helloworld)
self._out = []
cmd._get_config_loader = self.loader
cmd.out = self.out
return cmd
def out(self, msg):
self._out.append(msg)
def test_command_not_enough_args(self):
command = self._makeOne([])
command.run()
self.assertEqual(
self._out, ['You must provide at least two arguments']
)
def test_command_two_args(self):
command = self._makeOne(
['', 'development.ini', '/'],
[('Content-Type', 'text/html; charset=UTF-8')],
)
command.run()
self.assertEqual(self._path_info, '/')
self.assertEqual(self.loader.uri.path, 'development.ini')
self.assertEqual(self.loader.calls[0]['op'], 'logging')
self.assertEqual(self.loader.calls[1]['op'], 'app')
self.assertEqual(self.loader.calls[1]['name'], None)
self.assertEqual(self._out, ['abc'])
def test_command_path_doesnt_start_with_slash(self):
command = self._makeOne(
['', 'development.ini', 'abc'],
[('Content-Type', 'text/html; charset=UTF-8')],
)
command.run()
self.assertEqual(self._path_info, '/abc')
self.assertEqual(self.loader.uri.path, 'development.ini')
self.assertEqual(self._out, ['abc'])
def test_command_has_bad_config_header(self):
command = self._makeOne(['', '--header=name', 'development.ini', '/'])
command.run()
self.assertEqual(
self._out[0],
(
"Bad --header=name option, value must be in the form "
"'name:value'"
),
)
def test_command_has_good_header_var(self):
command = self._makeOne(
['', '--header=name:value', 'development.ini', '/'],
[('Content-Type', 'text/html; charset=UTF-8')],
)
command.run()
self.assertEqual(self._environ['HTTP_NAME'], 'value')
self.assertEqual(self._path_info, '/')
self.assertEqual(self._out, ['abc'])
def test_command_w_basic_auth(self):
command = self._makeOne(
[
'',
'--login=user:password',
'--header=name:value',
'development.ini',
'/',
],
[('Content-Type', 'text/html; charset=UTF-8')],
)
command.run()
self.assertEqual(self._environ['HTTP_NAME'], 'value')
self.assertEqual(
self._environ['HTTP_AUTHORIZATION'], 'Basic dXNlcjpwYXNzd29yZA=='
)
self.assertEqual(self._path_info, '/')
self.assertEqual(self._out, ['abc'])
def test_command_has_content_type_header_var(self):
command = self._makeOne(
['', '--header=content-type:app/foo', 'development.ini', '/'],
[('Content-Type', 'text/html; charset=UTF-8')],
)
command.run()
self.assertEqual(self._environ['CONTENT_TYPE'], 'app/foo')
self.assertEqual(self._path_info, '/')
self.assertEqual(self._out, ['abc'])
def test_command_has_multiple_header_vars(self):
command = self._makeOne(
[
'',
'--header=name:value',
'--header=name2:value2',
'development.ini',
'/',
],
[('Content-Type', 'text/html; charset=UTF-8')],
)
command.run()
self.assertEqual(self._environ['HTTP_NAME'], 'value')
self.assertEqual(self._environ['HTTP_NAME2'], 'value2')
self.assertEqual(self._path_info, '/')
self.assertEqual(self._out, ['abc'])
def test_command_method_get(self):
command = self._makeOne(
['', '--method=GET', 'development.ini', '/'],
[('Content-Type', 'text/html; charset=UTF-8')],
)
command.run()
self.assertEqual(self._environ['REQUEST_METHOD'], 'GET')
self.assertEqual(self._path_info, '/')
self.assertEqual(self._out, ['abc'])
def test_command_method_post(self):
command = self._makeOne(
['', '--method=POST', 'development.ini', '/'],
[('Content-Type', 'text/html; charset=UTF-8')],
)
stdin = StringIO()
command.stdin = stdin
command.run()
self.assertEqual(self._environ['REQUEST_METHOD'], 'POST')
self.assertEqual(self._environ['CONTENT_LENGTH'], '-1')
self.assertEqual(self._environ['wsgi.input'], stdin)
self.assertEqual(self._path_info, '/')
self.assertEqual(self._out, ['abc'])
def test_command_method_put(self):
command = self._makeOne(
['', '--method=PUT', 'development.ini', '/'],
[('Content-Type', 'text/html; charset=UTF-8')],
)
stdin = StringIO()
command.stdin = stdin
command.run()
self.assertEqual(self._environ['REQUEST_METHOD'], 'PUT')
self.assertEqual(self._environ['CONTENT_LENGTH'], '-1')
self.assertEqual(self._environ['wsgi.input'], stdin)
self.assertEqual(self._path_info, '/')
self.assertEqual(self._out, ['abc'])
def test_command_method_patch(self):
command = self._makeOne(
['', '--method=PATCH', 'development.ini', '/'],
[('Content-Type', 'text/html; charset=UTF-8')],
)
stdin = StringIO()
command.stdin = stdin
command.run()
self.assertEqual(self._environ['REQUEST_METHOD'], 'PATCH')
self.assertEqual(self._environ['CONTENT_LENGTH'], '-1')
self.assertEqual(self._environ['wsgi.input'], stdin)
self.assertEqual(self._path_info, '/')
self.assertEqual(self._out, ['abc'])
def test_command_method_propfind(self):
command = self._makeOne(
['', '--method=PROPFIND', 'development.ini', '/'],
[('Content-Type', 'text/html; charset=UTF-8')],
)
stdin = StringIO()
command.stdin = stdin
command.run()
self.assertEqual(self._environ['REQUEST_METHOD'], 'PROPFIND')
self.assertEqual(self._path_info, '/')
self.assertEqual(self._out, ['abc'])
def test_command_method_options(self):
command = self._makeOne(
['', '--method=OPTIONS', 'development.ini', '/'],
[('Content-Type', 'text/html; charset=UTF-8')],
)
stdin = StringIO()
command.stdin = stdin
command.run()
self.assertEqual(self._environ['REQUEST_METHOD'], 'OPTIONS')
self.assertEqual(self._path_info, '/')
self.assertEqual(self._out, ['abc'])
def test_command_with_query_string(self):
command = self._makeOne(
['', 'development.ini', '/abc?a=1&b=2&c'],
[('Content-Type', 'text/html; charset=UTF-8')],
)
command.run()
self.assertEqual(self._environ['QUERY_STRING'], 'a=1&b=2&c')
self.assertEqual(self._path_info, '/abc')
self.assertEqual(self._out, ['abc'])
def test_command_display_headers(self):
command = self._makeOne(
['', '--display-headers', 'development.ini', '/'],
[('Content-Type', 'text/html; charset=UTF-8')],
)
command.run()
self.assertEqual(self._path_info, '/')
self.assertEqual(
self._out,
['200 OK', 'Content-Type: text/html; charset=UTF-8', 'abc'],
)
def test_command_response_has_no_charset(self):
command = self._makeOne(
['', '--method=GET', 'development.ini', '/'],
headers=[('Content-Type', 'image/jpeg')],
)
command.run()
self.assertEqual(self._path_info, '/')
self.assertEqual(self._out, [b'abc'])
def test_command_method_configures_logging(self):
command = self._makeOne(['', '--method=GET', 'development.ini', '/'])
command.run()
self.assertEqual(self.loader.calls[0]['op'], 'logging')
def test_command_script_name(self):
command = self._makeOne(['', '--method=GET', 'development.ini', '/'])
command.run()
self.assertEqual(
self.loader.calls[0]['defaults']['__script__'], 'prequest'
)
| TestPRequestCommand |
python | pytorch__pytorch | test/distributed/checkpoint/_experimental/test_builder.py | {
"start": 732,
"end": 6507
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
# Create a temporary directory for checkpoints
self.temp_dir = tempfile.mkdtemp()
# Create real objects for testing
self.rank_info = RankInfo(
global_world_size=1,
global_rank=0,
)
# Create a test state dictionary
self.state_dict = {
"model": torch.nn.Linear(10, 5).state_dict(),
"optimizer": {"param_groups": [{"lr": 0.01}]},
"epoch": 5,
"step": 1000,
}
def tearDown(self) -> None:
# Clean up the temporary directory
shutil.rmtree(self.temp_dir)
def test_make_sync_checkpointer(self) -> None:
"""Test creating a synchronous checkpointer using make_sync_checkpointer."""
# Create sync checkpointer using factory function with no barrier
config = CheckpointerConfig(barrier_config=BarrierConfig(barrier_type=None))
checkpointer = make_sync_checkpointer(config=config, rank_info=self.rank_info)
# Verify it's a SyncCheckpointer instance
self.assertIsInstance(checkpointer, SyncCheckpointer)
# Test that it works for sync operations
checkpoint_path = os.path.join(self.temp_dir, "checkpoint_factory_sync")
result = checkpointer.save(checkpoint_path, self.state_dict)
self.assertIsNone(result) # Sync mode returns None
# Verify checkpoint was created
checkpoint_file = os.path.join(
checkpoint_path, f"checkpoint_{self.rank_info.global_rank}.pt"
)
self.assertTrue(os.path.exists(checkpoint_file))
# Test loading
loaded_state_dict = checkpointer.load(checkpoint_path)
self.assertEqual(loaded_state_dict["epoch"], 5)
def test_make_sync_checkpointer_with_config_first(self) -> None:
"""Test creating a synchronous checkpointer with config as first parameter."""
# Create sync checkpointer with config as first parameter
config = CheckpointerConfig(barrier_config=BarrierConfig(barrier_type=None))
checkpointer = make_sync_checkpointer(config=config, rank_info=self.rank_info)
# Verify it's a SyncCheckpointer instance
self.assertIsInstance(checkpointer, SyncCheckpointer)
# Test that it works for sync operations
checkpoint_path = os.path.join(
self.temp_dir, "checkpoint_factory_sync_config_first"
)
result = checkpointer.save(checkpoint_path, self.state_dict)
self.assertIsNone(result) # Sync mode returns None
# Verify checkpoint was created
checkpoint_file = os.path.join(
checkpoint_path, f"checkpoint_{self.rank_info.global_rank}.pt"
)
self.assertTrue(os.path.exists(checkpoint_file))
def test_make_sync_checkpointer_with_custom_config(self) -> None:
"""Test creating a synchronous checkpointer with a custom config."""
# Create a custom config with no barrier
config = CheckpointerConfig(barrier_config=BarrierConfig(barrier_type=None))
# Create sync checkpointer with the custom config
checkpointer = make_sync_checkpointer(rank_info=self.rank_info, config=config)
# Verify it's a SyncCheckpointer instance
self.assertIsInstance(checkpointer, SyncCheckpointer)
# Test that it works for sync operations
checkpoint_path = os.path.join(
self.temp_dir, "checkpoint_factory_sync_custom_config"
)
result = checkpointer.save(checkpoint_path, self.state_dict)
self.assertIsNone(result) # Sync mode returns None
# Verify checkpoint was created
checkpoint_file = os.path.join(
checkpoint_path, f"checkpoint_{self.rank_info.global_rank}.pt"
)
self.assertTrue(os.path.exists(checkpoint_file))
# Test loading
loaded_state_dict = checkpointer.load(checkpoint_path)
self.assertEqual(loaded_state_dict["epoch"], 5)
def test_make_async_checkpointer(self) -> None:
"""Test creating an asynchronous checkpointer using make_async_checkpointer."""
# Create async checkpointer using factory function with default parameters
config: CheckpointerConfig = CheckpointerConfig()
config.staging_config = CheckpointStagerConfig(
use_non_blocking_copy=torch.accelerator.is_available(),
use_pinned_memory=torch.accelerator.is_available(),
)
checkpointer = make_async_checkpointer(config=config, rank_info=self.rank_info)
try:
# Verify it's an AsyncCheckpointer instance
self.assertIsInstance(checkpointer, AsyncCheckpointer)
# Test that it works for async operations
checkpoint_path = os.path.join(self.temp_dir, "checkpoint_factory_async")
stage_future, write_future = checkpointer.save(
checkpoint_path, self.state_dict
)
# Verify futures are returned
self.assertIsNotNone(stage_future)
self.assertIsNotNone(write_future)
# Wait for completion
stage_future.result()
write_future.result()
# Verify checkpoint was created
checkpoint_file = os.path.join(
checkpoint_path, f"checkpoint_{self.rank_info.global_rank}.pt"
)
self.assertTrue(os.path.exists(checkpoint_file))
# Test loading
loaded_state_dict = checkpointer.load(checkpoint_path)
self.assertEqual(loaded_state_dict["epoch"], 5)
finally:
# Clean up
checkpointer.close()
if __name__ == "__main__":
run_tests()
| TestMakeCheckpointer |
python | ray-project__ray | rllib/env/policy_client.py | {
"start": 6615,
"end": 10722
} | class ____(threading.Thread):
def __init__(self, rollout_worker, send_fn):
super().__init__()
self.daemon = True
self.rollout_worker = rollout_worker
self.send_fn = send_fn
def run(self):
try:
while True:
logger.info("Generating new batch of experiences.")
samples = self.rollout_worker.sample()
metrics = self.rollout_worker.get_metrics()
if isinstance(samples, MultiAgentBatch):
logger.info(
"Sending batch of {} env steps ({} agent steps) to "
"server.".format(samples.env_steps(), samples.agent_steps())
)
else:
logger.info(
"Sending batch of {} steps back to server.".format(
samples.count
)
)
self.send_fn(
{
"command": Commands.REPORT_SAMPLES,
"samples": samples,
"metrics": metrics,
}
)
except Exception as e:
logger.error("Error: inference worker thread died!", e)
@OldAPIStack
def _auto_wrap_external(real_env_creator):
def wrapped_creator(env_config):
real_env = real_env_creator(env_config)
if not isinstance(real_env, (ExternalEnv, ExternalMultiAgentEnv)):
logger.info(
"The env you specified is not a supported (sub-)type of "
"ExternalEnv. Attempting to convert it automatically to "
"ExternalEnv."
)
if isinstance(real_env, MultiAgentEnv):
external_cls = ExternalMultiAgentEnv
else:
external_cls = ExternalEnv
class _ExternalEnvWrapper(external_cls):
def __init__(self, real_env):
super().__init__(
observation_space=real_env.observation_space,
action_space=real_env.action_space,
)
def run(self):
# Since we are calling methods on this class in the
# client, run doesn't need to do anything.
time.sleep(999999)
return _ExternalEnvWrapper(real_env)
return real_env
return wrapped_creator
@OldAPIStack
def _create_embedded_rollout_worker(kwargs, send_fn):
# Since the server acts as an input datasource, we have to reset the
# input config to the default, which runs env rollouts.
kwargs = kwargs.copy()
kwargs["config"] = kwargs["config"].copy(copy_frozen=False)
config = kwargs["config"]
config.output = None
config.input_ = "sampler"
config.input_config = {}
# If server has no env (which is the expected case):
# Generate a dummy ExternalEnv here using RandomEnv and the
# given observation/action spaces.
if config.env is None:
from ray.rllib.examples.envs.classes.random_env import (
RandomEnv,
RandomMultiAgentEnv,
)
env_config = {
"action_space": config.action_space,
"observation_space": config.observation_space,
}
is_ma = config.is_multi_agent
kwargs["env_creator"] = _auto_wrap_external(
lambda _: (RandomMultiAgentEnv if is_ma else RandomEnv)(env_config)
)
# kwargs["config"].env = True
# Otherwise, use the env specified by the server args.
else:
real_env_creator = kwargs["env_creator"]
kwargs["env_creator"] = _auto_wrap_external(real_env_creator)
logger.info("Creating rollout worker with kwargs={}".format(kwargs))
from ray.rllib.evaluation.rollout_worker import RolloutWorker
rollout_worker = RolloutWorker(**kwargs)
inference_thread = _LocalInferenceThread(rollout_worker, send_fn)
inference_thread.start()
return rollout_worker, inference_thread
| _LocalInferenceThread |
python | pytorch__pytorch | torch/_inductor/pattern_matcher.py | {
"start": 3912,
"end": 5306
} | class ____:
def __init__(self) -> None:
# Ensure we're really a singleton.
assert "MULTIPLE" not in globals() or self is MULTIPLE
# Sentinel indicating multiple quantities can be matched
MULTIPLE = Multiple()
def _transfer_meta(
new_meta: dict[str, Any], old_node: torch.fx.Node, pass_name: str = ""
) -> None:
from torch.fx.traceback import NodeSource, NodeSourceAction
# transfer metadata after pattern matching occurs.
# skip "val" and "tensor_meta" because this info is too specific; it's unlikely
# to remain accurate after pattern matching has occurred.
if config.trace.provenance_tracking_level == 1:
# We handle "from_node" field of the node meta specially to record that the new node comes from the old_node.
new_from_node = new_meta.get("from_node", []).copy()
new_from_node.append(NodeSource(old_node, pass_name, NodeSourceAction.REPLACE))
new_meta.update(
(k, v)
for k, v in old_node.meta.items()
if k in torch.fx.proxy._COPY_META_FIELDS
)
new_meta["from_node"] = new_from_node
else:
new_meta.update(
(k, v)
for k, v in old_node.meta.items()
if k in torch.fx.proxy._COPY_META_FIELDS
)
if "stack_trace" in old_node.meta:
new_meta["stack_trace"] = old_node.meta["stack_trace"]
| Multiple |
python | doocs__leetcode | solution/1000-1099/1080.Insufficient Nodes in Root to Leaf Paths/Solution.py | {
"start": 192,
"end": 685
} | class ____:
def sufficientSubset(
self, root: Optional[TreeNode], limit: int
) -> Optional[TreeNode]:
if root is None:
return None
limit -= root.val
if root.left is None and root.right is None:
return None if limit > 0 else root
root.left = self.sufficientSubset(root.left, limit)
root.right = self.sufficientSubset(root.right, limit)
return None if root.left is None and root.right is None else root
| Solution |
python | readthedocs__readthedocs.org | readthedocs/api/v3/serializers.py | {
"start": 5626,
"end": 6975
} | class ____(FlexFieldsModelSerializer):
project = serializers.SlugRelatedField(slug_field="slug", read_only=True)
version = serializers.SlugRelatedField(slug_field="slug", read_only=True)
created = serializers.DateTimeField(source="date")
finished = serializers.SerializerMethodField()
success = serializers.SerializerMethodField()
duration = serializers.IntegerField(source="length")
state = BuildStateSerializer(source="*")
_links = BuildLinksSerializer(source="*")
urls = BuildURLsSerializer(source="*")
class Meta:
model = Build
fields = [
"id",
"version",
"project",
"created",
"finished",
"duration",
"state",
"success",
"error",
"commit",
"_links",
"urls",
]
expandable_fields = {"config": (BuildConfigSerializer,)}
def get_finished(self, obj):
if obj.date and obj.length:
return obj.date + datetime.timedelta(seconds=obj.length)
def get_success(self, obj):
"""
Return ``None`` if the build is not finished.
This is needed because ``default=True`` in the model field.
"""
if obj.finished:
return obj.success
return None
| BuildSerializer |
python | pyqtgraph__pyqtgraph | pyqtgraph/flowchart/library/Filters.py | {
"start": 1474,
"end": 2568
} | class ____(CtrlNode):
"""Butterworth filter"""
nodeName = 'ButterworthFilter'
uiTemplate = [
('band', 'combo', {'values': ['lowpass', 'highpass'], 'index': 0}),
('wPass', 'spin', {'value': 1000., 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'Hz', 'siPrefix': True}),
('wStop', 'spin', {'value': 2000., 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'Hz', 'siPrefix': True}),
('gPass', 'spin', {'value': 2.0, 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'dB', 'siPrefix': True}),
('gStop', 'spin', {'value': 20.0, 'step': 1, 'dec': True, 'bounds': [0.0, None], 'suffix': 'dB', 'siPrefix': True}),
('bidir', 'check', {'checked': True})
]
def processData(self, data):
s = self.stateGroup.state()
if s['band'] == 'lowpass':
mode = 'low'
else:
mode = 'high'
ret = functions.butterworthFilter(data, bidir=s['bidir'], btype=mode, wPass=s['wPass'], wStop=s['wStop'], gPass=s['gPass'], gStop=s['gStop'])
return ret
| Butterworth |
python | huggingface__transformers | src/transformers/models/internvl/modeling_internvl.py | {
"start": 20484,
"end": 21501
} | class ____(BaseModelOutputWithPast):
r"""
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
`past_key_values` input) to speed up sequential decoding.
image_hidden_states (`torch.FloatTensor`, *optional*):
A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
"""
image_hidden_states: Optional[torch.FloatTensor] = None
@auto_docstring(
custom_intro="""
The InternVL model which consists of a vision backbone and a language model, without a language modeling head.
"""
)
| InternVLModelOutputWithPast |
python | getsentry__sentry | tests/sentry/preprod/api/endpoints/test_organization_preprod_artifact_assemble.py | {
"start": 9565,
"end": 13644
} | class ____(TestCase):
"""Unit tests for VCS parameter validation function - no database required."""
def test_valid_minimal_no_vcs_params(self) -> None:
"""Test that validation passes when no VCS params are provided."""
data = {"checksum": "a" * 40, "chunks": []}
error = validate_vcs_parameters(data)
assert error is None
def test_valid_complete_vcs_params(self) -> None:
"""Test that validation passes when all required VCS params are provided."""
data = {
"checksum": "a" * 40,
"chunks": [],
"head_sha": "e" * 40,
"head_repo_name": "owner/repo",
"provider": "github",
"head_ref": "feature/xyz",
}
error = validate_vcs_parameters(data)
assert error is None
def test_valid_complete_vcs_params_with_base_sha(self) -> None:
"""Test that validation passes when all VCS params including base_sha are provided."""
data = {
"checksum": "a" * 40,
"chunks": [],
"head_sha": "e" * 40,
"base_sha": "f" * 40,
"head_repo_name": "owner/repo",
"provider": "github",
"head_ref": "feature/xyz",
}
error = validate_vcs_parameters(data)
assert error is None
def test_same_head_and_base_sha(self) -> None:
"""Test that validation fails when head_sha and base_sha are the same."""
same_sha = "e" * 40
data = {
"checksum": "a" * 40,
"chunks": [],
"head_sha": same_sha,
"base_sha": same_sha,
}
error = validate_vcs_parameters(data)
assert error is not None
assert "Head SHA and base SHA cannot be the same" in error
assert same_sha in error
def test_base_sha_without_head_sha(self) -> None:
"""Test that validation fails when base_sha is provided without head_sha."""
data = {"checksum": "a" * 40, "chunks": [], "base_sha": "f" * 40}
error = validate_vcs_parameters(data)
assert error is not None
assert "Head SHA is required when base SHA is provided" in error
def test_missing_head_repo_name(self) -> None:
"""Test that validation fails when head_repo_name is missing."""
data = {
"checksum": "a" * 40,
"chunks": [],
"head_sha": "e" * 40,
"provider": "github",
"head_ref": "feature/xyz",
}
error = validate_vcs_parameters(data)
assert error is not None
assert "Missing parameters" in error
assert "head_repo_name" in error
def test_missing_provider(self) -> None:
"""Test that validation fails when provider is missing."""
data = {
"checksum": "a" * 40,
"chunks": [],
"head_sha": "e" * 40,
"head_repo_name": "owner/repo",
"head_ref": "feature/xyz",
}
error = validate_vcs_parameters(data)
assert error is not None
assert "Missing parameters" in error
assert "provider" in error
def test_missing_head_ref(self) -> None:
"""Test that validation fails when head_ref is missing."""
data = {
"checksum": "a" * 40,
"chunks": [],
"head_sha": "e" * 40,
"head_repo_name": "owner/repo",
"provider": "github",
}
error = validate_vcs_parameters(data)
assert error is not None
assert "Missing parameters" in error
assert "head_ref" in error
def test_missing_multiple_params(self) -> None:
"""Test that validation fails and reports all missing params."""
data = {"checksum": "a" * 40, "chunks": [], "head_sha": "e" * 40}
error = validate_vcs_parameters(data)
assert error is not None
assert "Missing parameters" in error
assert "head_repo_name" in error
assert "provider" in error
assert "head_ref" in error
| ValidateVcsParametersTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/test_post_comments.py | {
"start": 6924,
"end": 13363
} | class ____(TestCase):
@property
def _config(self):
return (
ConfigBuilder()
.with_basic_auth_credentials("user@example.com", "password")
.with_subdomain("d3v-airbyte")
.with_start_date(_START_DATE)
.build()
)
def _get_authenticator(self, config):
return ApiTokenAuthenticator(email=config["credentials"]["email"], password=config["credentials"]["api_token"])
@HttpMocker()
def test_given_no_state_and_successful_sync_when_read_then_set_state_to_now(self, http_mocker):
"""
A normal incremental sync without pagination
"""
api_token_authenticator = self._get_authenticator(self._config)
# todo: Add this back once the CDK supports conditional streams on an endpoint
# _ = given_ticket_forms(http_mocker, string_to_datetime(self._config["start_date"]), api_token_authenticator)
posts_record_builder = given_posts(http_mocker, string_to_datetime(self._config["start_date"]), api_token_authenticator)
post = posts_record_builder.build()
post_comments_record_builder = PostsCommentsRecordBuilder.posts_comments_record()
http_mocker.get(
PostsCommentsRequestBuilder.posts_comments_endpoint(api_token_authenticator, post["id"])
.with_start_time(self._config["start_date"])
.with_page_size(100)
.build(),
PostsCommentsResponseBuilder.posts_comments_response().with_record(post_comments_record_builder).build(),
)
output = read_stream("post_comments", SyncMode.incremental, self._config)
assert len(output.records) == 1
post_comment = post_comments_record_builder.build()
assert output.most_recent_state.stream_descriptor.name == "post_comments" # 1687393942.0
post_comments_state_value = str(int(string_to_datetime(post_comment["updated_at"]).timestamp()))
assert (
output.most_recent_state.stream_state
== AirbyteStateBlob(
{
"lookback_window": 0,
"parent_state": {
"posts": {"updated_at": post["updated_at"]}
}, # note that this state does not have the concurrent format because SubstreamPartitionRouter is still relying on the declarative cursor
"state": {"updated_at": post_comments_state_value},
"states": [
{
"partition": {
"parent_slice": {},
"post_id": post["id"],
},
"cursor": {
"updated_at": post_comments_state_value,
},
}
],
"use_global_cursor": False,
}
)
)
@HttpMocker()
def test_given_state_and_pagination_when_read_then_return_records(self, http_mocker):
"""
A normal incremental sync with state and pagination
"""
api_token_authenticator = self._get_authenticator(self._config)
state_start_date = ab_datetime_parse(self._config["start_date"]).add(timedelta(weeks=52))
first_page_record_updated_at = state_start_date.add(timedelta(weeks=4))
last_page_record_updated_at = first_page_record_updated_at.add(timedelta(weeks=8))
state = {"updated_at": datetime_to_string(state_start_date)}
posts_record_builder = given_posts(http_mocker, state_start_date, api_token_authenticator)
post = posts_record_builder.build()
post_comments_first_record_builder = PostsCommentsRecordBuilder.posts_comments_record().with_field(
FieldPath("updated_at"), datetime_to_string(first_page_record_updated_at)
)
# Read first page request mock
http_mocker.get(
PostsCommentsRequestBuilder.posts_comments_endpoint(api_token_authenticator, post["id"])
.with_start_time(datetime_to_string(state_start_date))
.with_page_size(100)
.build(),
PostsCommentsResponseBuilder.posts_comments_response(
PostsCommentsRequestBuilder.posts_comments_endpoint(api_token_authenticator, post["id"]).with_page_size(100).build()
)
.with_pagination()
.with_record(post_comments_first_record_builder)
.build(),
)
post_comments_last_record_builder = PostsCommentsRecordBuilder.posts_comments_record().with_field(
FieldPath("updated_at"), datetime_to_string(last_page_record_updated_at)
)
# Read second page request mock
http_mocker.get(
PostsCommentsRequestBuilder.posts_comments_endpoint(api_token_authenticator, post["id"])
.with_page_after("after-cursor")
.with_page_size(100)
.build(),
PostsCommentsResponseBuilder.posts_comments_response().with_record(post_comments_last_record_builder).build(),
)
output = read_stream(
"post_comments", SyncMode.incremental, self._config, StateBuilder().with_stream_state("post_comments", state).build()
)
assert len(output.records) == 2
assert output.most_recent_state.stream_descriptor.name == "post_comments"
post_comments_state_value = str(int(last_page_record_updated_at.timestamp()))
assert output.most_recent_state.stream_state == AirbyteStateBlob(
{
"lookback_window": 0,
"parent_state": {"posts": {"updated_at": post["updated_at"]}},
# note that this state does not have the concurrent format because SubstreamPartitionRouter is still relying on the declarative cursor
"state": {"updated_at": post_comments_state_value},
"states": [
{
"partition": {
"parent_slice": {},
"post_id": post["id"],
},
"cursor": {
"updated_at": post_comments_state_value,
},
}
],
"use_global_cursor": False,
}
)
| TestPostsCommentsStreamIncremental |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1263326,
"end": 1263518
} | class ____(VegaLiteSchema):
"""StackOffset schema wrapper."""
_schema = {"$ref": "#/definitions/StackOffset"}
def __init__(self, *args):
super().__init__(*args)
| StackOffset |
python | ray-project__ray | doc/source/ray-core/doc_code/placement_group_example.py | {
"start": 1315,
"end": 1730
} | class ____:
def __init__(self):
pass
def ready(self):
pass
# Create an actor to a placement group.
actor = Actor.options(
scheduling_strategy=PlacementGroupSchedulingStrategy(
placement_group=pg,
)
).remote()
# Verify the actor is scheduled.
ray.get(actor.ready.remote(), timeout=10)
# __schedule_pg_end__
# __schedule_pg_3_start__
@ray.remote(num_cpus=0, num_gpus=1)
| Actor |
python | scipy__scipy | scipy/optimize/_lsq/least_squares.py | {
"start": 7178,
"end": 42812
} | class ____:
# Supplies a user function with args and kwargs.
def __init__(self, f, args=(), kwargs=None):
self.f = f
self.args = args
self.kwargs = kwargs or {}
def __call__(self, x):
return self.f(x, *self.args, **self.kwargs)
@_workers_wrapper
def least_squares(
fun, x0, jac='2-point', bounds=(-np.inf, np.inf), method='trf',
ftol=1e-8, xtol=1e-8, gtol=1e-8, x_scale=None, loss='linear',
f_scale=1.0, diff_step=None, tr_solver=None, tr_options=None,
jac_sparsity=None, max_nfev=None, verbose=0, args=(), kwargs=None,
callback=None, workers=None
):
"""Solve a nonlinear least-squares problem with bounds on the variables.
Given the residuals f(x) (an m-D real function of n real
variables) and the loss function rho(s) (a scalar function), `least_squares`
finds a local minimum of the cost function F(x)::
minimize F(x) = 0.5 * sum(rho(f_i(x)**2), i = 0, ..., m - 1)
subject to lb <= x <= ub
The purpose of the loss function rho(s) is to reduce the influence of
outliers on the solution.
Parameters
----------
fun : callable
Function which computes the vector of residuals, with the signature
``fun(x, *args, **kwargs)``, i.e., the minimization proceeds with
respect to its first argument. The argument ``x`` passed to this
function is an ndarray of shape (n,) (never a scalar, even for n=1).
It must allocate and return a 1-D array_like of shape (m,) or a scalar.
If the argument ``x`` is complex or the function ``fun`` returns
complex residuals, it must be wrapped in a real function of real
arguments, as shown at the end of the Examples section.
x0 : array_like with shape (n,) or float
Initial guess on independent variables. If float, it will be treated
as a 1-D array with one element. When `method` is 'trf', the initial
guess might be slightly adjusted to lie sufficiently within the given
`bounds`.
jac : {'2-point', '3-point', 'cs', callable}, optional
Method of computing the Jacobian matrix (an m-by-n matrix, where
element (i, j) is the partial derivative of f[i] with respect to
x[j]). The keywords select a finite difference scheme for numerical
estimation. The scheme '3-point' is more accurate, but requires
twice as many operations as '2-point' (default). The scheme 'cs'
uses complex steps, and while potentially the most accurate, it is
applicable only when `fun` correctly handles complex inputs and
can be analytically continued to the complex plane. If callable, it is used as
``jac(x, *args, **kwargs)`` and should return a good approximation
(or the exact value) for the Jacobian as an array_like (np.atleast_2d
is applied), a sparse array (csr_array preferred for performance) or
a `scipy.sparse.linalg.LinearOperator`.
.. versionchanged:: 1.16.0
An ability to use the '3-point', 'cs' keywords with the 'lm' method.
Previously 'lm' was limited to '2-point' and callable.
bounds : 2-tuple of array_like or `Bounds`, optional
There are two ways to specify bounds:
1. Instance of `Bounds` class
2. Lower and upper bounds on independent variables. Defaults to no
bounds. Each array must match the size of `x0` or be a scalar,
in the latter case a bound will be the same for all variables.
Use ``np.inf`` with an appropriate sign to disable bounds on all
or some variables.
method : {'trf', 'dogbox', 'lm'}, optional
Algorithm to perform minimization.
* 'trf' : Trust Region Reflective algorithm, particularly suitable
for large sparse problems with bounds. Generally robust method.
* 'dogbox' : dogleg algorithm with rectangular trust regions,
typical use case is small problems with bounds. Not recommended
for problems with rank-deficient Jacobian.
* 'lm' : Levenberg-Marquardt algorithm as implemented in MINPACK.
Doesn't handle bounds and sparse Jacobians. Usually the most
efficient method for small unconstrained problems.
Default is 'trf'. See Notes for more information.
ftol : float or None, optional
Tolerance for termination by the change of the cost function. Default
is 1e-8. The optimization process is stopped when ``dF < ftol * F``,
and there was an adequate agreement between a local quadratic model and
the true model in the last step.
If None and 'method' is not 'lm', the termination by this condition is
disabled. If 'method' is 'lm', this tolerance must be higher than
machine epsilon.
xtol : float or None, optional
Tolerance for termination by the change of the independent variables.
Default is 1e-8. The exact condition depends on the `method` used:
* For 'trf' and 'dogbox' : ``norm(dx) < xtol * (xtol + norm(x))``.
* For 'lm' : ``Delta < xtol * norm(xs)``, where ``Delta`` is
a trust-region radius and ``xs`` is the value of ``x``
scaled according to `x_scale` parameter (see below).
If None and 'method' is not 'lm', the termination by this condition is
disabled. If 'method' is 'lm', this tolerance must be higher than
machine epsilon.
gtol : float or None, optional
Tolerance for termination by the norm of the gradient. Default is 1e-8.
The exact condition depends on a `method` used:
* For 'trf' : ``norm(g_scaled, ord=np.inf) < gtol``, where
``g_scaled`` is the value of the gradient scaled to account for
the presence of the bounds [STIR]_.
* For 'dogbox' : ``norm(g_free, ord=np.inf) < gtol``, where
``g_free`` is the gradient with respect to the variables which
are not in the optimal state on the boundary.
* For 'lm' : the maximum absolute value of the cosine of angles
between columns of the Jacobian and the residual vector is less
than `gtol`, or the residual vector is zero.
If None and 'method' is not 'lm', the termination by this condition is
disabled. If 'method' is 'lm', this tolerance must be higher than
machine epsilon.
x_scale : {None, array_like, 'jac'}, optional
Characteristic scale of each variable. Setting `x_scale` is equivalent
to reformulating the problem in scaled variables ``xs = x / x_scale``.
An alternative view is that the size of a trust region along jth
dimension is proportional to ``x_scale[j]``. Improved convergence may
be achieved by setting `x_scale` such that a step of a given size
along any of the scaled variables has a similar effect on the cost
function. If set to 'jac', the scale is iteratively updated using the
inverse norms of the columns of the Jacobian matrix (as described in
[JJMore]_). The default scaling for each method (i.e.
if ``x_scale is None``) is as follows:
* For 'trf' : ``x_scale == 1``
* For 'dogbox' : ``x_scale == 1``
* For 'lm' : ``x_scale == 'jac'``
.. versionchanged:: 1.16.0
The default keyword value is changed from 1 to None to indicate that
a default approach to scaling is used.
For the 'lm' method the default scaling is changed from 1 to 'jac'.
This has been found to give better performance, and is the same
scaling as performed by ``leastsq``.
loss : str or callable, optional
Determines the loss function. The following keyword values are allowed:
* 'linear' (default) : ``rho(z) = z``. Gives a standard
least-squares problem.
* 'soft_l1' : ``rho(z) = 2 * ((1 + z)**0.5 - 1)``. The smooth
approximation of l1 (absolute value) loss. Usually a good
choice for robust least squares.
* 'huber' : ``rho(z) = z if z <= 1 else 2*z**0.5 - 1``. Works
similarly to 'soft_l1'.
* 'cauchy' : ``rho(z) = ln(1 + z)``. Severely weakens outliers
influence, but may cause difficulties in optimization process.
* 'arctan' : ``rho(z) = arctan(z)``. Limits a maximum loss on
a single residual, has properties similar to 'cauchy'.
If callable, it must take a 1-D ndarray ``z=f**2`` and return an
array_like with shape (3, m) where row 0 contains function values,
row 1 contains first derivatives and row 2 contains second
derivatives. Method 'lm' supports only 'linear' loss.
f_scale : float, optional
Value of soft margin between inlier and outlier residuals, default
is 1.0. The loss function is evaluated as follows
``rho_(f**2) = C**2 * rho(f**2 / C**2)``, where ``C`` is `f_scale`,
and ``rho`` is determined by `loss` parameter. This parameter has
no effect with ``loss='linear'``, but for other `loss` values it is
of crucial importance.
max_nfev : None or int, optional
For all methods this parameter controls the maximum number of function
evaluations used by each method, separate to those used in numerical
approximation of the jacobian.
If None (default), the value is chosen automatically as 100 * n.
.. versionchanged:: 1.16.0
The default for the 'lm' method is changed to 100 * n, for both a callable
and a numerically estimated jacobian. Previously the default when using an
estimated jacobian was 100 * n * (n + 1), because the method included
evaluations used in the estimation.
diff_step : None or array_like, optional
Determines the relative step size for the finite difference
approximation of the Jacobian. The actual step is computed as
``x * diff_step``. If None (default), then `diff_step` is taken to be
a conventional "optimal" power of machine epsilon for the finite
difference scheme used [NR]_.
tr_solver : {None, 'exact', 'lsmr'}, optional
Method for solving trust-region subproblems, relevant only for 'trf'
and 'dogbox' methods.
* 'exact' is suitable for not very large problems with dense
Jacobian matrices. The computational complexity per iteration is
comparable to a singular value decomposition of the Jacobian
matrix.
* 'lsmr' is suitable for problems with sparse and large Jacobian
matrices. It uses the iterative procedure
`scipy.sparse.linalg.lsmr` for finding a solution of a linear
least-squares problem and only requires matrix-vector product
evaluations.
If None (default), the solver is chosen based on the type of Jacobian
returned on the first iteration.
tr_options : dict, optional
Keyword options passed to trust-region solver.
* ``tr_solver='exact'``: `tr_options` are ignored.
* ``tr_solver='lsmr'``: options for `scipy.sparse.linalg.lsmr`.
Additionally, ``method='trf'`` supports 'regularize' option
(bool, default is True), which adds a regularization term to the
normal equation, which improves convergence if the Jacobian is
rank-deficient [Byrd]_ (eq. 3.4).
jac_sparsity : {None, array_like, sparse array}, optional
Defines the sparsity structure of the Jacobian matrix for finite
difference estimation, its shape must be (m, n). If the Jacobian has
only few non-zero elements in *each* row, providing the sparsity
structure will greatly speed up the computations [Curtis]_. A zero
entry means that a corresponding element in the Jacobian is identically
zero. If provided, forces the use of 'lsmr' trust-region solver.
If None (default), then dense differencing will be used. Has no effect
for 'lm' method.
verbose : {0, 1, 2}, optional
Level of algorithm's verbosity:
* 0 (default) : work silently.
* 1 : display a termination report.
* 2 : display progress during iterations (not supported by 'lm'
method).
args, kwargs : tuple and dict, optional
Additional arguments passed to `fun` and `jac`. Both empty by default.
The calling signature is ``fun(x, *args, **kwargs)`` and the same for
`jac`.
callback : None or callable, optional
Callback function that is called by the algorithm on each iteration.
This can be used to print or plot the optimization results at each
step, and to stop the optimization algorithm based on some user-defined
condition. Only implemented for the `trf` and `dogbox` methods.
The signature is ``callback(intermediate_result: OptimizeResult)``
`intermediate_result is a `scipy.optimize.OptimizeResult`
which contains the intermediate results of the optimization at the
current iteration.
The callback also supports a signature like: ``callback(x)``
Introspection is used to determine which of the signatures is invoked.
If the `callback` function raises `StopIteration` the optimization algorithm
will stop and return with status code -2.
.. versionadded:: 1.16.0
workers : map-like callable, optional
A map-like callable, such as `multiprocessing.Pool.map` for evaluating
any numerical differentiation in parallel.
This evaluation is carried out as ``workers(fun, iterable)``.
.. versionadded:: 1.16.0
Returns
-------
result : OptimizeResult
`OptimizeResult` with the following fields defined:
x : ndarray, shape (n,)
Solution found.
cost : float
Value of the cost function at the solution.
fun : ndarray, shape (m,)
Vector of residuals at the solution.
jac : ndarray, sparse array or LinearOperator, shape (m, n)
Modified Jacobian matrix at the solution, in the sense that J^T J
is a Gauss-Newton approximation of the Hessian of the cost function.
The type is the same as the one used by the algorithm.
grad : ndarray, shape (m,)
Gradient of the cost function at the solution.
optimality : float
First-order optimality measure. In unconstrained problems, it is
always the uniform norm of the gradient. In constrained problems,
it is the quantity which was compared with `gtol` during iterations.
active_mask : ndarray of int, shape (n,)
Each component shows whether a corresponding constraint is active
(that is, whether a variable is at the bound):
* 0 : a constraint is not active.
* -1 : a lower bound is active.
* 1 : an upper bound is active.
Might be somewhat arbitrary for 'trf' method as it generates a
sequence of strictly feasible iterates and `active_mask` is
determined within a tolerance threshold.
nfev : int
Number of function evaluations done. This number does not include
the function calls used for numerical Jacobian approximation.
.. versionchanged:: 1.16.0
For the 'lm' method the number of function calls used in numerical
Jacobian approximation is no longer included. This is to bring all
methods into line.
njev : int or None
Number of Jacobian evaluations done. If numerical Jacobian
approximation is used in 'lm' method, it is set to None.
status : int
The reason for algorithm termination:
* -2 : terminated because callback raised StopIteration.
* -1 : improper input parameters status returned from MINPACK.
* 0 : the maximum number of function evaluations is exceeded.
* 1 : `gtol` termination condition is satisfied.
* 2 : `ftol` termination condition is satisfied.
* 3 : `xtol` termination condition is satisfied.
* 4 : Both `ftol` and `xtol` termination conditions are satisfied.
message : str
Verbal description of the termination reason.
success : bool
True if one of the convergence criteria is satisfied (`status` > 0).
See Also
--------
leastsq : A legacy wrapper for the MINPACK implementation of the
Levenberg-Marquadt algorithm.
curve_fit : Least-squares minimization applied to a curve-fitting problem.
Notes
-----
Method 'lm' (Levenberg-Marquardt) calls a wrapper over a least-squares
algorithm implemented in MINPACK (lmder). It runs the
Levenberg-Marquardt algorithm formulated as a trust-region type algorithm.
The implementation is based on paper [JJMore]_, it is very robust and
efficient with a lot of smart tricks. It should be your first choice
for unconstrained problems. Note that it doesn't support bounds. Also,
it doesn't work when m < n.
Method 'trf' (Trust Region Reflective) is motivated by the process of
solving a system of equations, which constitute the first-order optimality
condition for a bound-constrained minimization problem as formulated in
[STIR]_. The algorithm iteratively solves trust-region subproblems
augmented by a special diagonal quadratic term and with trust-region shape
determined by the distance from the bounds and the direction of the
gradient. This enhancements help to avoid making steps directly into bounds
and efficiently explore the whole space of variables. To further improve
convergence, the algorithm considers search directions reflected from the
bounds. To obey theoretical requirements, the algorithm keeps iterates
strictly feasible. With dense Jacobians trust-region subproblems are
solved by an exact method very similar to the one described in [JJMore]_
(and implemented in MINPACK). The difference from the MINPACK
implementation is that a singular value decomposition of a Jacobian
matrix is done once per iteration, instead of a QR decomposition and series
of Givens rotation eliminations. For large sparse Jacobians a 2-D subspace
approach of solving trust-region subproblems is used [STIR]_, [Byrd]_.
The subspace is spanned by a scaled gradient and an approximate
Gauss-Newton solution delivered by `scipy.sparse.linalg.lsmr`. When no
constraints are imposed the algorithm is very similar to MINPACK and has
generally comparable performance. The algorithm works quite robust in
unbounded and bounded problems, thus it is chosen as a default algorithm.
Method 'dogbox' operates in a trust-region framework, but considers
rectangular trust regions as opposed to conventional ellipsoids [Voglis]_.
The intersection of a current trust region and initial bounds is again
rectangular, so on each iteration a quadratic minimization problem subject
to bound constraints is solved approximately by Powell's dogleg method
[NumOpt]_. The required Gauss-Newton step can be computed exactly for
dense Jacobians or approximately by `scipy.sparse.linalg.lsmr` for large
sparse Jacobians. The algorithm is likely to exhibit slow convergence when
the rank of Jacobian is less than the number of variables. The algorithm
often outperforms 'trf' in bounded problems with a small number of
variables.
Robust loss functions are implemented as described in [BA]_. The idea
is to modify a residual vector and a Jacobian matrix on each iteration
such that computed gradient and Gauss-Newton Hessian approximation match
the true gradient and Hessian approximation of the cost function. Then
the algorithm proceeds in a normal way, i.e., robust loss functions are
implemented as a simple wrapper over standard least-squares algorithms.
.. versionadded:: 0.17.0
References
----------
.. [STIR] M. A. Branch, T. F. Coleman, and Y. Li, "A Subspace, Interior,
and Conjugate Gradient Method for Large-Scale Bound-Constrained
Minimization Problems," SIAM Journal on Scientific Computing,
Vol. 21, Number 1, pp 1-23, 1999.
.. [NR] William H. Press et. al., "Numerical Recipes. The Art of Scientific
Computing. 3rd edition", Sec. 5.7.
.. [Byrd] R. H. Byrd, R. B. Schnabel and G. A. Shultz, "Approximate
solution of the trust region problem by minimization over
two-dimensional subspaces", Math. Programming, 40, pp. 247-263,
1988.
.. [Curtis] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
sparse Jacobian matrices", Journal of the Institute of
Mathematics and its Applications, 13, pp. 117-120, 1974.
.. [JJMore] J. J. More, "The Levenberg-Marquardt Algorithm: Implementation
and Theory," Numerical Analysis, ed. G. A. Watson, Lecture
Notes in Mathematics 630, Springer Verlag, pp. 105-116, 1977.
.. [Voglis] C. Voglis and I. E. Lagaris, "A Rectangular Trust Region
Dogleg Approach for Unconstrained and Bound Constrained
Nonlinear Optimization", WSEAS International Conference on
Applied Mathematics, Corfu, Greece, 2004.
.. [NumOpt] J. Nocedal and S. J. Wright, "Numerical optimization,
2nd edition", Chapter 4.
.. [BA] B. Triggs et. al., "Bundle Adjustment - A Modern Synthesis",
Proceedings of the International Workshop on Vision Algorithms:
Theory and Practice, pp. 298-372, 1999.
Examples
--------
In this example we find a minimum of the Rosenbrock function without bounds
on independent variables.
>>> import numpy as np
>>> def fun_rosenbrock(x):
... return np.array([10 * (x[1] - x[0]**2), (1 - x[0])])
Notice that we only provide the vector of the residuals. The algorithm
constructs the cost function as a sum of squares of the residuals, which
gives the Rosenbrock function. The exact minimum is at ``x = [1.0, 1.0]``.
>>> from scipy.optimize import least_squares
>>> x0_rosenbrock = np.array([2, 2])
>>> res_1 = least_squares(fun_rosenbrock, x0_rosenbrock)
>>> res_1.x
array([ 1., 1.])
>>> res_1.cost
9.8669242910846867e-30
>>> res_1.optimality
8.8928864934219529e-14
We now constrain the variables, in such a way that the previous solution
becomes infeasible. Specifically, we require that ``x[1] >= 1.5``, and
``x[0]`` left unconstrained. To this end, we specify the `bounds` parameter
to `least_squares` in the form ``bounds=([-np.inf, 1.5], np.inf)``.
We also provide the analytic Jacobian:
>>> def jac_rosenbrock(x):
... return np.array([
... [-20 * x[0], 10],
... [-1, 0]])
Putting this all together, we see that the new solution lies on the bound:
>>> res_2 = least_squares(fun_rosenbrock, x0_rosenbrock, jac_rosenbrock,
... bounds=([-np.inf, 1.5], np.inf))
>>> res_2.x
array([ 1.22437075, 1.5 ])
>>> res_2.cost
0.025213093946805685
>>> res_2.optimality
1.5885401433157753e-07
Now we solve a system of equations (i.e., the cost function should be zero
at a minimum) for a Broyden tridiagonal vector-valued function of 100000
variables:
>>> def fun_broyden(x):
... f = (3 - x) * x + 1
... f[1:] -= x[:-1]
... f[:-1] -= 2 * x[1:]
... return f
The corresponding Jacobian matrix is sparse. We tell the algorithm to
estimate it by finite differences and provide the sparsity structure of
Jacobian to significantly speed up this process.
>>> from scipy.sparse import lil_array
>>> def sparsity_broyden(n):
... sparsity = lil_array((n, n), dtype=int)
... i = np.arange(n)
... sparsity[i, i] = 1
... i = np.arange(1, n)
... sparsity[i, i - 1] = 1
... i = np.arange(n - 1)
... sparsity[i, i + 1] = 1
... return sparsity
...
>>> n = 100000
>>> x0_broyden = -np.ones(n)
...
>>> res_3 = least_squares(fun_broyden, x0_broyden,
... jac_sparsity=sparsity_broyden(n))
>>> res_3.cost
4.5687069299604613e-23
>>> res_3.optimality
1.1650454296851518e-11
Let's also solve a curve fitting problem using robust loss function to
take care of outliers in the data. Define the model function as
``y = a + b * exp(c * t)``, where t is a predictor variable, y is an
observation and a, b, c are parameters to estimate.
First, define the function which generates the data with noise and
outliers, define the model parameters, and generate data:
>>> from numpy.random import default_rng
>>> rng = default_rng()
>>> def gen_data(t, a, b, c, noise=0., n_outliers=0, seed=None):
... rng = default_rng(seed)
...
... y = a + b * np.exp(t * c)
...
... error = noise * rng.standard_normal(t.size)
... outliers = rng.integers(0, t.size, n_outliers)
... error[outliers] *= 10
...
... return y + error
...
>>> a = 0.5
>>> b = 2.0
>>> c = -1
>>> t_min = 0
>>> t_max = 10
>>> n_points = 15
...
>>> t_train = np.linspace(t_min, t_max, n_points)
>>> y_train = gen_data(t_train, a, b, c, noise=0.1, n_outliers=3)
Define function for computing residuals and initial estimate of
parameters.
>>> def fun(x, t, y):
... return x[0] + x[1] * np.exp(x[2] * t) - y
...
>>> x0 = np.array([1.0, 1.0, 0.0])
Compute a standard least-squares solution:
>>> res_lsq = least_squares(fun, x0, args=(t_train, y_train))
Now compute two solutions with two different robust loss functions. The
parameter `f_scale` is set to 0.1, meaning that inlier residuals should
not significantly exceed 0.1 (the noise level used).
>>> res_soft_l1 = least_squares(fun, x0, loss='soft_l1', f_scale=0.1,
... args=(t_train, y_train))
>>> res_log = least_squares(fun, x0, loss='cauchy', f_scale=0.1,
... args=(t_train, y_train))
And, finally, plot all the curves. We see that by selecting an appropriate
`loss` we can get estimates close to optimal even in the presence of
strong outliers. But keep in mind that generally it is recommended to try
'soft_l1' or 'huber' losses first (if at all necessary) as the other two
options may cause difficulties in optimization process.
>>> t_test = np.linspace(t_min, t_max, n_points * 10)
>>> y_true = gen_data(t_test, a, b, c)
>>> y_lsq = gen_data(t_test, *res_lsq.x)
>>> y_soft_l1 = gen_data(t_test, *res_soft_l1.x)
>>> y_log = gen_data(t_test, *res_log.x)
...
>>> import matplotlib.pyplot as plt
>>> plt.plot(t_train, y_train, 'o')
>>> plt.plot(t_test, y_true, 'k', linewidth=2, label='true')
>>> plt.plot(t_test, y_lsq, label='linear loss')
>>> plt.plot(t_test, y_soft_l1, label='soft_l1 loss')
>>> plt.plot(t_test, y_log, label='cauchy loss')
>>> plt.xlabel("t")
>>> plt.ylabel("y")
>>> plt.legend()
>>> plt.show()
In the next example, we show how complex-valued residual functions of
complex variables can be optimized with ``least_squares()``. Consider the
following function:
>>> def f(z):
... return z - (0.5 + 0.5j)
We wrap it into a function of real variables that returns real residuals
by simply handling the real and imaginary parts as independent variables:
>>> def f_wrap(x):
... fx = f(x[0] + 1j*x[1])
... return np.array([fx.real, fx.imag])
Thus, instead of the original m-D complex function of n complex
variables we optimize a 2m-D real function of 2n real variables:
>>> from scipy.optimize import least_squares
>>> res_wrapped = least_squares(f_wrap, (0.1, 0.1), bounds=([0, 0], [1, 1]))
>>> z = res_wrapped.x[0] + res_wrapped.x[1]*1j
>>> z
(0.49999999999925893+0.49999999999925893j)
"""
if method not in ['trf', 'dogbox', 'lm']:
raise ValueError("`method` must be 'trf', 'dogbox' or 'lm'.")
if jac not in ['2-point', '3-point', 'cs'] and not callable(jac):
raise ValueError("`jac` must be '2-point', '3-point', 'cs' or "
"callable.")
if tr_solver not in [None, 'exact', 'lsmr']:
raise ValueError("`tr_solver` must be None, 'exact' or 'lsmr'.")
if loss not in IMPLEMENTED_LOSSES and not callable(loss):
raise ValueError(f"`loss` must be one of {IMPLEMENTED_LOSSES.keys()}"
" or a callable.")
if method == 'lm' and loss != 'linear':
raise ValueError("method='lm' supports only 'linear' loss function.")
if verbose not in [0, 1, 2]:
raise ValueError("`verbose` must be in [0, 1, 2].")
if max_nfev is not None and max_nfev <= 0:
raise ValueError("`max_nfev` must be None or positive integer.")
if np.iscomplexobj(x0):
raise ValueError("`x0` must be real.")
x0 = np.atleast_1d(x0).astype(float)
if x0.ndim > 1:
raise ValueError("`x0` must have at most 1 dimension.")
if isinstance(bounds, Bounds):
lb, ub = bounds.lb, bounds.ub
bounds = (lb, ub)
else:
if len(bounds) == 2:
lb, ub = prepare_bounds(bounds, x0.shape[0])
else:
raise ValueError("`bounds` must contain 2 elements.")
if method == 'lm' and not np.all((lb == -np.inf) & (ub == np.inf)):
raise ValueError("Method 'lm' doesn't support bounds.")
if lb.shape != x0.shape or ub.shape != x0.shape:
raise ValueError("Inconsistent shapes between bounds and `x0`.")
if np.any(lb >= ub):
raise ValueError("Each lower bound must be strictly less than each "
"upper bound.")
if not in_bounds(x0, lb, ub):
raise ValueError("Initial guess is outside of provided bounds")
x_scale = check_x_scale(x_scale, x0, method)
ftol, xtol, gtol = check_tolerance(ftol, xtol, gtol, method)
if method == 'trf':
x0 = make_strictly_feasible(x0, lb, ub)
if tr_options is None:
tr_options = {}
###########################################################################
# assemble VectorFunction
###########################################################################
# first wrap the args/kwargs
fun_wrapped = _WrapArgsKwargs(fun, args=args, kwargs=kwargs)
jac_wrapped = jac
if callable(jac):
jac_wrapped = _WrapArgsKwargs(jac, args=args, kwargs=kwargs)
def _dummy_hess(x, *args):
# we don't care about Hessian evaluations
return x
vector_fun = VectorFunction(
fun_wrapped,
x0,
jac_wrapped,
_dummy_hess,
finite_diff_rel_step=diff_step,
finite_diff_jac_sparsity=jac_sparsity,
finite_diff_bounds=bounds,
workers=workers
)
###########################################################################
f0 = vector_fun.fun(x0)
J0 = vector_fun.jac(x0)
if f0.ndim != 1:
raise ValueError("`fun` must return at most 1-d array_like. "
f"f0.shape: {f0.shape}")
if not np.all(np.isfinite(f0)):
raise ValueError("Residuals are not finite in the initial point.")
n = x0.size
m = f0.size
if method == 'lm' and m < n:
raise ValueError("Method 'lm' doesn't work when the number of "
"residuals is less than the number of variables.")
loss_function = construct_loss_function(m, loss, f_scale)
if callable(loss):
rho = loss_function(f0)
if rho.shape != (3, m):
raise ValueError("The return value of `loss` callable has wrong "
"shape.")
initial_cost = 0.5 * np.sum(rho[0])
elif loss_function is not None:
initial_cost = loss_function(f0, cost_only=True)
else:
initial_cost = 0.5 * np.dot(f0, f0)
if not callable(jac):
# Estimate Jacobian by finite differences.
if method == 'lm':
if jac_sparsity is not None:
raise ValueError("method='lm' does not support "
"`jac_sparsity`.")
else:
# this will raise a ValueError if the jac_sparsity isn't correct
_ = check_jac_sparsity(jac_sparsity, m, n)
if jac_sparsity is not None and tr_solver == 'exact':
raise ValueError("tr_solver='exact' is incompatible "
"with `jac_sparsity`.")
if J0.shape != (m, n):
raise ValueError(
f"The return value of `jac` has wrong shape: expected {(m, n)}, "
f"actual {J0.shape}."
)
if not isinstance(J0, np.ndarray):
if method == 'lm':
raise ValueError("method='lm' works only with dense "
"Jacobian matrices.")
if tr_solver == 'exact':
raise ValueError(
"tr_solver='exact' works only with dense "
"Jacobian matrices.")
jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
if isinstance(J0, LinearOperator) and jac_scale:
raise ValueError("x_scale='jac' can't be used when `jac` "
"returns LinearOperator.")
if tr_solver is None:
if isinstance(J0, np.ndarray):
tr_solver = 'exact'
else:
tr_solver = 'lsmr'
# Wrap callback function. If callback is None, callback_wrapped also is None
callback_wrapped = _wrap_callback(callback)
if method == 'lm':
if callback is not None:
warn("Callback function specified, but not supported with `lm` method.",
stacklevel=2)
result = call_minpack(vector_fun.fun, x0, vector_fun.jac, ftol, xtol, gtol,
max_nfev, x_scale, jac_method=jac)
elif method == 'trf':
result = trf(vector_fun.fun, vector_fun.jac, x0, f0, J0, lb, ub, ftol, xtol,
gtol, max_nfev, x_scale, loss_function, tr_solver,
tr_options.copy(), verbose, callback=callback_wrapped)
elif method == 'dogbox':
if tr_solver == 'lsmr' and 'regularize' in tr_options:
warn("The keyword 'regularize' in `tr_options` is not relevant "
"for 'dogbox' method.",
stacklevel=2)
tr_options = tr_options.copy()
del tr_options['regularize']
result = dogbox(vector_fun.fun, vector_fun.jac, x0, f0, J0, lb, ub, ftol,
xtol, gtol, max_nfev, x_scale, loss_function,
tr_solver, tr_options, verbose, callback=callback_wrapped)
result.message = TERMINATION_MESSAGES[result.status]
result.success = result.status > 0
if verbose >= 1:
print(result.message)
print(f"Function evaluations {result.nfev}, initial cost {initial_cost:.4e}, "
f"final cost {result.cost:.4e}, "
f"first-order optimality {result.optimality:.2e}.")
return result
| _WrapArgsKwargs |
python | pypa__pip | src/pip/_internal/network/download.py | {
"start": 5250,
"end": 12682
} | class ____:
def __init__(
self,
session: PipSession,
progress_bar: BarType,
resume_retries: int,
) -> None:
assert (
resume_retries >= 0
), "Number of max resume retries must be bigger or equal to zero"
self._session = session
self._progress_bar = progress_bar
self._resume_retries = resume_retries
def batch(
self, links: Iterable[Link], location: str
) -> Iterable[tuple[Link, tuple[str, str]]]:
"""Convenience method to download multiple links."""
for link in links:
filepath, content_type = self(link, location)
yield link, (filepath, content_type)
def __call__(self, link: Link, location: str) -> tuple[str, str]:
"""Download a link and save it under location."""
resp = self._http_get(link)
download_size = _get_http_response_size(resp)
filepath = os.path.join(location, _get_http_response_filename(resp, link))
with open(filepath, "wb") as content_file:
download = _FileDownload(link, content_file, download_size)
self._process_response(download, resp)
if download.is_incomplete():
self._attempt_resumes_or_redownloads(download, resp)
content_type = resp.headers.get("Content-Type", "")
return filepath, content_type
def _process_response(self, download: _FileDownload, resp: Response) -> None:
"""Download and save chunks from a response."""
chunks = _log_download(
resp,
download.link,
self._progress_bar,
download.size,
range_start=download.bytes_received,
)
try:
for chunk in chunks:
download.write_chunk(chunk)
except ReadTimeoutError as e:
# If the download size is not known, then give up downloading the file.
if download.size is None:
raise e
logger.warning("Connection timed out while downloading.")
def _attempt_resumes_or_redownloads(
self, download: _FileDownload, first_resp: Response
) -> None:
"""Attempt to resume/restart the download if connection was dropped."""
while download.reattempts < self._resume_retries and download.is_incomplete():
assert download.size is not None
download.reattempts += 1
logger.warning(
"Attempting to resume incomplete download (%s/%s, attempt %d)",
format_size(download.bytes_received),
format_size(download.size),
download.reattempts,
)
try:
resume_resp = self._http_get_resume(download, should_match=first_resp)
# Fallback: if the server responded with 200 (i.e., the file has
# since been modified or range requests are unsupported) or any
# other unexpected status, restart the download from the beginning.
must_restart = resume_resp.status_code != HTTPStatus.PARTIAL_CONTENT
if must_restart:
download.reset_file()
download.size = _get_http_response_size(resume_resp)
first_resp = resume_resp
self._process_response(download, resume_resp)
except (ConnectionError, ReadTimeoutError, OSError):
continue
# No more resume attempts. Raise an error if the download is still incomplete.
if download.is_incomplete():
os.remove(download.output_file.name)
raise IncompleteDownloadError(download)
# If we successfully completed the download via resume, manually cache it
# as a complete response to enable future caching
if download.reattempts > 0:
self._cache_resumed_download(download, first_resp)
def _cache_resumed_download(
self, download: _FileDownload, original_response: Response
) -> None:
"""
Manually cache a file that was successfully downloaded via resume retries.
cachecontrol doesn't cache 206 (Partial Content) responses, since they
are not complete files. This method manually adds the final file to the
cache as though it was downloaded in a single request, so that future
requests can use the cache.
"""
url = download.link.url_without_fragment
adapter = self._session.get_adapter(url)
# Check if the adapter is the CacheControlAdapter (i.e. caching is enabled)
if not isinstance(adapter, CacheControlAdapter):
logger.debug(
"Skipping resume download caching: no cache controller for %s", url
)
return
# Check SafeFileCache is being used
assert isinstance(
adapter.cache, SafeFileCache
), "separate body cache not in use!"
synthetic_request = PreparedRequest()
synthetic_request.prepare(method="GET", url=url, headers={})
synthetic_response_headers = HTTPHeaderDict()
for key, value in original_response.headers.items():
if key.lower() not in ["content-range", "content-length"]:
synthetic_response_headers[key] = value
synthetic_response_headers["content-length"] = str(download.size)
synthetic_response = URLlib3Response(
body="",
headers=synthetic_response_headers,
status=200,
preload_content=False,
)
# Save metadata and then stream the file contents to cache.
cache_url = adapter.controller.cache_url(url)
metadata_blob = adapter.controller.serializer.dumps(
synthetic_request, synthetic_response, b""
)
adapter.cache.set(cache_url, metadata_blob)
download.output_file.flush()
with open(download.output_file.name, "rb") as f:
adapter.cache.set_body_from_io(cache_url, f)
logger.debug(
"Cached resumed download as complete response for future use: %s", url
)
def _http_get_resume(
self, download: _FileDownload, should_match: Response
) -> Response:
"""Issue a HTTP range request to resume the download."""
# To better understand the download resumption logic, see the mdn web docs:
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Range_requests
headers = HEADERS.copy()
headers["Range"] = f"bytes={download.bytes_received}-"
# If possible, use a conditional range request to avoid corrupted
# downloads caused by the remote file changing in-between.
if identifier := _get_http_response_etag_or_last_modified(should_match):
headers["If-Range"] = identifier
return self._http_get(download.link, headers)
def _http_get(self, link: Link, headers: Mapping[str, str] = HEADERS) -> Response:
target_url = link.url_without_fragment
try:
resp = self._session.get(target_url, headers=headers, stream=True)
raise_for_status(resp)
except NetworkConnectionError as e:
assert e.response is not None
logger.critical(
"HTTP error %s while getting %s", e.response.status_code, link
)
raise
return resp
| Downloader |
python | huggingface__transformers | src/transformers/models/maskformer/modeling_maskformer.py | {
"start": 19439,
"end": 25609
} | class ____(nn.Module):
"""
Multi-headed attention from 'Attention Is All You Need' paper.
Here, we add position embeddings to the queries and keys (as explained in the DETR paper).
"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
bias: bool = True,
):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
if self.head_dim * num_heads != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
f" {num_heads})."
)
self.scaling = self.head_dim**-0.5
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
def _shape(self, tensor: torch.Tensor, seq_len: int, batch_size: int):
return tensor.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
def with_pos_embed(self, tensor: torch.Tensor, object_queries: Optional[Tensor]):
return tensor if object_queries is None else tensor + object_queries
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
object_queries: Optional[torch.Tensor] = None,
key_value_states: Optional[torch.Tensor] = None,
spatial_position_embeddings: Optional[torch.Tensor] = None,
output_attentions: bool = False,
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
# if key_value_states are provided this layer is used as a cross-attention layer
# for the decoder
is_cross_attention = key_value_states is not None
batch_size, target_len, embed_dim = hidden_states.size()
# add position embeddings to the hidden states before projecting to queries and keys
if object_queries is not None:
hidden_states_original = hidden_states
hidden_states = self.with_pos_embed(hidden_states, object_queries)
# add key-value position embeddings to the key value states
if spatial_position_embeddings is not None:
key_value_states_original = key_value_states
key_value_states = self.with_pos_embed(key_value_states, spatial_position_embeddings)
# get query proj
query_states = self.q_proj(hidden_states) * self.scaling
# get key, value proj
if is_cross_attention:
# cross_attentions
key_states = self._shape(self.k_proj(key_value_states), -1, batch_size)
value_states = self._shape(self.v_proj(key_value_states_original), -1, batch_size)
else:
# self_attention
key_states = self._shape(self.k_proj(hidden_states), -1, batch_size)
value_states = self._shape(self.v_proj(hidden_states_original), -1, batch_size)
proj_shape = (batch_size * self.num_heads, -1, self.head_dim)
query_states = self._shape(query_states, target_len, batch_size).view(*proj_shape)
key_states = key_states.view(*proj_shape)
value_states = value_states.view(*proj_shape)
source_len = key_states.size(1)
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
if attn_weights.size() != (batch_size * self.num_heads, target_len, source_len):
raise ValueError(
f"Attention weights should be of size {(batch_size * self.num_heads, target_len, source_len)}, but is"
f" {attn_weights.size()}"
)
if attention_mask is not None:
if attention_mask.size() != (batch_size, 1, target_len, source_len):
raise ValueError(
f"Attention mask should be of size {(batch_size, 1, target_len, source_len)}, but is"
f" {attention_mask.size()}"
)
if attention_mask.dtype == torch.bool:
attention_mask = torch.zeros_like(attention_mask, dtype=attn_weights.dtype).masked_fill_(
attention_mask, -torch.inf
)
attn_weights = attn_weights.view(batch_size, self.num_heads, target_len, source_len) + attention_mask
attn_weights = attn_weights.view(batch_size * self.num_heads, target_len, source_len)
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
if output_attentions:
# this operation is a bit awkward, but it's required to
# make sure that attn_weights keeps its gradient.
# In order to do so, attn_weights have to reshaped
# twice and have to be reused in the following
attn_weights_reshaped = attn_weights.view(batch_size, self.num_heads, target_len, source_len)
attn_weights = attn_weights_reshaped.view(batch_size * self.num_heads, target_len, source_len)
else:
attn_weights_reshaped = None
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
attn_output = torch.bmm(attn_probs, value_states)
if attn_output.size() != (batch_size * self.num_heads, target_len, self.head_dim):
raise ValueError(
f"`attn_output` should be of size {(batch_size, self.num_heads, target_len, self.head_dim)}, but is"
f" {attn_output.size()}"
)
attn_output = attn_output.view(batch_size, self.num_heads, target_len, self.head_dim)
attn_output = attn_output.transpose(1, 2)
attn_output = attn_output.reshape(batch_size, target_len, embed_dim)
attn_output = self.out_proj(attn_output)
return attn_output, attn_weights_reshaped
# Copied from transformers.models.detr.modeling_detr.DetrDecoderLayer
| DetrAttention |
python | tensorflow__tensorflow | tensorflow/python/autograph/converters/call_trees.py | {
"start": 1304,
"end": 1428
} | class ____(object):
no_root = True
def __init__(self):
self.context_name = None
set_trace_warned = False
| _Function |
python | getsentry__sentry | tests/integration/test_service.py | {
"start": 476,
"end": 7457
} | class ____(TestCase):
jwt = "my_cool_jwt"
def generate_integration(self, metadata: dict[str, Any] | None = None):
integration = self.create_integration(
organization=self.organization,
provider="github",
external_id="github:1",
)
with assume_test_silo_mode_of(Integration):
if metadata is not None:
integration.metadata.update(metadata)
integration.save()
return integration
@responses.activate
@mock.patch("sentry.integrations.github.client.get_jwt", return_value=jwt)
def test_refresh_expired_token(self, mock_jwt):
integration = self.generate_integration(
metadata={
"access_token": "token_1",
"expires_at": "2025-01-01T05:21:59Z",
"permissions": {
"administration": "read",
"contents": "read",
"issues": "write",
"metadata": "read",
"pull_requests": "read",
},
}
)
responses.add(
responses.POST,
"https://api.github.com/app/installations/github:1/access_tokens",
json={
"token": "token_2",
"expires_at": "2025-01-01T06:22:00Z",
"permissions": {
"administration": "read",
},
},
status=200,
content_type="application/json",
)
rpc_integration = integration_service.refresh_github_access_token(
integration_id=integration.id,
organization_id=self.organization.id,
)
assert rpc_integration is not None
assert rpc_integration.metadata["access_token"] == "token_2"
assert rpc_integration.metadata["expires_at"] == "2025-01-01T06:22:00"
assert rpc_integration.metadata["permissions"] == {
"administration": "read",
}
@responses.activate
@mock.patch("sentry.integrations.github.client.get_jwt", return_value=jwt)
def test_refresh_token_within_grace_period(self, mock_jwt):
integration = self.generate_integration(
metadata={
"access_token": "token_1",
"expires_at": "2025-01-01T05:31:59Z",
"permissions": {
"contents": "read",
},
}
)
responses.add(
responses.POST,
"https://api.github.com/app/installations/github:1/access_tokens",
json={
"token": "token_refreshed",
"expires_at": "2025-01-01T06:32:00Z",
"permissions": {
"contents": "write",
},
},
status=200,
content_type="application/json",
)
rpc_integration = integration_service.refresh_github_access_token(
integration_id=integration.id,
organization_id=self.organization.id,
)
assert rpc_integration is not None
assert rpc_integration.metadata["access_token"] == "token_refreshed"
assert rpc_integration.metadata["expires_at"] == "2025-01-01T06:32:00"
assert rpc_integration.metadata["permissions"] == {
"contents": "write",
}
@responses.activate
@mock.patch("sentry.integrations.github.client.get_jwt", return_value=jwt)
def test_no_refresh_token_outside_grace_period(self, mock_jwt):
integration = self.generate_integration(
metadata={
"access_token": "token_valid",
"expires_at": "2025-01-01T05:32:01Z",
"permissions": {
"issues": "write",
},
}
)
rpc_integration = integration_service.refresh_github_access_token(
integration_id=integration.id,
organization_id=self.organization.id,
)
assert rpc_integration is not None
assert rpc_integration.metadata["access_token"] == "token_valid"
assert rpc_integration.metadata["expires_at"] == "2025-01-01T05:32:01Z"
assert rpc_integration.metadata["permissions"] == {
"issues": "write",
}
@responses.activate
@mock.patch("sentry.integrations.github.client.get_jwt", return_value=jwt)
def test_refresh_token_missing_expiration_time(self, mock_jwt):
integration = self.generate_integration(
metadata={
"access_token": "token_no_expiry",
"permissions": {
"metadata": "read",
},
}
)
responses.add(
responses.POST,
"https://api.github.com/app/installations/github:1/access_tokens",
json={
"token": "token_new",
"expires_at": "2025-01-01T06:22:00Z",
"permissions": {
"metadata": "write",
"pull_requests": "read",
},
},
status=200,
content_type="application/json",
)
rpc_integration = integration_service.refresh_github_access_token(
integration_id=integration.id,
organization_id=self.organization.id,
)
assert rpc_integration is not None
assert rpc_integration.metadata["access_token"] == "token_new"
assert rpc_integration.metadata["expires_at"] == "2025-01-01T06:22:00"
assert rpc_integration.metadata["permissions"] == {
"metadata": "write",
"pull_requests": "read",
}
def test_missing_integration(self):
rpc_integration = integration_service.refresh_github_access_token(
integration_id=12345,
organization_id=self.organization.id,
)
assert rpc_integration is None
def test_disabled_integration(self):
integration = self.generate_integration()
with assume_test_silo_mode_of(Integration):
integration.status = ObjectStatus.DISABLED
integration.save()
rpc_integration = integration_service.refresh_github_access_token(
integration_id=integration.id,
organization_id=self.organization.id,
)
assert rpc_integration is None
def test_missing_installation(self):
# Generate a new integration with an installation on a different org.
integration = self.create_integration(
organization=self.create_organization(owner=self.create_user()),
provider="github",
external_id="github:1",
)
rpc_integration = integration_service.refresh_github_access_token(
integration_id=integration.id,
organization_id=self.organization.id,
)
assert rpc_integration is None
| IntegrationServiceTest |
python | eventlet__eventlet | tests/db_pool_test.py | {
"start": 17586,
"end": 17692
} | class ____(Psycopg2ConnectionPool, RawConnectionPool, TestPsycopg2Base):
__test__ = True
| Test02Psycopg2Raw |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.