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 | tensorflow__tensorflow | tensorflow/python/client/timeline.py | {
"start": 12955,
"end": 30057
} | class ____(object):
"""A class for visualizing execution timelines of TensorFlow steps."""
def __init__(
self, step_stats: step_stats_pb2.StepStats, graph: Optional[Any] = None
) -> None:
"""Constructs a new Timeline.
A 'Timeline' is used for visualizing the execution of a TensorFlow
computation. It shows the timings and concurrency of execution at
the granularity of TensorFlow Ops.
This class is not thread safe.
Args:
step_stats: The 'step_stats_pb2.StepStats' proto recording execution
times.
graph: (Optional) The 'Graph' that was executed.
"""
self._origin_step_stats = step_stats
self._step_stats = None
self._graph = graph
self._chrome_trace = _ChromeTraceFormatter()
self._next_pid = 0
self._device_pids = {} # device name -> pid for compute activity.
self._tensor_pids = {} # device name -> pid for tensors.
self._tensors = {} # tensor_name -> TensorTracker
self._next_flow_id = 0
self._flow_starts = {} # tensor_name -> (timestamp, pid, tid)
self._alloc_times = {} # tensor_name -> ( time, allocator, size )
self._allocator_maximums = {} # allocator name => maximum bytes long
def _alloc_pid(self) -> int:
"""Allocate a process Id."""
pid = self._next_pid
self._next_pid += 1
return pid
def _alloc_flow_id(self) -> int:
"""Allocate a flow Id."""
flow_id = self._next_flow_id
self._next_flow_id += 1
return flow_id
def _parse_op_label(
self, label: str
) -> Tuple[str, str, List[str]]:
"""Parses the fields in a node timeline label."""
# Expects labels of the form: name = op(arg, arg, ...).
match = re.match(r'(.*) = (.*)\((.*)\)', label)
if match is None:
return 'unknown', 'unknown', []
nn, op, inputs = match.groups()
if not inputs:
inputs = []
else:
inputs = inputs.split(', ')
return nn, op, inputs
def _parse_kernel_label(self, label, node_name):
"""Parses the fields in a node timeline label."""
# Expects labels of the form: retval (arg) detail @@annotation
start = label.find('@@')
end = label.find('#')
if start >= 0 and end >= 0 and start + 2 < end:
node_name = label[start + 2 : end]
# Node names should always have the form 'name:op'.
fields = node_name.split(':') + ['unknown']
name, op = fields[:2]
return name, op
def _assign_lanes(self) -> None:
"""Assigns non-overlapping lanes for the activities on each device."""
for device_stats in self._step_stats.dev_stats:
# TODO(pbar): Genuine thread IDs in step_stats_pb2.NodeExecStats
# might be helpful.
lanes = [0]
for ns in device_stats.node_stats:
l = -1
for i, lts in enumerate(lanes):
if ns.all_start_micros > lts:
l = i
lanes[l] = ns.all_start_micros + ns.all_end_rel_micros
break
if l < 0:
l = len(lanes)
lanes.append(ns.all_start_micros + ns.all_end_rel_micros)
ns.thread_id = l
def _emit_op(
self, nodestats: step_stats_pb2.NodeExecStats, pid: int, is_gputrace: bool
) -> None:
"""Generates a Chrome Trace event to show Op execution.
Args:
nodestats: The 'step_stats_pb2.NodeExecStats' proto recording op
execution.
pid: The pid assigned for the device where this op ran.
is_gputrace: If True then this op came from the GPUTracer.
"""
node_name = nodestats.node_name
start = nodestats.all_start_micros
duration = nodestats.all_end_rel_micros
tid = nodestats.thread_id
inputs = []
if is_gputrace:
node_name, op = self._parse_kernel_label(
nodestats.timeline_label, node_name
)
elif node_name == 'RecvTensor':
# RPC tracing does not use the standard timeline_label format.
op = 'RecvTensor'
else:
_, op, inputs = self._parse_op_label(nodestats.timeline_label)
args = {'name': node_name, 'op': op}
if build_info.build_info['is_rocm_build']:
args['kernel'] = nodestats.timeline_label.split('@@')[0]
for i, iname in enumerate(inputs):
args['input%d' % i] = iname
self._chrome_trace.emit_region(start, duration, pid, tid, 'Op', op, args)
def _emit_tensor_snapshot(
self,
tensor: _TensorTracker,
timestamp: int,
pid: int,
tid: int,
value: step_stats_pb2.NodeOutput,
) -> None:
"""Generate Chrome Trace snapshot event for a computed Tensor.
Args:
tensor: A 'TensorTracker' object.
timestamp: The timestamp of this snapshot as a long integer.
pid: The pid assigned for showing the device where this op ran.
tid: The tid of the thread computing the tensor snapshot.
value: A JSON-compliant snapshot of the object.
"""
desc = str(value.tensor_description).replace('"', '')
snapshot = {'tensor_description': desc}
self._chrome_trace.emit_obj_snapshot(
'Tensor', tensor.name, timestamp, pid, tid, tensor.object_id, snapshot
)
def _produce_tensor(
self,
name: str,
timestamp: int,
tensors_pid: int,
allocator: str,
num_bytes: int,
) -> _TensorTracker:
"""Creates a new tensor tracker."""
object_id = len(self._tensors)
tensor = _TensorTracker(
name, object_id, timestamp, tensors_pid, allocator, num_bytes
)
self._tensors[name] = tensor
return tensor
def _is_gputrace_device(self, device_name: str) -> bool:
"""Returns true if this device is part of the GPUTracer logging."""
return '/stream:' in device_name or '/memcpy' in device_name
def _allocate_pids(self) -> None:
"""Allocate fake process ids for each device in the step_stats_pb2.StepStats."""
self._allocators_pid = self._alloc_pid()
self._chrome_trace.emit_pid('Allocators', self._allocators_pid)
# Add processes in the Chrome trace to show compute and data activity.
for dev_stats in self._step_stats.dev_stats:
device_pid = self._alloc_pid()
self._device_pids[dev_stats.device] = device_pid
tensors_pid = self._alloc_pid()
self._tensor_pids[dev_stats.device] = tensors_pid
self._chrome_trace.emit_pid(dev_stats.device + ' Compute', device_pid)
self._chrome_trace.emit_pid(dev_stats.device + ' Tensors', tensors_pid)
def _analyze_tensors(self, show_memory: bool) -> None:
"""Analyze tensor references to track dataflow."""
for dev_stats in self._step_stats.dev_stats:
device_pid = self._device_pids[dev_stats.device]
tensors_pid = self._tensor_pids[dev_stats.device]
for node_stats in dev_stats.node_stats:
tid = node_stats.thread_id
node_name = node_stats.node_name
start_time = node_stats.all_start_micros
end_time = node_stats.all_start_micros + node_stats.all_end_rel_micros
for index, output in enumerate(node_stats.output):
if index:
output_name = '%s:%d' % (node_name, index)
else:
output_name = node_name
allocation = output.tensor_description.allocation_description
num_bytes = allocation.requested_bytes
allocator_name = allocation.allocator_name
tensor = self._produce_tensor(
output_name, start_time, tensors_pid, allocator_name, num_bytes
)
tensor.add_ref(start_time)
tensor.add_unref(end_time)
self._flow_starts[output_name] = (end_time, device_pid, tid)
if show_memory:
self._chrome_trace.emit_obj_create(
'Tensor',
output_name,
start_time,
tensors_pid,
tid,
tensor.object_id,
)
self._emit_tensor_snapshot(
tensor, end_time - 1, tensors_pid, tid, output
)
def _show_compute(self, show_dataflow: bool) -> None:
"""Visualize the computation activity."""
for dev_stats in self._step_stats.dev_stats:
device_name = dev_stats.device
device_pid = self._device_pids[device_name]
is_gputrace = self._is_gputrace_device(device_name)
for node_stats in dev_stats.node_stats:
tid = node_stats.thread_id
start_time = node_stats.all_start_micros
end_time = node_stats.all_start_micros + node_stats.all_end_rel_micros
self._emit_op(node_stats, device_pid, is_gputrace)
if is_gputrace or node_stats.node_name == 'RecvTensor':
continue
_, _, inputs = self._parse_op_label(node_stats.timeline_label)
for input_name in inputs:
if input_name not in self._tensors:
# This can happen when partitioning has inserted a Send/Recv.
# We remove the numeric suffix so that the dataflow appears to
# come from the original node. Ideally, the StepStats would
# contain logging for the Send and Recv nodes.
index = input_name.rfind('/_')
if index > 0:
input_name = input_name[:index]
if input_name in self._tensors:
tensor = self._tensors[input_name]
tensor.add_ref(start_time)
tensor.add_unref(end_time - 1)
if show_dataflow:
# We use a different flow ID for every graph edge.
create_time, create_pid, create_tid = self._flow_starts[
input_name
]
# Don't add flows when producer and consumer ops are on the same
# pid/tid since the horizontal arrows clutter the visualization.
if create_pid != device_pid or create_tid != tid:
flow_id = self._alloc_flow_id()
self._chrome_trace.emit_flow_start(
input_name, create_time, create_pid, create_tid, flow_id
)
self._chrome_trace.emit_flow_end(
input_name, start_time, device_pid, tid, flow_id
)
else:
logging.vlog(
1, "Can't find tensor %s - removed by CSE?", input_name
)
def _show_memory_counters(self) -> None:
"""Produce a counter series for each memory allocator."""
# Iterate over all tensor trackers to build a list of allocations and
# frees for each allocator. Then sort the lists and emit a cumulative
# counter series for each allocator.
allocations = {}
for name in self._tensors:
tensor = self._tensors[name]
self._chrome_trace.emit_obj_delete(
'Tensor', name, tensor.last_unref, tensor.pid, 0, tensor.object_id
)
allocator = tensor.allocator
if allocator not in allocations:
allocations[allocator] = []
num_bytes = tensor.num_bytes
allocations[allocator].append((tensor.create_time, num_bytes, name))
allocations[allocator].append((tensor.last_unref, -num_bytes, name))
alloc_maxes = {}
# Generate a counter series showing total allocations for each allocator.
for allocator in allocations:
alloc_list = allocations[allocator]
alloc_list.sort()
total_bytes = 0
alloc_tensor_set = set()
alloc_maxes[allocator] = AllocationMaximum(
timestamp=0, num_bytes=0, tensors=set()
)
for time, num_bytes, name in sorted(
alloc_list, key=lambda allocation: allocation[0]
):
total_bytes += num_bytes
if num_bytes < 0:
alloc_tensor_set.discard(name)
else:
alloc_tensor_set.add(name)
if total_bytes > alloc_maxes[allocator].num_bytes:
alloc_maxes[allocator] = AllocationMaximum(
timestamp=time,
num_bytes=total_bytes,
tensors=copy.deepcopy(alloc_tensor_set),
)
self._chrome_trace.emit_counter(
'Memory',
allocator,
self._allocators_pid,
time,
allocator,
total_bytes,
)
self._allocator_maximums = alloc_maxes
def _preprocess_op_time(self, op_time: str) -> None:
"""Update the start and end time of ops in step stats.
Args:
op_time: How the execution time of op is shown in timeline. Possible
values are "schedule", "gpu" and "all". "schedule" will show op from
the time it is scheduled to the end of the scheduling. Notice by the end
of its scheduling its async kernels may not start yet. It is shown using
the default value from step_stats. "gpu" will show op with the execution
time of its kernels on GPU. "all" will show op from the start of its
scheduling to the end of its last kernel.
"""
if op_time == 'schedule':
self._step_stats = self._origin_step_stats
return
self._step_stats = copy.deepcopy(self._origin_step_stats)
# Separate job task and gpu tracer stream
stream_all_stats = []
job_stats = []
for stats in self._step_stats.dev_stats:
if '/stream:all' in stats.device:
stream_all_stats.append(stats)
elif '/job' in stats.device:
job_stats.append(stats)
# Record the start time of the first kernel and the end time of
# the last gpu kernel for all ops.
op_gpu_start = {}
op_gpu_end = {}
for stats in stream_all_stats:
for kernel in stats.node_stats:
name, _ = self._parse_kernel_label(
kernel.timeline_label, kernel.node_name
)
start = kernel.all_start_micros
end = kernel.all_start_micros + kernel.all_end_rel_micros
if name in op_gpu_start:
op_gpu_start[name] = min(op_gpu_start[name], start)
op_gpu_end[name] = max(op_gpu_end[name], end)
else:
op_gpu_start[name] = start
op_gpu_end[name] = end
# Update the start and end time of each op according to the op_time
for stats in job_stats:
for op in stats.node_stats:
if op.node_name in op_gpu_start:
end = max(
op_gpu_end[op.node_name],
op.all_start_micros + op.all_end_rel_micros,
)
if op_time == 'gpu':
op.all_start_micros = op_gpu_start[op.node_name]
op.all_end_rel_micros = end - op.all_start_micros
def analyze_step_stats(
self,
show_dataflow: bool = True,
show_memory: bool = True,
op_time: str = 'schedule',
) -> StepStatsAnalysis:
"""Analyze the step stats and format it into Chrome Trace Format.
Args:
show_dataflow: (Optional.) If True, add flow events to the trace
connecting producers and consumers of tensors.
show_memory: (Optional.) If True, add object snapshot events to the trace
showing the sizes and lifetimes of tensors.
op_time: (Optional.) How the execution time of op is shown in timeline.
Possible values are "schedule", "gpu" and "all". "schedule" will show op
from the time it is scheduled to the end of the scheduling. Notice by
the end of its scheduling its async kernels may not start yet. It is
shown using the default value from step_stats. "gpu" will show op with
the execution time of its kernels on GPU. "all" will show op from the
start of its scheduling to the end of its last kernel.
Returns:
A 'StepStatsAnalysis' object.
"""
self._preprocess_op_time(op_time)
self._allocate_pids()
self._assign_lanes()
self._analyze_tensors(show_memory)
self._show_compute(show_dataflow)
if show_memory:
self._show_memory_counters()
return StepStatsAnalysis(
chrome_trace=self._chrome_trace,
allocator_maximums=self._allocator_maximums,
)
def generate_chrome_trace_format(
self,
show_dataflow: bool = True,
show_memory: bool = False,
op_time: str = 'schedule',
) -> str:
# pyformat: disable
"""Produces a trace in Chrome Trace Format.
Args:
show_dataflow: (Optional.) If True, add flow events to the trace
connecting producers and consumers of tensors.
show_memory: (Optional.) If True, add object snapshot events to the trace
showing the sizes and lifetimes of tensors.
op_time: (Optional.) How the execution time of op is shown in timeline.
Possible values are "schedule", "gpu" and "all".
"schedule" will show op from the time it is scheduled to the end of
the scheduling.
Notice by the end of its scheduling its async kernels may not start
yet. It is shown using the default value from step_stats.
"gpu" will show op with the execution time of its kernels on GPU.
"all" will show op from the start of its scheduling to the end of
its last kernel.
Returns:
A JSON formatted string in Chrome Trace format.
"""
# pyformat: enable
step_stats_analysis = self.analyze_step_stats(
show_dataflow=show_dataflow, show_memory=show_memory, op_time=op_time
)
return step_stats_analysis.chrome_trace.format_to_string(pretty=True)
| Timeline |
python | huggingface__transformers | src/transformers/models/megatron_bert/modeling_megatron_bert.py | {
"start": 20839,
"end": 21558
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = MegatronBertPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
def forward(self, hidden_states):
hidden_states = self.transform(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->MegatronBert
| MegatronBertLMPredictionHead |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/decorators/asset_decorator.py | {
"start": 18040,
"end": 19236
} | class ____(NamedTuple):
required_resource_keys: AbstractSet[str]
name: Optional[str]
key_prefix: Optional[CoercibleToAssetKeyPrefix]
ins: Mapping[str, AssetIn]
deps: Iterable[AssetDep]
metadata: Optional[ArbitraryMetadataMapping]
tags: Optional[Mapping[str, str]]
description: Optional[str]
config_schema: Optional[UserConfigSchema]
resource_defs: dict[str, object]
hooks: Optional[AbstractSet[HookDefinition]]
io_manager_key: Optional[str]
io_manager_def: Optional[object]
compute_kind: Optional[str]
dagster_type: Optional[DagsterType]
partitions_def: Optional[PartitionsDefinition]
op_tags: Optional[Mapping[str, Any]]
group_name: Optional[str]
output_required: bool
legacy_freshness_policy: Optional[LegacyFreshnessPolicy]
freshness_policy: Optional[FreshnessPolicy]
automation_condition: Optional[AutomationCondition]
backfill_policy: Optional[BackfillPolicy]
retry_policy: Optional[RetryPolicy]
code_version: Optional[str]
key: Optional[CoercibleToAssetKey]
check_specs: Optional[Sequence[AssetCheckSpec]]
owners: Optional[Sequence[str]]
pool: Optional[str]
| AssetDecoratorArgs |
python | joke2k__faker | tests/providers/test_ssn.py | {
"start": 31299,
"end": 32319
} | class ____(unittest.TestCase):
def setUp(self):
self.fake = Faker("hu_HU")
Faker.seed(0)
def test_ssn(self):
for _ in range(100):
ssn = self.fake.ssn()
assert ssn.isdigit()
assert len(ssn) >= 10
assert len(ssn) <= 12
for _ in range(100):
dob_val = (
f"{self.fake.random_int(0, 99):02d}"
f"{self.fake.random_int(1, 12):02d}"
f"{self.fake.random_int(1, 31):02d}"
)
dob = self.fake.random.choice([None, dob_val])
gender = self.fake.random.choice([None, "F", "M", "z"])
try:
ssn = self.fake.ssn(dob=dob, gender=gender)
assert ssn.isdigit()
assert len(ssn) >= 10
assert len(ssn) <= 12
except ValueError:
pass
def test_vat_id(self):
for _ in range(100):
assert re.search(r"^HU\d{8}$", self.fake.vat_id())
| TestHuHU |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 584838,
"end": 585197
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("errors",)
errors = sgqlc.types.Field(
sgqlc.types.non_null(
sgqlc.types.list_of(sgqlc.types.non_null("RepositoryCodeownersError"))
),
graphql_name="errors",
)
| RepositoryCodeowners |
python | pytorch__pytorch | torch/fx/proxy.py | {
"start": 2224,
"end": 3541
} | class ____:
"""A context manager to track the Scope of Node during symbolic tracing.
When entering a forward function of a Module, we'll update the scope information of
the current module, and when we exit, we'll restore the previous scope information.
"""
def __init__(
self,
scope: Scope,
current_scope: Scope,
):
super().__init__()
# Keep a copy of prev scope to restore on exit
self._prev_scope = copy.copy(scope)
# Update scope to current scope
scope.module_path = current_scope.module_path
scope.module_type = current_scope.module_type
# Save a reference so we can restore it
self._scope = scope
def __enter__(self):
return self._scope
def __exit__(self, *args):
self._scope.module_path = self._prev_scope.module_path
self._scope.module_type = self._prev_scope.module_type
return
_COPY_META_FIELDS = [
"nn_module_stack",
"torch_fn",
"source_fn_stack",
"original_aten",
"recompute",
"ac_graph_id",
"has_backward_hook",
"from_node",
"quantization_tag", # TODO deprecated
"_numeric_debug_handle", # TODO deprecated
"custom",
"partitioner_tag",
]
@compatibility(is_backward_compatible=True)
| ScopeContextManager |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 465394,
"end": 465862
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of AddLabelsToLabelable"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "labelable")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
labelable = sgqlc.types.Field(Labelable, graphql_name="labelable")
"""The item that was labeled."""
| AddLabelsToLabelablePayload |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_insights_tree.py | {
"start": 352,
"end": 5505
} | class ____(
OrganizationEventsEndpointTestBase, SnubaTestCase, SpanTestCase
):
url_name = "sentry-api-0-organization-insights-tree"
FEATURES = ["organizations:trace-spans-format"]
def setUp(self) -> None:
super().setUp()
self.ten_mins_ago = before_now(minutes=10)
self.features = {}
self.url = reverse(
self.url_name,
kwargs={
"organization_id_or_slug": self.project.organization.slug,
},
)
self.create_environment(self.project, name="production")
self._store_nextjs_function_spans()
self._store_unrelated_spans()
def _store_nextjs_function_spans(self) -> None:
descriptions = [
"Page Server Component (/app/dashboard/)",
"Loading Server Component (/app/dashboard/)",
"Layout Server Component (/app/)",
"Not-found Server Component (/app/dashboard/)",
"Head Server Component (/app/dashboard/)",
"Unknown Server Component (/app/dashboard/)",
"Page.generateMetadata (/app/dashboard/)",
"Page.generateImageMetadata (/app/dashboard/)",
"Page.generateViewport (/app/dashboard/)",
"Page Server Component (/app/dashboard/settings/)",
"Page Server Component (/app/dashboard/users/)",
"Layout Server Component (/app/dashboard/)",
"Page Server Component (/)",
"Page Server Component (/app/dashboard/[userId]/)",
"Page Server Component (/app/[category]/[product]/)",
"Layout Server Component (/app/[id]/)",
"Page Server Component (/app/[id]/)",
"Page Server Component (/app/[...slug]/)",
"Page Server Component (/app/[[...optional]]/)",
"unrelated description",
]
spans = []
for description in descriptions:
span = self.create_span(
{"description": description},
organization=self.project.organization,
project=self.project,
duration=100,
start_ts=self.ten_mins_ago,
)
span["sentry_tags"]["op"] = "function.nextjs"
self.store_span(span, is_eap=True)
spans.append(span)
def _store_unrelated_spans(self) -> None:
descriptions = [
"INSERT value INTO table",
"SELECT * FROM table",
]
spans = []
for description in descriptions:
span = self.create_span(
{"description": description},
organization=self.project.organization,
project=self.project,
duration=100,
start_ts=self.ten_mins_ago,
)
span["sentry_tags"]["op"] = "db"
self.store_span(span, is_eap=True)
spans.append(span)
def test_get_nextjs_function_data(self) -> None:
self.login_as(user=self.user)
with self.feature(self.FEATURES):
response = self.client.get(
self.url,
data={
"statsPeriod": "14d",
"noPagination": True,
"query": "span.op:function.nextjs",
"mode": "aggregate",
"field": ["span.description", "avg(span.duration)", "count(span.duration)"],
"project": self.project.id,
"dataset": "spans",
},
)
assert response.status_code == 200
span_descriptions = [row["span.description"] for row in response.data["data"]]
assert "Page Server Component (/app/[category]/[product]/)" in span_descriptions
root_route_idx = span_descriptions.index("Page Server Component (/)")
element = response.data["data"][root_route_idx]
assert element["function.nextjs.component_type"] == "Page Server Component"
assert element["function.nextjs.path"] == []
unparameterized_route_idx = span_descriptions.index(
"Page.generateMetadata (/app/dashboard/)"
)
element = response.data["data"][unparameterized_route_idx]
assert element["function.nextjs.component_type"] == "Page.generateMetadata"
assert element["function.nextjs.path"] == ["app", "dashboard"]
parameterized_route_idx = span_descriptions.index(
"Page Server Component (/app/[category]/[product]/)"
)
element = response.data["data"][parameterized_route_idx]
assert element["function.nextjs.component_type"] == "Page Server Component"
assert element["function.nextjs.path"] == ["app", "[category]", "[product]"]
catchall_route_idx = span_descriptions.index("Page Server Component (/app/[...slug]/)")
element = response.data["data"][catchall_route_idx]
assert element["function.nextjs.component_type"] == "Page Server Component"
assert element["function.nextjs.path"] == ["app", "[...slug]"]
assert "INSERT value INTO table" not in span_descriptions
| OrganizationInsightsTreeEndpointTest |
python | walkccc__LeetCode | solutions/2097. Valid Arrangement of Pairs/2097.py | {
"start": 0,
"end": 705
} | class ____:
def validArrangement(self, pairs: list[list[int]]) -> list[list[int]]:
ans = []
graph = collections.defaultdict(list)
outDegree = collections.Counter()
inDegrees = collections.Counter()
for start, end in pairs:
graph[start].append(end)
outDegree[start] += 1
inDegrees[end] += 1
def getStartNode() -> int:
for u in graph.keys():
if outDegree[u] - inDegrees[u] == 1:
return u
return pairs[0][0] # Arbitrarily choose a node.
def euler(u: int) -> None:
stack = graph[u]
while stack:
v = stack.pop()
euler(v)
ans.append([u, v])
euler(getStartNode())
return ans[::-1]
| Solution |
python | scipy__scipy | scipy/stats/_sensitivity_analysis.py | {
"start": 4366,
"end": 25123
} | class ____:
first_order: np.ndarray
total_order: np.ndarray
_indices_method: Callable
_f_A: np.ndarray
_f_B: np.ndarray
_f_AB: np.ndarray
_A: np.ndarray | None = None
_B: np.ndarray | None = None
_AB: np.ndarray | None = None
_bootstrap_result: BootstrapResult | None = None
def bootstrap(
self,
confidence_level: "DecimalNumber" = 0.95,
n_resamples: "IntNumber" = 999
) -> BootstrapSobolResult:
"""Bootstrap Sobol' indices to provide confidence intervals.
Parameters
----------
confidence_level : float, default: ``0.95``
The confidence level of the confidence intervals.
n_resamples : int, default: ``999``
The number of resamples performed to form the bootstrap
distribution of the indices.
Returns
-------
res : BootstrapSobolResult
Bootstrap result containing the confidence intervals and the
bootstrap distribution of the indices.
An object with attributes:
first_order : BootstrapResult
Bootstrap result of the first order indices.
total_order : BootstrapResult
Bootstrap result of the total order indices.
See `BootstrapResult` for more details.
"""
def statistic(idx):
f_A_ = self._f_A[:, idx]
f_B_ = self._f_B[:, idx]
f_AB_ = self._f_AB[..., idx]
return self._indices_method(f_A_, f_B_, f_AB_)
n = self._f_A.shape[1]
res = bootstrap(
[np.arange(n)], statistic=statistic, method="BCa",
n_resamples=n_resamples,
confidence_level=confidence_level,
bootstrap_result=self._bootstrap_result
)
self._bootstrap_result = res
first_order = BootstrapResult(
confidence_interval=ConfidenceInterval(
res.confidence_interval.low[0], res.confidence_interval.high[0]
),
bootstrap_distribution=res.bootstrap_distribution[0],
standard_error=res.standard_error[0],
)
total_order = BootstrapResult(
confidence_interval=ConfidenceInterval(
res.confidence_interval.low[1], res.confidence_interval.high[1]
),
bootstrap_distribution=res.bootstrap_distribution[1],
standard_error=res.standard_error[1],
)
return BootstrapSobolResult(
first_order=first_order, total_order=total_order
)
@xp_capabilities(np_only=True)
@_transition_to_rng('random_state', replace_doc=False)
def sobol_indices(
*,
func,
n,
dists=None,
method='saltelli_2010',
rng=None
):
r"""Global sensitivity indices of Sobol'.
Parameters
----------
func : callable or dict(str, array_like)
If `func` is a callable, function to compute the Sobol' indices from.
Its signature must be::
func(x: ArrayLike) -> ArrayLike
with ``x`` of shape ``(d, n)`` and output of shape ``(s, n)`` where:
- ``d`` is the input dimensionality of `func`
(number of input variables),
- ``s`` is the output dimensionality of `func`
(number of output variables), and
- ``n`` is the number of samples (see `n` below).
Function evaluation values must be finite.
If `func` is a dictionary, contains the function evaluations from three
different arrays. Keys must be: ``f_A``, ``f_B`` and ``f_AB``.
``f_A`` and ``f_B`` should have a shape ``(s, n)`` and ``f_AB``
should have a shape ``(d, s, n)``.
This is an advanced feature and misuse can lead to wrong analysis.
n : int
Number of samples used to generate the matrices ``A`` and ``B``.
Must be a power of 2. The total number of points at which `func` is
evaluated will be ``n*(d+2)``.
dists : list(distributions), optional
List of each parameter's distribution. The distribution of parameters
depends on the application and should be carefully chosen.
Parameters are assumed to be independently distributed, meaning there
is no constraint nor relationship between their values.
Distributions must be an instance of a class with a ``ppf``
method.
Must be specified if `func` is a callable, and ignored otherwise.
method : Callable or str, default: 'saltelli_2010'
Method used to compute the first and total Sobol' indices.
If a callable, its signature must be::
func(f_A: np.ndarray, f_B: np.ndarray, f_AB: np.ndarray)
-> Tuple[np.ndarray, np.ndarray]
with ``f_A, f_B`` of shape ``(s, n)`` and ``f_AB`` of shape
``(d, s, n)``.
These arrays contain the function evaluations from three different sets
of samples.
The output is a tuple of the first and total indices with
shape ``(s, d)``.
This is an advanced feature and misuse can lead to wrong analysis.
rng : `numpy.random.Generator`, optional
Pseudorandom number generator state. When `rng` is None, a new
`numpy.random.Generator` is created using entropy from the
operating system. Types other than `numpy.random.Generator` are
passed to `numpy.random.default_rng` to instantiate a ``Generator``.
.. versionchanged:: 1.15.0
As part of the `SPEC-007 <https://scientific-python.org/specs/spec-0007/>`_
transition from use of `numpy.random.RandomState` to
`numpy.random.Generator`, this keyword was changed from `random_state` to
`rng`. For an interim period, both keywords will continue to work, although
only one may be specified at a time. After the interim period, function
calls using the `random_state` keyword will emit warnings. Following a
deprecation period, the `random_state` keyword will be removed.
Returns
-------
res : SobolResult
An object with attributes:
first_order : ndarray of shape (s, d)
First order Sobol' indices.
total_order : ndarray of shape (s, d)
Total order Sobol' indices.
And method:
bootstrap(confidence_level: float, n_resamples: int)
-> BootstrapSobolResult
A method providing confidence intervals on the indices.
See `scipy.stats.bootstrap` for more details.
The bootstrapping is done on both first and total order indices,
and they are available in `BootstrapSobolResult` as attributes
``first_order`` and ``total_order``.
Notes
-----
The Sobol' method [1]_, [2]_ is a variance-based Sensitivity Analysis which
obtains the contribution of each parameter to the variance of the
quantities of interest (QoIs; i.e., the outputs of `func`).
Respective contributions can be used to rank the parameters and
also gauge the complexity of the model by computing the
model's effective (or mean) dimension.
.. note::
Parameters are assumed to be independently distributed. Each
parameter can still follow any distribution. In fact, the distribution
is very important and should match the real distribution of the
parameters.
It uses a functional decomposition of the variance of the function to
explore
.. math::
\mathbb{V}(Y) = \sum_{i}^{d} \mathbb{V}_i (Y) + \sum_{i<j}^{d}
\mathbb{V}_{ij}(Y) + ... + \mathbb{V}_{1,2,...,d}(Y),
introducing conditional variances:
.. math::
\mathbb{V}_i(Y) = \mathbb{\mathbb{V}}[\mathbb{E}(Y|x_i)]
\qquad
\mathbb{V}_{ij}(Y) = \mathbb{\mathbb{V}}[\mathbb{E}(Y|x_i x_j)]
- \mathbb{V}_i(Y) - \mathbb{V}_j(Y),
Sobol' indices are expressed as
.. math::
S_i = \frac{\mathbb{V}_i(Y)}{\mathbb{V}[Y]}
\qquad
S_{ij} =\frac{\mathbb{V}_{ij}(Y)}{\mathbb{V}[Y]}.
:math:`S_{i}` corresponds to the first-order term which apprises the
contribution of the i-th parameter, while :math:`S_{ij}` corresponds to the
second-order term which informs about the contribution of interactions
between the i-th and the j-th parameters. These equations can be
generalized to compute higher order terms; however, they are expensive to
compute and their interpretation is complex.
This is why only first order indices are provided.
Total order indices represent the global contribution of the parameters
to the variance of the QoI and are defined as:
.. math::
S_{T_i} = S_i + \sum_j S_{ij} + \sum_{j,k} S_{ijk} + ...
= 1 - \frac{\mathbb{V}[\mathbb{E}(Y|x_{\sim i})]}{\mathbb{V}[Y]}.
First order indices sum to at most 1, while total order indices sum to at
least 1. If there are no interactions, then first and total order indices
are equal, and both first and total order indices sum to 1.
.. warning::
Negative Sobol' values are due to numerical errors. Increasing the
number of points `n` should help.
The number of sample required to have a good analysis increases with
the dimensionality of the problem. e.g. for a 3 dimension problem,
consider at minima ``n >= 2**12``. The more complex the model is,
the more samples will be needed.
Even for a purely additive model, the indices may not sum to 1 due
to numerical noise.
References
----------
.. [1] Sobol, I. M.. "Sensitivity analysis for nonlinear mathematical
models." Mathematical Modeling and Computational Experiment, 1:407-414,
1993.
.. [2] Sobol, I. M. (2001). "Global sensitivity indices for nonlinear
mathematical models and their Monte Carlo estimates." Mathematics
and Computers in Simulation, 55(1-3):271-280,
:doi:`10.1016/S0378-4754(00)00270-6`, 2001.
.. [3] Saltelli, A. "Making best use of model evaluations to
compute sensitivity indices." Computer Physics Communications,
145(2):280-297, :doi:`10.1016/S0010-4655(02)00280-1`, 2002.
.. [4] Saltelli, A., M. Ratto, T. Andres, F. Campolongo, J. Cariboni,
D. Gatelli, M. Saisana, and S. Tarantola. "Global Sensitivity Analysis.
The Primer." 2007.
.. [5] Saltelli, A., P. Annoni, I. Azzini, F. Campolongo, M. Ratto, and
S. Tarantola. "Variance based sensitivity analysis of model
output. Design and estimator for the total sensitivity index."
Computer Physics Communications, 181(2):259-270,
:doi:`10.1016/j.cpc.2009.09.018`, 2010.
.. [6] Ishigami, T. and T. Homma. "An importance quantification technique
in uncertainty analysis for computer models." IEEE,
:doi:`10.1109/ISUMA.1990.151285`, 1990.
Examples
--------
The following is an example with the Ishigami function [6]_
.. math::
Y(\mathbf{x}) = \sin x_1 + 7 \sin^2 x_2 + 0.1 x_3^4 \sin x_1,
with :math:`\mathbf{x} \in [-\pi, \pi]^3`. This function exhibits strong
non-linearity and non-monotonicity.
Remember, Sobol' indices assumes that samples are independently
distributed. In this case we use a uniform distribution on each marginals.
>>> import numpy as np
>>> from scipy.stats import sobol_indices, uniform
>>> rng = np.random.default_rng()
>>> def f_ishigami(x):
... f_eval = (
... np.sin(x[0])
... + 7 * np.sin(x[1])**2
... + 0.1 * (x[2]**4) * np.sin(x[0])
... )
... return f_eval
>>> indices = sobol_indices(
... func=f_ishigami, n=1024,
... dists=[
... uniform(loc=-np.pi, scale=2*np.pi),
... uniform(loc=-np.pi, scale=2*np.pi),
... uniform(loc=-np.pi, scale=2*np.pi)
... ],
... rng=rng
... )
>>> indices.first_order
array([0.31637954, 0.43781162, 0.00318825])
>>> indices.total_order
array([0.56122127, 0.44287857, 0.24229595])
Confidence interval can be obtained using bootstrapping.
>>> boot = indices.bootstrap()
Then, this information can be easily visualized.
>>> import matplotlib.pyplot as plt
>>> fig, axs = plt.subplots(1, 2, figsize=(9, 4))
>>> _ = axs[0].errorbar(
... [1, 2, 3], indices.first_order, fmt='o',
... yerr=[
... indices.first_order - boot.first_order.confidence_interval.low,
... boot.first_order.confidence_interval.high - indices.first_order
... ],
... )
>>> axs[0].set_ylabel("First order Sobol' indices")
>>> axs[0].set_xlabel('Input parameters')
>>> axs[0].set_xticks([1, 2, 3])
>>> _ = axs[1].errorbar(
... [1, 2, 3], indices.total_order, fmt='o',
... yerr=[
... indices.total_order - boot.total_order.confidence_interval.low,
... boot.total_order.confidence_interval.high - indices.total_order
... ],
... )
>>> axs[1].set_ylabel("Total order Sobol' indices")
>>> axs[1].set_xlabel('Input parameters')
>>> axs[1].set_xticks([1, 2, 3])
>>> plt.tight_layout()
>>> plt.show()
.. note::
By default, `scipy.stats.uniform` has support ``[0, 1]``.
Using the parameters ``loc`` and ``scale``, one obtains the uniform
distribution on ``[loc, loc + scale]``.
This result is particularly interesting because the first order index
:math:`S_{x_3} = 0` whereas its total order is :math:`S_{T_{x_3}} = 0.244`.
This means that higher order interactions with :math:`x_3` are responsible
for the difference. Almost 25% of the observed variance
on the QoI is due to the correlations between :math:`x_3` and :math:`x_1`,
although :math:`x_3` by itself has no impact on the QoI.
The following gives a visual explanation of Sobol' indices on this
function. Let's generate 1024 samples in :math:`[-\pi, \pi]^3` and
calculate the value of the output.
>>> from scipy.stats import qmc
>>> n_dim = 3
>>> p_labels = ['$x_1$', '$x_2$', '$x_3$']
>>> sample = qmc.Sobol(d=n_dim, seed=rng).random(1024)
>>> sample = qmc.scale(
... sample=sample,
... l_bounds=[-np.pi, -np.pi, -np.pi],
... u_bounds=[np.pi, np.pi, np.pi]
... )
>>> output = f_ishigami(sample.T)
Now we can do scatter plots of the output with respect to each parameter.
This gives a visual way to understand how each parameter impacts the
output of the function.
>>> fig, ax = plt.subplots(1, n_dim, figsize=(12, 4))
>>> for i in range(n_dim):
... xi = sample[:, i]
... ax[i].scatter(xi, output, marker='+')
... ax[i].set_xlabel(p_labels[i])
>>> ax[0].set_ylabel('Y')
>>> plt.tight_layout()
>>> plt.show()
Now Sobol' goes a step further:
by conditioning the output value by given values of the parameter
(black lines), the conditional output mean is computed. It corresponds to
the term :math:`\mathbb{E}(Y|x_i)`. Taking the variance of this term gives
the numerator of the Sobol' indices.
>>> mini = np.min(output)
>>> maxi = np.max(output)
>>> n_bins = 10
>>> bins = np.linspace(-np.pi, np.pi, num=n_bins, endpoint=False)
>>> dx = bins[1] - bins[0]
>>> fig, ax = plt.subplots(1, n_dim, figsize=(12, 4))
>>> for i in range(n_dim):
... xi = sample[:, i]
... ax[i].scatter(xi, output, marker='+')
... ax[i].set_xlabel(p_labels[i])
... for bin_ in bins:
... idx = np.where((bin_ <= xi) & (xi <= bin_ + dx))
... xi_ = xi[idx]
... y_ = output[idx]
... ave_y_ = np.mean(y_)
... ax[i].plot([bin_ + dx/2] * 2, [mini, maxi], c='k')
... ax[i].scatter(bin_ + dx/2, ave_y_, c='r')
>>> ax[0].set_ylabel('Y')
>>> plt.tight_layout()
>>> plt.show()
Looking at :math:`x_3`, the variance
of the mean is zero leading to :math:`S_{x_3} = 0`. But we can further
observe that the variance of the output is not constant along the parameter
values of :math:`x_3`. This heteroscedasticity is explained by higher order
interactions. Moreover, an heteroscedasticity is also noticeable on
:math:`x_1` leading to an interaction between :math:`x_3` and :math:`x_1`.
On :math:`x_2`, the variance seems to be constant and thus null interaction
with this parameter can be supposed.
This case is fairly simple to analyse visually---although it is only a
qualitative analysis. Nevertheless, when the number of input parameters
increases such analysis becomes unrealistic as it would be difficult to
conclude on high-order terms. Hence the benefit of using Sobol' indices.
"""
rng = check_random_state(rng)
n_ = int(n)
if not (n_ & (n_ - 1) == 0) or n != n_:
raise ValueError(
"The balance properties of Sobol' points require 'n' "
"to be a power of 2."
)
n = n_
if not callable(method):
indices_methods = {
"saltelli_2010": saltelli_2010,
}
try:
method = method.lower() # type: ignore[assignment]
indices_method_ = indices_methods[method]
except KeyError as exc:
message = (
f"{method!r} is not a valid 'method'. It must be one of"
f" {set(indices_methods)!r} or a callable."
)
raise ValueError(message) from exc
else:
indices_method_ = method
sig = inspect.signature(indices_method_)
if set(sig.parameters) != {'f_A', 'f_B', 'f_AB'}:
message = (
"If 'method' is a callable, it must have the following"
f" signature: {inspect.signature(saltelli_2010)}"
)
raise ValueError(message)
def indices_method(f_A, f_B, f_AB):
"""Wrap indices method to ensure proper output dimension.
1D when single output, 2D otherwise.
"""
return np.squeeze(indices_method_(f_A=f_A, f_B=f_B, f_AB=f_AB))
if callable(func):
if dists is None:
raise ValueError(
"'dists' must be defined when 'func' is a callable."
)
def wrapped_func(x):
return np.atleast_2d(func(x))
A, B = sample_A_B(n=n, dists=dists, rng=rng)
AB = sample_AB(A=A, B=B)
f_A = wrapped_func(A)
if f_A.shape[1] != n:
raise ValueError(
"'func' output should have a shape ``(s, -1)`` with ``s`` "
"the number of output."
)
def funcAB(AB):
d, d, n = AB.shape
AB = np.moveaxis(AB, 0, -1).reshape(d, n*d)
f_AB = wrapped_func(AB)
return np.moveaxis(f_AB.reshape((-1, n, d)), -1, 0)
f_B = wrapped_func(B)
f_AB = funcAB(AB)
else:
message = (
"When 'func' is a dictionary, it must contain the following "
"keys: 'f_A', 'f_B' and 'f_AB'."
"'f_A' and 'f_B' should have a shape ``(s, n)`` and 'f_AB' "
"should have a shape ``(d, s, n)``."
)
try:
f_A, f_B, f_AB = map(lambda arr: arr.copy(), np.atleast_2d(
func['f_A'], func['f_B'], func['f_AB']
))
except KeyError as exc:
raise ValueError(message) from exc
if f_A.shape[1] != n or f_A.shape != f_B.shape or \
f_AB.shape == f_A.shape or f_AB.shape[-1] % n != 0:
raise ValueError(message)
# Normalization by mean
# Sobol', I. and Levitan, Y. L. (1999). On the use of variance reducing
# multipliers in monte carlo computations of a global sensitivity index.
# Computer Physics Communications, 117(1) :52-61.
mean = np.mean([f_A, f_B], axis=(0, -1)).reshape(-1, 1)
f_A -= mean
f_B -= mean
f_AB -= mean
# Compute indices
# Filter warnings for constant output as var = 0
with np.errstate(divide='ignore', invalid='ignore'):
first_order, total_order = indices_method(f_A=f_A, f_B=f_B, f_AB=f_AB)
# null variance means null indices
first_order[~np.isfinite(first_order)] = 0
total_order[~np.isfinite(total_order)] = 0
res = dict(
first_order=first_order,
total_order=total_order,
_indices_method=indices_method,
_f_A=f_A,
_f_B=f_B,
_f_AB=f_AB
)
if callable(func):
res.update(
dict(
_A=A,
_B=B,
_AB=AB,
)
)
return SobolResult(**res)
| SobolResult |
python | ansible__ansible | lib/ansible/modules/mount_facts.py | {
"start": 8553,
"end": 26018
} | class ____:
mount_point: str
line: str
fields: dict[str, str | dict[str, str]]
def replace_octal_escapes(value: str) -> str:
return re.sub(r"(\\[0-7]{3})", lambda m: codecs.decode(m.group(0), "unicode_escape"), value)
@functools.lru_cache(maxsize=None)
def get_device_by_uuid(module: AnsibleModule, uuid : str) -> str | None:
"""Get device information by UUID."""
blkid_output = None
if (blkid_binary := module.get_bin_path("blkid")):
cmd = [blkid_binary, "--uuid", uuid]
with suppress(subprocess.CalledProcessError):
blkid_output = handle_timeout(module)(subprocess.check_output)(cmd, text=True, timeout=module.params["timeout"])
return blkid_output
@functools.lru_cache(maxsize=None)
def list_uuids_linux() -> list[str]:
"""List UUIDs from the system."""
with suppress(OSError):
return os.listdir("/dev/disk/by-uuid")
return []
@functools.lru_cache(maxsize=None)
def run_lsblk(module : AnsibleModule) -> list[list[str]]:
"""Return device, UUID pairs from lsblk."""
lsblk_output = ""
if (lsblk_binary := module.get_bin_path("lsblk")):
cmd = [lsblk_binary, "--list", "--noheadings", "--paths", "--output", "NAME,UUID", "--exclude", "2"]
lsblk_output = subprocess.check_output(cmd, text=True, timeout=module.params["timeout"])
return [line.split() for line in lsblk_output.splitlines() if len(line.split()) == 2]
@functools.lru_cache(maxsize=None)
def get_udevadm_device_uuid(module : AnsibleModule, device : str) -> str | None:
"""Fallback to get the device's UUID for lsblk <= 2.23 which doesn't have the --paths option."""
udevadm_output = ""
if (udevadm_binary := module.get_bin_path("udevadm")):
cmd = [udevadm_binary, "info", "--query", "property", "--name", device]
udevadm_output = subprocess.check_output(cmd, text=True, timeout=module.params["timeout"])
uuid = None
for line in udevadm_output.splitlines():
# a snippet of the output of the udevadm command below will be:
# ...
# ID_FS_TYPE=ext4
# ID_FS_USAGE=filesystem
# ID_FS_UUID=57b1a3e7-9019-4747-9809-7ec52bba9179
# ...
if line.startswith("ID_FS_UUID="):
uuid = line.split("=", 1)[1]
break
return uuid
def get_partition_uuid(module: AnsibleModule, partname : str) -> str | None:
"""Get the UUID of a partition by its name."""
# TODO: NetBSD and FreeBSD can have UUIDs in /etc/fstab,
# but none of these methods work (mount always displays the label though)
for uuid in list_uuids_linux():
dev = os.path.realpath(os.path.join("/dev/disk/by-uuid", uuid))
if partname == dev:
return uuid
for dev, uuid in handle_timeout(module, default=[])(run_lsblk)(module):
if partname == dev:
return uuid
return handle_timeout(module)(get_udevadm_device_uuid)(module, partname)
def handle_timeout(module, default=None):
"""Decorator to catch timeout exceptions and handle failing, warning, and ignoring the timeout."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except (subprocess.TimeoutExpired, _timeout.TimeoutError) as e:
if module.params["on_timeout"] == "error":
module.fail_json(msg=str(e))
elif module.params["on_timeout"] == "warn":
module.warn(str(e))
return default
return wrapper
return decorator
def run_mount_bin(module: AnsibleModule, mount_bin: str) -> str: # type: ignore # Missing return statement
"""Execute the specified mount binary with optional timeout."""
mount_bin = module.get_bin_path(mount_bin, required=True)
try:
return handle_timeout(module, default="")(subprocess.check_output)(
mount_bin, text=True, timeout=module.params["timeout"]
)
except subprocess.CalledProcessError as e:
module.fail_json(msg=f"Failed to execute {mount_bin}: {str(e)}")
def get_mount_pattern(stdout: str):
lines = stdout.splitlines()
pattern = None
if all(LINUX_MOUNT_RE.match(line) for line in lines):
pattern = LINUX_MOUNT_RE
elif all(BSD_MOUNT_RE.match(line) for line in lines if not line.startswith("map ")):
pattern = BSD_MOUNT_RE
elif len(lines) > 2 and all(AIX_MOUNT_RE.match(line) for line in lines[2:]):
pattern = AIX_MOUNT_RE
return pattern
def gen_mounts_from_stdout(stdout: str) -> t.Iterable[MountInfo]:
"""List mount dictionaries from mount stdout."""
if not (pattern := get_mount_pattern(stdout)):
stdout = ""
for line in stdout.splitlines():
if not (match := pattern.match(line)):
# AIX has a couple header lines for some reason
# MacOS "map" lines are skipped (e.g. "map auto_home on /System/Volumes/Data/home (autofs, automounted, nobrowse)")
# TODO: include MacOS lines
continue
mount = match.groupdict()["mount"]
if pattern is LINUX_MOUNT_RE:
mount_info = match.groupdict()
elif pattern is BSD_MOUNT_RE:
# the group containing fstype is comma separated, and may include whitespace
mount_info = match.groupdict()
parts = re.split(r"\s*,\s*", match.group("fstype"), maxsplit=1)
if len(parts) == 1:
mount_info["fstype"] = parts[0]
else:
mount_info.update({"fstype": parts[0], "options": parts[1]})
elif pattern is AIX_MOUNT_RE:
mount_info = match.groupdict()
device = mount_info.pop("mounted")
node = mount_info.pop("node")
if device and node:
device = f"{node}:{device}"
mount_info["device"] = device
yield MountInfo(mount, line, mount_info)
def gen_fstab_entries(lines: list[str]) -> t.Iterable[MountInfo]:
"""Yield tuples from /etc/fstab https://man7.org/linux/man-pages/man5/fstab.5.html.
Each tuple contains the mount point, line of origin, and the dictionary of the parsed line.
"""
for line in lines:
if not (line := line.strip()) or line.startswith("#"):
continue
fields = [replace_octal_escapes(field) for field in line.split()]
mount_info: dict[str, str | int] = {
"device": fields[0],
"mount": fields[1],
"fstype": fields[2],
"options": fields[3],
}
with suppress(IndexError):
# the last two fields are optional
mount_info["dump"] = int(fields[4])
mount_info["passno"] = int(fields[5])
yield MountInfo(fields[1], line, mount_info)
def gen_vfstab_entries(lines: list[str]) -> t.Iterable[MountInfo]:
"""Yield tuples from /etc/vfstab https://docs.oracle.com/cd/E36784_01/html/E36882/vfstab-4.html.
Each tuple contains the mount point, line of origin, and the dictionary of the parsed line.
"""
for line in lines:
if not line.strip() or line.strip().startswith("#"):
continue
fields = line.split()
passno: str | int = fields[4]
with suppress(ValueError):
passno = int(passno)
mount_info: dict[str, str | int] = {
"device": fields[0],
"device_to_fsck": fields[1],
"mount": fields[2],
"fstype": fields[3],
"passno": passno,
"mount_at_boot": fields[5],
"options": fields[6],
}
yield MountInfo(fields[2], line, mount_info)
def list_aix_filesystems_stanzas(lines: list[str]) -> list[list[str]]:
"""Parse stanzas from /etc/filesystems according to https://www.ibm.com/docs/hu/aix/7.2?topic=files-filesystems-file."""
stanzas = []
for line in lines:
if line.startswith("*") or not line.strip():
continue
if line.rstrip().endswith(":"):
stanzas.append([line])
else:
if "=" not in line:
# Expected for Linux, return an empty list since this doesn't appear to be AIX /etc/filesystems
stanzas = []
break
stanzas[-1].append(line)
return stanzas
def gen_aix_filesystems_entries(lines: list[str]) -> t.Iterable[MountInfoOptions]:
"""Yield tuples from /etc/filesystems https://www.ibm.com/docs/hu/aix/7.2?topic=files-filesystems-file.
Each tuple contains the mount point, lines of origin, and the dictionary of the parsed lines.
"""
for stanza in list_aix_filesystems_stanzas(lines):
original = "\n".join(stanza)
mount = stanza.pop(0)[:-1] # snip trailing :
mount_info: dict[str, str] = {}
for line in stanza:
attr, value = line.split("=", 1)
mount_info[attr.strip()] = value.strip()
device = ""
if (nodename := mount_info.get("nodename")):
device = nodename
if (dev := mount_info.get("dev")):
if device:
device += ":"
device += dev
normalized_fields: dict[str, str | dict[str, str]] = {
"mount": mount,
"device": device or "unknown",
"fstype": mount_info.get("vfs") or "unknown",
# avoid clobbering the mount point with the AIX mount option "mount"
"attributes": mount_info,
}
yield MountInfoOptions(mount, original, normalized_fields)
def gen_mnttab_entries(lines: list[str]) -> t.Iterable[MountInfo]:
"""Yield tuples from /etc/mnttab columns https://docs.oracle.com/cd/E36784_01/html/E36882/mnttab-4.html.
Each tuple contains the mount point, line of origin, and the dictionary of the parsed line.
"""
if not any(len(fields[4]) == 10 for line in lines for fields in [line.split()]):
raise ValueError
for line in lines:
fields = line.split()
datetime.date.fromtimestamp(int(fields[4]))
mount_info: dict[str, str | int] = {
"device": fields[0],
"mount": fields[1],
"fstype": fields[2],
"options": fields[3],
"time": int(fields[4]),
}
yield MountInfo(fields[1], line, mount_info)
def gen_mounts_by_file(file: str) -> t.Iterable[MountInfo | MountInfoOptions]:
"""Yield parsed mount entries from the first successful generator.
Generators are tried in the following order to minimize false positives:
- /etc/vfstab: 7 columns
- /etc/mnttab: 5 columns (mnttab[4] must contain UNIX timestamp)
- /etc/fstab: 4-6 columns (fstab[4] is optional and historically 0-9, but can be any int)
- /etc/filesystems: multi-line, not column-based, and specific to AIX
"""
if (lines := get_file_content(file, "").splitlines()):
for gen_mounts in [gen_vfstab_entries, gen_mnttab_entries, gen_fstab_entries, gen_aix_filesystems_entries]:
with suppress(IndexError, ValueError):
# mpypy error: misc: Incompatible types in "yield from" (actual type "object", expected type "Union[MountInfo, MountInfoOptions]
# only works if either
# * the list of functions excludes gen_aix_filesystems_entries
# * the list of functions only contains gen_aix_filesystems_entries
yield from list(gen_mounts(lines)) # type: ignore[misc]
break
def get_sources(module: AnsibleModule) -> list[str]:
"""Return a list of filenames from the requested sources."""
sources: list[str] = []
for source in module.params["sources"] or ["all"]:
if not source:
module.fail_json(msg="sources contains an empty string")
if source in {"dynamic", "all"}:
sources.extend(DYNAMIC_SOURCES)
if source in {"static", "all"}:
sources.extend(STATIC_SOURCES)
elif source not in {"static", "dynamic", "all"}:
sources.append(source)
return sources
def gen_mounts_by_source(module: AnsibleModule):
"""Iterate over the sources and yield tuples containing the source, mount point, source line(s), and the parsed result."""
sources = get_sources(module)
if len(set(sources)) < len(sources):
module.warn(f"mount_facts option 'sources' contains duplicate entries, repeat sources will be ignored: {sources}")
mount_fallback = module.params["mount_binary"] and set(sources).intersection(DYNAMIC_SOURCES)
seen = set()
for source in sources:
if source in seen or (real_source := os.path.realpath(source)) in seen:
continue
if source == "mount":
seen.add(source)
stdout = run_mount_bin(module, module.params["mount_binary"])
results = [(source, *astuple(mount_info)) for mount_info in gen_mounts_from_stdout(stdout)]
else:
seen.add(real_source)
results = [(source, *astuple(mount_info)) for mount_info in gen_mounts_by_file(source)]
if results and source in ("mount", *DYNAMIC_SOURCES):
mount_fallback = False
yield from results
if mount_fallback:
stdout = run_mount_bin(module, module.params["mount_binary"])
yield from [("mount", *astuple(mount_info)) for mount_info in gen_mounts_from_stdout(stdout)]
def get_mount_facts(module: AnsibleModule):
"""List and filter mounts, returning all mounts for each unique source."""
seconds = module.params["timeout"]
mounts = []
for source, mount, origin, fields in gen_mounts_by_source(module):
device = fields["device"]
fstype = fields["fstype"]
# Convert UUIDs in Linux /etc/fstab to device paths
# TODO need similar for OpenBSD which lists UUIDS (without the UUID= prefix) in /etc/fstab, needs another approach though.
uuid = None
if device.startswith("UUID="):
uuid = device.split("=", 1)[1]
device = get_device_by_uuid(module, uuid) or device
if not any(fnmatch(device, pattern) for pattern in module.params["devices"] or ["*"]):
continue
if not any(fnmatch(fstype, pattern) for pattern in module.params["fstypes"] or ["*"]):
continue
timed_func = _timeout.timeout(seconds, f"Timed out getting mount size for mount {mount} (type {fstype})")(get_mount_size)
if mount_size := handle_timeout(module)(timed_func)(mount):
fields.update(mount_size)
if uuid is None:
with suppress(subprocess.CalledProcessError):
uuid = get_partition_uuid(module, device)
fields.update({"ansible_context": {"source": source, "source_data": origin}, "uuid": uuid})
mounts.append(fields)
return mounts
def handle_deduplication(module, mounts):
"""Return the unique mount points from the complete list of mounts, and handle the optional aggregate results."""
mount_points = {}
mounts_by_source = {}
for mount in mounts:
mount_point = mount["mount"]
source = mount["ansible_context"]["source"]
if mount_point not in mount_points:
mount_points[mount_point] = mount
mounts_by_source.setdefault(source, []).append(mount_point)
duplicates_by_src = {src: mnts for src, mnts in mounts_by_source.items() if len(set(mnts)) != len(mnts)}
if duplicates_by_src and module.params["include_aggregate_mounts"] is None:
duplicates_by_src = {src: mnts for src, mnts in mounts_by_source.items() if len(set(mnts)) != len(mnts)}
duplicates_str = ", ".join([f"{src} ({duplicates})" for src, duplicates in duplicates_by_src.items()])
module.warn(f"mount_facts: ignoring repeat mounts in the following sources: {duplicates_str}. "
"You can disable this warning by configuring the 'include_aggregate_mounts' option as True or False.")
if module.params["include_aggregate_mounts"]:
aggregate_mounts = mounts
else:
aggregate_mounts = []
return mount_points, aggregate_mounts
def get_argument_spec():
"""Helper returning the argument spec."""
return dict(
sources=dict(type="list", elements="str", default=None),
mount_binary=dict(default="mount", type="raw"),
devices=dict(type="list", elements="str", default=None),
fstypes=dict(type="list", elements="str", default=None),
timeout=dict(type="float"),
on_timeout=dict(choices=["error", "warn", "ignore"], default="error"),
include_aggregate_mounts=dict(default=None, type="bool"),
)
def main():
module = AnsibleModule(
argument_spec=get_argument_spec(),
supports_check_mode=True,
)
if (seconds := module.params["timeout"]) is not None and seconds <= 0:
module.fail_json(msg=f"argument 'timeout' must be a positive number or null, not {seconds}")
if (mount_binary := module.params["mount_binary"]) is not None and not isinstance(mount_binary, str):
module.fail_json(msg=f"argument 'mount_binary' must be a string or null, not {mount_binary}")
mounts = get_mount_facts(module)
mount_points, aggregate_mounts = handle_deduplication(module, mounts)
module.exit_json(ansible_facts={"mount_points": mount_points, "aggregate_mounts": aggregate_mounts})
if __name__ == "__main__":
main()
| MountInfoOptions |
python | pypa__pipenv | pipenv/vendor/tomlkit/toml_file.py | {
"start": 303,
"end": 1627
} | class ____:
"""
Represents a TOML file.
:param path: path to the TOML file
"""
def __init__(self, path: _StrPath) -> None:
self._path = path
self._linesep = os.linesep
def read(self) -> TOMLDocument:
"""Read the file content as a :class:`tomlkit.toml_document.TOMLDocument`."""
with open(self._path, encoding="utf-8", newline="") as f:
content = f.read()
# check if consistent line endings
num_newline = content.count("\n")
if num_newline > 0:
num_win_eol = content.count("\r\n")
if num_win_eol == num_newline:
self._linesep = "\r\n"
elif num_win_eol == 0:
self._linesep = "\n"
else:
self._linesep = "mixed"
return loads(content)
def write(self, data: TOMLDocument) -> None:
"""Write the TOMLDocument to the file."""
content = data.as_string()
# apply linesep
if self._linesep == "\n":
content = content.replace("\r\n", "\n")
elif self._linesep == "\r\n":
content = re.sub(r"(?<!\r)\n", "\r\n", content)
with open(self._path, "w", encoding="utf-8", newline="") as f:
f.write(content)
| TOMLFile |
python | pydata__xarray | xarray/tests/test_units.py | {
"start": 187021,
"end": 190824
} | class ____(PlotTestCase):
@pytest.mark.parametrize(
"coord_unit, coord_attrs",
[
(1, {"units": "meter"}),
pytest.param(
unit_registry.m,
{},
marks=pytest.mark.xfail(reason="indexes don't support units"),
),
],
)
def test_units_in_line_plot_labels(self, coord_unit, coord_attrs):
arr = np.linspace(1, 10, 3) * unit_registry.Pa
coord_arr = np.linspace(1, 3, 3) * coord_unit
x_coord = xr.DataArray(coord_arr, dims="x", attrs=coord_attrs)
da = xr.DataArray(data=arr, dims="x", coords={"x": x_coord}, name="pressure")
da.plot.line()
ax = plt.gca()
assert ax.get_ylabel() == "pressure [pascal]"
assert ax.get_xlabel() == "x [meter]"
@pytest.mark.parametrize(
"coord_unit, coord_attrs",
[
(1, {"units": "meter"}),
pytest.param(
unit_registry.m,
{},
marks=pytest.mark.xfail(reason="indexes don't support units"),
),
],
)
def test_units_in_slice_line_plot_labels_sel(self, coord_unit, coord_attrs):
arr = xr.DataArray(
name="var_a",
data=np.array([[1, 2], [3, 4]]),
coords=dict(
a=("a", np.array([5, 6]) * coord_unit, coord_attrs),
b=("b", np.array([7, 8]) * coord_unit, coord_attrs),
),
dims=("a", "b"),
)
arr.sel(a=5).plot(marker="o") # type: ignore[call-arg]
assert plt.gca().get_title() == "a = 5 [meter]"
@pytest.mark.parametrize(
"coord_unit, coord_attrs",
[
(1, {"units": "meter"}),
pytest.param(
unit_registry.m,
{},
marks=pytest.mark.xfail(reason="pint.errors.UnitStrippedWarning"),
),
],
)
def test_units_in_slice_line_plot_labels_isel(self, coord_unit, coord_attrs):
arr = xr.DataArray(
name="var_a",
data=np.array([[1, 2], [3, 4]]),
coords=dict(
a=("x", np.array([5, 6]) * coord_unit, coord_attrs),
b=("y", np.array([7, 8])),
),
dims=("x", "y"),
)
arr.isel(x=0).plot(marker="o") # type: ignore[call-arg]
assert plt.gca().get_title() == "a = 5 [meter]"
def test_units_in_2d_plot_colorbar_label(self):
arr = np.ones((2, 3)) * unit_registry.Pa
da = xr.DataArray(data=arr, dims=["x", "y"], name="pressure")
_fig, (ax, cax) = plt.subplots(1, 2)
ax = da.plot.contourf(ax=ax, cbar_ax=cax, add_colorbar=True)
assert cax.get_ylabel() == "pressure [pascal]"
def test_units_facetgrid_plot_labels(self):
arr = np.ones((2, 3)) * unit_registry.Pa
da = xr.DataArray(data=arr, dims=["x", "y"], name="pressure")
_fig, (_ax, _cax) = plt.subplots(1, 2)
fgrid = da.plot.line(x="x", col="y")
assert fgrid.axs[0, 0].get_ylabel() == "pressure [pascal]"
def test_units_facetgrid_2d_imshow_plot_colorbar_labels(self):
arr = np.ones((2, 3, 4, 5)) * unit_registry.Pa
da = xr.DataArray(data=arr, dims=["x", "y", "z", "w"], name="pressure")
da.plot.imshow(x="x", y="y", col="w") # no colorbar to check labels of
def test_units_facetgrid_2d_contourf_plot_colorbar_labels(self):
arr = np.ones((2, 3, 4)) * unit_registry.Pa
da = xr.DataArray(data=arr, dims=["x", "y", "z"], name="pressure")
_fig, (_ax1, _ax2, _ax3, _cax) = plt.subplots(1, 4)
fgrid = da.plot.contourf(x="x", y="y", col="z")
assert fgrid.cbar.ax.get_ylabel() == "pressure [pascal]" # type: ignore[union-attr]
| TestPlots |
python | ApeWorX__ape | src/ape_node/provider.py | {
"start": 18131,
"end": 27762
} | class ____(EthereumNodeProvider, TestProviderAPI, SubprocessProvider):
_process: Optional[GethDevProcess] = None
name: str = "node"
@property
def process_name(self) -> str:
if self._process:
return self._process.process_name
elif exec_cfg := self.config.executable:
return get_node_name_from_executable(exec_cfg[0])
return "geth"
@property
def chain_id(self) -> int:
return self.settings.ethereum.local.get("chain_id", DEFAULT_TEST_CHAIN_ID)
@property
def block_time(self) -> Optional[int]:
return self.settings.ethereum.local.get("block_time")
@property
def data_dir(self) -> Path:
# Overridden from base class for placing debug logs in ape data folder.
return self.settings.data_dir or self.config_manager.DATA_FOLDER / self.name
@log_instead_of_fail(default="<node>")
def __repr__(self) -> str:
client_version = self.client_version
client_version_str = f" ({client_version}) " if client_version else " "
return f"<Node{client_version_str}chain_id={self.chain_id}>"
@property
def auto_mine(self) -> bool:
if self.process is not None:
# Geth --dev auto mines.
return True
try:
return self.make_request("eth_mining", [])
except NotImplementedError:
# Assume true; unlikely to be off. Geth --dev automines.
return True
@auto_mine.setter
def auto_mine(self, value):
raise NotImplementedError("'auto_mine' setter not implemented.")
@property
def ipc_path(self) -> Optional[Path]:
if rpc := self._configured_ipc_path:
# "ipc_path" found in config/settings
return Path(rpc)
elif rpc := self._configured_uri:
if f"{rpc}".endswith(".ipc"):
# "uri" found in config/settings and is IPC.
return Path(rpc)
elif proc := self._process:
# Connected.
return Path(proc.ipc_path)
# Default (used by geth-process).
return self.data_dir / self.process_name / f"{self.process_name}.ipc"
def connect(self):
self._set_web3()
if self.is_connected:
self._complete_connect()
elif self.allow_start:
# Starting the process.
self.start()
atexit.register(self._disconnect_atexit)
def start(self, timeout: int = 20):
geth_dev = self._create_process()
geth_dev.connect(timeout=timeout)
if not self.web3.is_connected():
geth_dev.disconnect()
raise ConnectionError(f"Unable to connect to locally running {geth_dev.process_name}.")
else:
self.web3.middleware_onion.inject(ExtraDataToPOAMiddleware, layer=0)
self._process = geth_dev
# For subprocess-provider
if self._process is not None and (process := self._process.proc):
self.stderr_queue = JoinableQueue()
self.stdout_queue = JoinableQueue()
self.process = process
# Start listening to output.
spawn(self.produce_stdout_queue)
spawn(self.produce_stderr_queue)
spawn(self.consume_stdout_queue)
spawn(self.consume_stderr_queue)
self.network_manager.running_nodes.cache_provider(self)
def _create_process(self) -> GethDevProcess:
# NOTE: Using JSON mode to ensure types can be passed as CLI args.
test_config = self.config_manager.get_config("test").model_dump(mode="json")
# Allow configuring a custom executable besides your $PATH geth.
if self.settings.executable is not None:
test_config["executable"] = self.settings.executable
test_config["ipc_path"] = self.ipc_path
# Let the provider handle disconnecting the process.
# This avoids multiple atexit handlers from being unnecessarily
# registered that do some of the same thing.
test_config["auto_disconnect"] = False
# Include extra accounts to allocated funds to at genesis.
extra_accounts = self.settings.ethereum.local.get("extra_funded_accounts", [])
extra_accounts.extend(self.provider_settings.get("extra_funded_accounts", []))
extra_accounts = list({a.lower() for a in extra_accounts})
test_config["extra_funded_accounts"] = extra_accounts
test_config["initial_balance"] = self.test_config.balance
test_config["background"] = self.background
uri = self.ws_uri or self.uri
proc_data_dir = self.data_dir / f"{self.process_name}"
return GethDevProcess.from_uri(
uri,
proc_data_dir,
block_time=self.block_time,
**test_config,
)
def disconnect(self):
# Must disconnect process first.
if self._process is not None:
self._process.disconnect()
self._process = None
# Remove self from managed-processes list.
self.network_manager.running_nodes.remove_provider(self)
# Also unset the subprocess-provider reference.
# NOTE: Type ignore is wrong; TODO: figure out why.
self.process = None # type: ignore[assignment]
# Clear any snapshots.
self.chain_manager._snapshots[self.chain_id] = []
super().disconnect()
def send_transaction(self, txn: "TransactionAPI") -> "ReceiptAPI":
return self._send_transaction_with_retries(txn)
def _send_transaction_with_retries(
self, txn: "TransactionAPI", nonce_retries: int = 0, max_nonce_retries: int = 5
) -> "ReceiptAPI":
try:
return super().send_transaction(txn)
except VirtualMachineError as err:
if (
txn.sender in self.account_manager.test_accounts
and "exceeds block gas limit" in str(err)
):
# Changed, possibly due to other transactions (x-dist?).
# Retry using block gas limit.
block_gas_limit = self.chain_manager.blocks.head.gas_limit
if txn.gas_limit > block_gas_limit:
txn.gas_limit = block_gas_limit
elif txn.gas_limit == block_gas_limit:
txn.gas_limit -= 1
else:
# Raise whatever error it is. I am not sure how this is possible!
raise
account = self.account_manager.test_accounts[txn.sender]
signed_transaction = account.sign_transaction(txn)
logger.debug("Gas-limit exceeds block gas limit. Retrying using block gas limit.")
return super().send_transaction(signed_transaction)
elif txn.sender in self.account_manager.test_accounts and re.match(
r".*Nonce '\d*' is too low.*", str(err)
):
retries = nonce_retries + 1
if retries > max_nonce_retries:
raise # This error.
# Try again with a new nonce.
account = self.account_manager.test_accounts[txn.sender]
txn.nonce = account.nonce
signed_transaction = account.sign_transaction(txn)
logger.debug("Test transaction received bad nonce. Retrying using latest nonce.")
return self._send_transaction_with_retries(
signed_transaction,
nonce_retries=retries,
max_nonce_retries=max_nonce_retries,
)
raise # Whatever error it already is (Ape-ified from ape-ethereum.provider base).
def snapshot(self) -> "SnapshotID":
return self._get_latest_block().number or 0
def restore(self, snapshot_id: "SnapshotID"):
if isinstance(snapshot_id, int):
block_number_int = snapshot_id
block_number_hex_str = str(to_hex(snapshot_id))
elif isinstance(snapshot_id, bytes):
block_number_hex_str = add_0x_prefix(to_hex(snapshot_id))
block_number_int = int(block_number_hex_str, 16)
else:
block_number_hex_str = to_hex(snapshot_id)
block_number_int = int(snapshot_id, 16)
current_block = self._get_latest_block().number or 0
if block_number_int == current_block:
# Head is already at this block.
return
elif block_number_int > current_block:
logger.error("Unable to set head to future block.")
return
self.make_request("debug_setHead", [block_number_hex_str])
@raises_not_implemented
def set_timestamp(self, new_timestamp: int):
pass
@raises_not_implemented
def mine(self, num_blocks: int = 1):
pass
def build_command(self) -> list[str]:
return self._process.command if self._process else []
def get_test_account(self, index: int) -> "TestAccountAPI":
if self._process is None:
# Not managing the process. Use default approach.
test_container = self.account_manager.test_accounts.containers["test"]
return test_container.generate_account(index)
# perf: we avoid having to generate account keys twice by utilizing
# the accounts generated for geth's genesis.json.
account = self._process._dev_accounts[index]
return self.account_manager.init_test_account(index, account.address, account.private_key)
# NOTE: The default behavior of EthereumNodeBehavior assumes geth.
| GethDev |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAlias3.py | {
"start": 445,
"end": 1043
} | class ____(Generic[T]):
def __new__(cls, value: T) -> "ClassA[T]": ...
TypeAliasA1 = ClassA[T]
a1 = ClassA(3.0)
reveal_type(a1, expected_text="ClassA[float]")
a2 = TypeAliasA1(3)
reveal_type(a2, expected_text="ClassA[Unknown]")
a3 = TypeAliasA1[int](3)
reveal_type(a3, expected_text="ClassA[int]")
TypeAliasA2 = ClassA[TStr]
# This should generate an error.
b1 = TypeAliasA2(1)
b2 = TypeAliasA2("")
reveal_type(b2, expected_text="ClassA[str]")
b3 = TypeAliasA2[float](1.0)
reveal_type(b3, expected_text="ClassA[float]")
Func = Callable[P, T]
AnyFunc = Func[P, int]
x: AnyFunc[...]
| ClassA |
python | doocs__leetcode | solution/2300-2399/2312.Selling Pieces of Wood/Solution.py | {
"start": 0,
"end": 515
} | class ____:
def sellingWood(self, m: int, n: int, prices: List[List[int]]) -> int:
@cache
def dfs(h: int, w: int) -> int:
ans = d[h].get(w, 0)
for i in range(1, h // 2 + 1):
ans = max(ans, dfs(i, w) + dfs(h - i, w))
for i in range(1, w // 2 + 1):
ans = max(ans, dfs(h, i) + dfs(h, w - i))
return ans
d = defaultdict(dict)
for h, w, p in prices:
d[h][w] = p
return dfs(m, n)
| Solution |
python | doocs__leetcode | solution/0800-0899/0871.Minimum Number of Refueling Stops/Solution.py | {
"start": 0,
"end": 527
} | class ____:
def minRefuelStops(
self, target: int, startFuel: int, stations: List[List[int]]
) -> int:
pq = []
ans = pre = 0
stations.append([target, 0])
for pos, fuel in stations:
dist = pos - pre
startFuel -= dist
while startFuel < 0 and pq:
startFuel -= heappop(pq)
ans += 1
if startFuel < 0:
return -1
heappush(pq, -fuel)
pre = pos
return ans
| Solution |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 11704,
"end": 11948
} | class ____(desc_sig_element, _sig_element=True):
"""Node for a character literal in a signature."""
classes = ['sc']
###############################################################
# new admonition-like constructs
| desc_sig_literal_char |
python | pytorch__pytorch | torch/_dynamo/variables/torch_function.py | {
"start": 11615,
"end": 19510
} | class ____(VariableTracker):
"""Fake VT to use as a dummy object, indicating the presence of torch function mode stack mutation"""
# singleton value representing the global torch function mode stack
# singleton (it exists in C++)
stack_value_singleton = object()
# offset is used to track if we have inserted/removed a
# device context which is always placed at the bottom of the stack
# if a device context is inserted, the graph will run this mutation
# so when we want to reconstruct any other modes on the stack
# their indices should be shifted right by 1 (+1)
# Conversely, if there was a device context on the stack, and the graph
# mutates the stack to remove that context (set default device to None)
# each of the indices of other modes should be shifted left by 1 (-1)
offset = 0
def __init__(
self,
source: Source,
symbolic_stack: collections.deque[TorchFunctionModeVariable],
) -> None:
self.source = source
self.symbolic_stack = symbolic_stack
@classmethod
def reset(cls) -> None:
cls.offset = 0
@classmethod
def register_mutation(cls, tx: "InstructionTranslator") -> None:
if cls.stack_value_singleton not in tx.output.side_effects:
var = cls(
source=Source(),
symbolic_stack=tx.symbolic_torch_function_state.mode_stack,
)
tx.output.side_effects.track_mutable(cls.stack_value_singleton, var)
tx.output.side_effects.mutation(var)
@classmethod
def register_device_context_insertion(cls, tx: "InstructionTranslator") -> None:
stack = tx.symbolic_torch_function_state.mode_stack
if stack and cls.is_device_context(stack[0]):
return
else:
cls.offset += 1
stack.insert(
0,
TorchFunctionModeVariable(
None, source=TorchFunctionModeStackSource(-cls.offset)
),
)
@classmethod
def clear_default_device(cls, tx: "InstructionTranslator") -> None:
stack = tx.symbolic_torch_function_state.mode_stack
if stack and cls.is_device_context(stack[0]):
stack.popleft()
cls.offset -= 1
@staticmethod
def is_device_context(var: TorchFunctionModeVariable) -> bool:
return isinstance(var.value, DeviceContext) or var.value is None
@classmethod
def get_mode_index(cls, ind: int) -> int:
return ind + cls.offset
def _get_all_args(
args: Iterable[Any], kwargs: dict[str, Any]
) -> Iterable[VariableTracker]:
return _flatten_vts(pytree.arg_tree_leaves(*args, **kwargs))
def _flatten_vts(vts: Iterable[VariableTracker]) -> list[VariableTracker]:
from collections import deque
from .dicts import ConstDictVariable
from .lists import ListVariable
vts = deque(vts)
output = []
while vts:
vt = vts.popleft()
if not vt.is_realized() and vt.peek_type() in (dict, list, tuple): # type: ignore[attr-defined]
vt.realize()
if vt.is_realized():
if isinstance(vt, ListVariable):
vts.extend(vt.items)
continue
elif isinstance(vt, ConstDictVariable):
vts.extend(vt.items.values())
continue
output.append(vt)
return output
def _get_subclass_type(var: VariableTracker) -> type:
assert isinstance(var, (TensorWithTFOverrideVariable, UserDefinedObjectVariable))
return var.python_type()
def _get_subclass_type_var(
tx: "InstructionTranslator", var: VariableTracker
) -> VariableTracker:
if isinstance(var, TensorWithTFOverrideVariable):
return var.class_type_var(tx)
elif isinstance(var, UserDefinedObjectVariable):
source = var.source and TypeSource(var.source)
return VariableTracker.build(tx, var.python_type(), source)
else:
raise AssertionError(f"Unexpected type {type(var)}")
def _is_attr_overridden(
tx: "InstructionTranslator", var: VariableTracker, name: str
) -> bool:
if not isinstance(var, (TensorWithTFOverrideVariable, UserDefinedObjectVariable)):
return False
import torch
overridden = False
try:
attr_val = inspect.getattr_static(var.python_type(), name)
overridden |= attr_val != getattr(torch.Tensor, name)
except AttributeError:
pass
return overridden
def call_torch_function(
tx: "InstructionTranslator",
torch_function_var: VariableTracker,
fn: VariableTracker,
types: TupleVariable,
args: Iterable[Any],
kwargs: dict[str, Any],
) -> Any:
# This emulates calling __torch_function__, which has a signature
# def __torch_function__(cls, func, types, args=(), kwargs=None):
#
# Also notice the `cls` is not explicitly passed in the reference
# implementations:
# 1. https://github.com/pytorch/pytorch/blob/8d81806211bc3c0ee6c2ef235017bacf1d775a85/torch/csrc/utils/python_arg_parser.cpp#L368-L374 # noqa: B950
# 2. https://github.com/pytorch/pytorch/blob/8d81806211bc3c0ee6c2ef235017bacf1d775a85/torch/overrides.py#L1741-L1743
tf_args = [
fn,
types,
VariableTracker.build(tx, tuple(args)),
VariableTracker.build(tx, kwargs),
]
return torch_function_var.call_function(tx, tf_args, {})
def get_torch_function_fn(
tx: "InstructionTranslator", vt: VariableTracker
) -> VariableTracker:
# The underlying function could be a classmethod, staticmethod, regular
# function or a function with C-implementation. It doesn't matter as long as
# they satisfy the calling convention in `call_torch_function`.
from .builtin import BuiltinVariable
args = [vt, ConstantVariable("__torch_function__")]
func_vt = BuiltinVariable(getattr).call_function(tx, args, {})
return func_vt
def can_dispatch_torch_function(
tx: "InstructionTranslator", args: Iterable[Any], kwargs: dict[str, Any]
) -> bool:
has_overridden_args = any(
has_torch_function(arg) for arg in _get_all_args(args, kwargs)
)
tf_state = tx.symbolic_torch_function_state
return (has_overridden_args and tf_state.torch_function_subclass_enabled) or (
tf_state.torch_function_mode_enabled and tf_state.in_torch_function_mode()
)
def dispatch_torch_function(
tx: "InstructionTranslator",
fn: VariableTracker,
args: Iterable[Any],
kwargs: dict[str, Any],
) -> Any:
"""Gathers all args that are TensorWithTFOverrideVariable and dispatches based on the ordering in _get_overloaded_args"""
all_args = _get_all_args(args, kwargs)
overloaded_args = _get_overloaded_args(
[arg for arg in all_args if has_torch_function(arg)],
_get_subclass_type,
)
types = TupleVariable([_get_subclass_type_var(tx, arg) for arg in overloaded_args])
if tx.symbolic_torch_function_state.in_torch_function_mode():
res = tx.symbolic_torch_function_state.call_torch_function_mode(
tx, fn, types, args, kwargs
)
if not (isinstance(res, ConstantVariable) and res.value is NotImplemented):
return res
for arg in overloaded_args:
res = arg.call_torch_function(
tx,
fn,
types,
args,
kwargs,
)
if not (isinstance(res, ConstantVariable) and res.value is NotImplemented):
return res
unimplemented(
gb_type="All __torch_function__ overrides returned NotImplemented due to TypeError from user code",
context=f"{fn=}, {args=}, {kwargs=}",
explanation=f"All __torch_function__ overrides for for function {fn} returned NotImplemented",
hints=[
*graph_break_hints.USER_ERROR,
],
)
| TorchFunctionModeStackVariable |
python | Lightning-AI__lightning | src/lightning/fabric/strategies/model_parallel.py | {
"start": 14057,
"end": 14351
} | class ____(_BackwardSyncControl):
@override
def no_backward_sync(self, module: Module, enabled: bool) -> AbstractContextManager:
"""Blocks gradient synchronization inside the FSDP2 modules."""
return _FSDPNoSync(module=module, enabled=enabled)
| _ParallelBackwardSyncControl |
python | tiangolo__fastapi | docs_src/encoder/tutorial001.py | {
"start": 177,
"end": 461
} | class ____(BaseModel):
title: str
timestamp: datetime
description: Union[str, None] = None
app = FastAPI()
@app.put("/items/{id}")
def update_item(id: str, item: Item):
json_compatible_item_data = jsonable_encoder(item)
fake_db[id] = json_compatible_item_data
| Item |
python | kamyu104__LeetCode-Solutions | Python/design-a-todo-list.py | {
"start": 2231,
"end": 3918
} | class ____(object):
def __init__(self):
self.__tasks = []
self.__user_task_ids = collections.defaultdict(SortedList)
def addTask(self, userId, taskDescription, dueDate, tags):
"""
:type userId: int
:type taskDescription: str
:type dueDate: int
:type tags: List[str]
:rtype: int
"""
self.__tasks.append([dueDate, taskDescription, set(tags)])
self.__user_task_ids[userId].add((dueDate, len(self.__tasks)))
for tag in self.__tasks[-1][-1]:
self.__user_task_ids[userId, tag].add((dueDate, len(self.__tasks)))
return len(self.__tasks)
def getAllTasks(self, userId):
"""
:type userId: int
:rtype: List[str]
"""
if userId not in self.__user_task_ids:
return []
return [self.__tasks[i-1][1] for _, i in self.__user_task_ids[userId]]
def getTasksForTag(self, userId, tag):
"""
:type userId: int
:type tag: str
:rtype: List[str]
"""
if (userId, tag) not in self.__user_task_ids:
return []
return [self.__tasks[i-1][1] for _, i in self.__user_task_ids[userId, tag]]
def completeTask(self, userId, taskId):
"""
:type userId: int
:type taskId: int
:rtype: None
"""
if not (taskId-1 < len(self.__tasks) and userId in self.__user_task_ids):
return
self.__user_task_ids[userId].discard((self.__tasks[taskId-1][0], taskId))
for tag in self.__tasks[taskId-1][-1]:
self.__user_task_ids[userId, tag].discard((self.__tasks[taskId-1][0], taskId))
| TodoList2 |
python | Textualize__textual | src/textual/widgets/_data_table.py | {
"start": 7924,
"end": 8111
} | class ____(NamedTuple):
"""Container for a row, which contains an optional label and some data cells."""
label: RenderableType | None
cells: list[RenderableType]
| RowRenderables |
python | apache__airflow | providers/google/tests/unit/google/cloud/hooks/test_workflows.py | {
"start": 1924,
"end": 10056
} | class ____:
def setup_method(self, _):
with mock.patch(BASE_PATH.format("GoogleBaseHook.__init__"), new=mock_init):
self.hook = WorkflowsHook(gcp_conn_id="test")
@mock.patch(BASE_PATH.format("WorkflowsHook.get_credentials"))
@mock.patch(BASE_PATH.format("WorkflowsClient"))
def test_get_workflows_client(self, mock_client, mock_get_credentials):
self.hook.get_workflows_client()
mock_client.assert_called_once_with(
credentials=mock_get_credentials.return_value,
client_info=CLIENT_INFO,
)
@mock.patch(BASE_PATH.format("WorkflowsHook.get_credentials"))
@mock.patch(BASE_PATH.format("ExecutionsClient"))
def test_get_executions_client(self, mock_client, mock_get_credentials):
self.hook.get_executions_client()
mock_client.assert_called_once_with(
credentials=mock_get_credentials.return_value,
client_info=CLIENT_INFO,
)
@mock.patch(BASE_PATH.format("WorkflowsHook.get_workflows_client"))
def test_create_workflow(self, mock_client):
result = self.hook.create_workflow(
workflow=WORKFLOW,
workflow_id=WORKFLOW_ID,
location=LOCATION,
project_id=PROJECT_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
assert mock_client.return_value.create_workflow.return_value == result
mock_client.return_value.create_workflow.assert_called_once_with(
request=dict(workflow=WORKFLOW, workflow_id=WORKFLOW_ID, parent=WORKFLOW_PARENT),
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
@mock.patch(BASE_PATH.format("WorkflowsHook.get_workflows_client"))
def test_get_workflow(self, mock_client):
result = self.hook.get_workflow(
workflow_id=WORKFLOW_ID,
location=LOCATION,
project_id=PROJECT_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
assert mock_client.return_value.get_workflow.return_value == result
mock_client.return_value.get_workflow.assert_called_once_with(
request=dict(name=WORKFLOW_NAME),
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
@mock.patch(BASE_PATH.format("WorkflowsHook.get_workflows_client"))
def test_update_workflow(self, mock_client):
result = self.hook.update_workflow(
workflow=WORKFLOW,
update_mask=UPDATE_MASK,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
assert mock_client.return_value.update_workflow.return_value == result
mock_client.return_value.update_workflow.assert_called_once_with(
request=dict(
workflow=WORKFLOW,
update_mask=UPDATE_MASK,
),
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
@mock.patch(BASE_PATH.format("WorkflowsHook.get_workflows_client"))
def test_delete_workflow(self, mock_client):
result = self.hook.delete_workflow(
workflow_id=WORKFLOW_ID,
location=LOCATION,
project_id=PROJECT_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
assert mock_client.return_value.delete_workflow.return_value == result
mock_client.return_value.delete_workflow.assert_called_once_with(
request=dict(name=WORKFLOW_NAME),
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
@mock.patch(BASE_PATH.format("WorkflowsHook.get_workflows_client"))
def test_list_workflows(self, mock_client):
result = self.hook.list_workflows(
location=LOCATION,
project_id=PROJECT_ID,
filter_=FILTER_,
order_by=ORDER_BY,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
assert mock_client.return_value.list_workflows.return_value == result
mock_client.return_value.list_workflows.assert_called_once_with(
request=dict(
parent=WORKFLOW_PARENT,
filter=FILTER_,
order_by=ORDER_BY,
),
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
@mock.patch(BASE_PATH.format("WorkflowsHook.get_executions_client"))
def test_create_execution(self, mock_client):
result = self.hook.create_execution(
workflow_id=WORKFLOW_ID,
location=LOCATION,
project_id=PROJECT_ID,
execution=EXECUTION,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
assert mock_client.return_value.create_execution.return_value == result
mock_client.return_value.create_execution.assert_called_once_with(
request=dict(
parent=EXECUTION_PARENT,
execution=EXECUTION,
),
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
@mock.patch(BASE_PATH.format("WorkflowsHook.get_executions_client"))
def test_create_execution_with_nested(self, mock_client):
result = self.hook.create_execution(
workflow_id=WORKFLOW_ID,
location=LOCATION,
project_id=PROJECT_ID,
execution=EXECUTION_NESTED,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
assert mock_client.return_value.create_execution.return_value == result
mock_client.return_value.create_execution.assert_called_once_with(
request=dict(
parent=EXECUTION_PARENT,
execution=EXECUTION_NESTED_OUTPUT,
),
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
@mock.patch(BASE_PATH.format("WorkflowsHook.get_executions_client"))
def test_get_execution(self, mock_client):
result = self.hook.get_execution(
workflow_id=WORKFLOW_ID,
execution_id=EXECUTION_ID,
location=LOCATION,
project_id=PROJECT_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
assert mock_client.return_value.get_execution.return_value == result
mock_client.return_value.get_execution.assert_called_once_with(
request=dict(name=EXECUTION_NAME),
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
@mock.patch(BASE_PATH.format("WorkflowsHook.get_executions_client"))
def test_cancel_execution(self, mock_client):
result = self.hook.cancel_execution(
workflow_id=WORKFLOW_ID,
execution_id=EXECUTION_ID,
location=LOCATION,
project_id=PROJECT_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
assert mock_client.return_value.cancel_execution.return_value == result
mock_client.return_value.cancel_execution.assert_called_once_with(
request=dict(name=EXECUTION_NAME),
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
@mock.patch(BASE_PATH.format("WorkflowsHook.get_executions_client"))
def test_list_execution(self, mock_client):
result = self.hook.list_executions(
workflow_id=WORKFLOW_ID,
location=LOCATION,
project_id=PROJECT_ID,
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
assert mock_client.return_value.list_executions.return_value == result
mock_client.return_value.list_executions.assert_called_once_with(
request=dict(parent=EXECUTION_PARENT),
retry=RETRY,
timeout=TIMEOUT,
metadata=METADATA,
)
| TestWorkflowsHook |
python | pypa__pipenv | pipenv/vendor/click/_termui_impl.py | {
"start": 843,
"end": 15625
} | class ____(t.Generic[V]):
def __init__(
self,
iterable: t.Optional[t.Iterable[V]],
length: t.Optional[int] = None,
fill_char: str = "#",
empty_char: str = " ",
bar_template: str = "%(bar)s",
info_sep: str = " ",
show_eta: bool = True,
show_percent: t.Optional[bool] = None,
show_pos: bool = False,
item_show_func: t.Optional[t.Callable[[t.Optional[V]], t.Optional[str]]] = None,
label: t.Optional[str] = None,
file: t.Optional[t.TextIO] = None,
color: t.Optional[bool] = None,
update_min_steps: int = 1,
width: int = 30,
) -> None:
self.fill_char = fill_char
self.empty_char = empty_char
self.bar_template = bar_template
self.info_sep = info_sep
self.show_eta = show_eta
self.show_percent = show_percent
self.show_pos = show_pos
self.item_show_func = item_show_func
self.label: str = label or ""
if file is None:
file = _default_text_stdout()
# There are no standard streams attached to write to. For example,
# pythonw on Windows.
if file is None:
file = StringIO()
self.file = file
self.color = color
self.update_min_steps = update_min_steps
self._completed_intervals = 0
self.width: int = width
self.autowidth: bool = width == 0
if length is None:
from operator import length_hint
length = length_hint(iterable, -1)
if length == -1:
length = None
if iterable is None:
if length is None:
raise TypeError("iterable or length is required")
iterable = t.cast(t.Iterable[V], range(length))
self.iter: t.Iterable[V] = iter(iterable)
self.length = length
self.pos = 0
self.avg: t.List[float] = []
self.last_eta: float
self.start: float
self.start = self.last_eta = time.time()
self.eta_known: bool = False
self.finished: bool = False
self.max_width: t.Optional[int] = None
self.entered: bool = False
self.current_item: t.Optional[V] = None
self.is_hidden: bool = not isatty(self.file)
self._last_line: t.Optional[str] = None
def __enter__(self) -> "ProgressBar[V]":
self.entered = True
self.render_progress()
return self
def __exit__(
self,
exc_type: t.Optional[t.Type[BaseException]],
exc_value: t.Optional[BaseException],
tb: t.Optional[TracebackType],
) -> None:
self.render_finish()
def __iter__(self) -> t.Iterator[V]:
if not self.entered:
raise RuntimeError("You need to use progress bars in a with block.")
self.render_progress()
return self.generator()
def __next__(self) -> V:
# Iteration is defined in terms of a generator function,
# returned by iter(self); use that to define next(). This works
# because `self.iter` is an iterable consumed by that generator,
# so it is re-entry safe. Calling `next(self.generator())`
# twice works and does "what you want".
return next(iter(self))
def render_finish(self) -> None:
if self.is_hidden:
return
self.file.write(AFTER_BAR)
self.file.flush()
@property
def pct(self) -> float:
if self.finished:
return 1.0
return min(self.pos / (float(self.length or 1) or 1), 1.0)
@property
def time_per_iteration(self) -> float:
if not self.avg:
return 0.0
return sum(self.avg) / float(len(self.avg))
@property
def eta(self) -> float:
if self.length is not None and not self.finished:
return self.time_per_iteration * (self.length - self.pos)
return 0.0
def format_eta(self) -> str:
if self.eta_known:
t = int(self.eta)
seconds = t % 60
t //= 60
minutes = t % 60
t //= 60
hours = t % 24
t //= 24
if t > 0:
return f"{t}d {hours:02}:{minutes:02}:{seconds:02}"
else:
return f"{hours:02}:{minutes:02}:{seconds:02}"
return ""
def format_pos(self) -> str:
pos = str(self.pos)
if self.length is not None:
pos += f"/{self.length}"
return pos
def format_pct(self) -> str:
return f"{int(self.pct * 100): 4}%"[1:]
def format_bar(self) -> str:
if self.length is not None:
bar_length = int(self.pct * self.width)
bar = self.fill_char * bar_length
bar += self.empty_char * (self.width - bar_length)
elif self.finished:
bar = self.fill_char * self.width
else:
chars = list(self.empty_char * (self.width or 1))
if self.time_per_iteration != 0:
chars[
int(
(math.cos(self.pos * self.time_per_iteration) / 2.0 + 0.5)
* self.width
)
] = self.fill_char
bar = "".join(chars)
return bar
def format_progress_line(self) -> str:
show_percent = self.show_percent
info_bits = []
if self.length is not None and show_percent is None:
show_percent = not self.show_pos
if self.show_pos:
info_bits.append(self.format_pos())
if show_percent:
info_bits.append(self.format_pct())
if self.show_eta and self.eta_known and not self.finished:
info_bits.append(self.format_eta())
if self.item_show_func is not None:
item_info = self.item_show_func(self.current_item)
if item_info is not None:
info_bits.append(item_info)
return (
self.bar_template
% {
"label": self.label,
"bar": self.format_bar(),
"info": self.info_sep.join(info_bits),
}
).rstrip()
def render_progress(self) -> None:
import shutil
if self.is_hidden:
# Only output the label as it changes if the output is not a
# TTY. Use file=stderr if you expect to be piping stdout.
if self._last_line != self.label:
self._last_line = self.label
echo(self.label, file=self.file, color=self.color)
return
buf = []
# Update width in case the terminal has been resized
if self.autowidth:
old_width = self.width
self.width = 0
clutter_length = term_len(self.format_progress_line())
new_width = max(0, shutil.get_terminal_size().columns - clutter_length)
if new_width < old_width:
buf.append(BEFORE_BAR)
buf.append(" " * self.max_width) # type: ignore
self.max_width = new_width
self.width = new_width
clear_width = self.width
if self.max_width is not None:
clear_width = self.max_width
buf.append(BEFORE_BAR)
line = self.format_progress_line()
line_len = term_len(line)
if self.max_width is None or self.max_width < line_len:
self.max_width = line_len
buf.append(line)
buf.append(" " * (clear_width - line_len))
line = "".join(buf)
# Render the line only if it changed.
if line != self._last_line:
self._last_line = line
echo(line, file=self.file, color=self.color, nl=False)
self.file.flush()
def make_step(self, n_steps: int) -> None:
self.pos += n_steps
if self.length is not None and self.pos >= self.length:
self.finished = True
if (time.time() - self.last_eta) < 1.0:
return
self.last_eta = time.time()
# self.avg is a rolling list of length <= 7 of steps where steps are
# defined as time elapsed divided by the total progress through
# self.length.
if self.pos:
step = (time.time() - self.start) / self.pos
else:
step = time.time() - self.start
self.avg = self.avg[-6:] + [step]
self.eta_known = self.length is not None
def update(self, n_steps: int, current_item: t.Optional[V] = None) -> None:
"""Update the progress bar by advancing a specified number of
steps, and optionally set the ``current_item`` for this new
position.
:param n_steps: Number of steps to advance.
:param current_item: Optional item to set as ``current_item``
for the updated position.
.. versionchanged:: 8.0
Added the ``current_item`` optional parameter.
.. versionchanged:: 8.0
Only render when the number of steps meets the
``update_min_steps`` threshold.
"""
if current_item is not None:
self.current_item = current_item
self._completed_intervals += n_steps
if self._completed_intervals >= self.update_min_steps:
self.make_step(self._completed_intervals)
self.render_progress()
self._completed_intervals = 0
def finish(self) -> None:
self.eta_known = False
self.current_item = None
self.finished = True
def generator(self) -> t.Iterator[V]:
"""Return a generator which yields the items added to the bar
during construction, and updates the progress bar *after* the
yielded block returns.
"""
# WARNING: the iterator interface for `ProgressBar` relies on
# this and only works because this is a simple generator which
# doesn't create or manage additional state. If this function
# changes, the impact should be evaluated both against
# `iter(bar)` and `next(bar)`. `next()` in particular may call
# `self.generator()` repeatedly, and this must remain safe in
# order for that interface to work.
if not self.entered:
raise RuntimeError("You need to use progress bars in a with block.")
if self.is_hidden:
yield from self.iter
else:
for rv in self.iter:
self.current_item = rv
# This allows show_item_func to be updated before the
# item is processed. Only trigger at the beginning of
# the update interval.
if self._completed_intervals == 0:
self.render_progress()
yield rv
self.update(1)
self.finish()
self.render_progress()
def pager(generator: t.Iterable[str], color: t.Optional[bool] = None) -> None:
"""Decide what method to use for paging through text."""
stdout = _default_text_stdout()
# There are no standard streams attached to write to. For example,
# pythonw on Windows.
if stdout is None:
stdout = StringIO()
if not isatty(sys.stdin) or not isatty(stdout):
return _nullpager(stdout, generator, color)
pager_cmd = (os.environ.get("PAGER", None) or "").strip()
if pager_cmd:
if WIN:
return _tempfilepager(generator, pager_cmd, color)
return _pipepager(generator, pager_cmd, color)
if os.environ.get("TERM") in ("dumb", "emacs"):
return _nullpager(stdout, generator, color)
if WIN or sys.platform.startswith("os2"):
return _tempfilepager(generator, "more <", color)
if hasattr(os, "system") and os.system("(less) 2>/dev/null") == 0:
return _pipepager(generator, "less", color)
import tempfile
fd, filename = tempfile.mkstemp()
os.close(fd)
try:
if hasattr(os, "system") and os.system(f'more "{filename}"') == 0:
return _pipepager(generator, "more", color)
return _nullpager(stdout, generator, color)
finally:
os.unlink(filename)
def _pipepager(generator: t.Iterable[str], cmd: str, color: t.Optional[bool]) -> None:
"""Page through text by feeding it to another program. Invoking a
pager through this might support colors.
"""
import subprocess
env = dict(os.environ)
# If we're piping to less we might support colors under the
# condition that
cmd_detail = cmd.rsplit("/", 1)[-1].split()
if color is None and cmd_detail[0] == "less":
less_flags = f"{os.environ.get('LESS', '')}{' '.join(cmd_detail[1:])}"
if not less_flags:
env["LESS"] = "-R"
color = True
elif "r" in less_flags or "R" in less_flags:
color = True
c = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, env=env)
stdin = t.cast(t.BinaryIO, c.stdin)
encoding = get_best_encoding(stdin)
try:
for text in generator:
if not color:
text = strip_ansi(text)
stdin.write(text.encode(encoding, "replace"))
except (OSError, KeyboardInterrupt):
pass
else:
stdin.close()
# Less doesn't respect ^C, but catches it for its own UI purposes (aborting
# search or other commands inside less).
#
# That means when the user hits ^C, the parent process (click) terminates,
# but less is still alive, paging the output and messing up the terminal.
#
# If the user wants to make the pager exit on ^C, they should set
# `LESS='-K'`. It's not our decision to make.
while True:
try:
c.wait()
except KeyboardInterrupt:
pass
else:
break
def _tempfilepager(
generator: t.Iterable[str], cmd: str, color: t.Optional[bool]
) -> None:
"""Page through text by invoking a program on a temporary file."""
import tempfile
fd, filename = tempfile.mkstemp()
# TODO: This never terminates if the passed generator never terminates.
text = "".join(generator)
if not color:
text = strip_ansi(text)
encoding = get_best_encoding(sys.stdout)
with open_stream(filename, "wb")[0] as f:
f.write(text.encode(encoding))
try:
os.system(f'{cmd} "{filename}"')
finally:
os.close(fd)
os.unlink(filename)
def _nullpager(
stream: t.TextIO, generator: t.Iterable[str], color: t.Optional[bool]
) -> None:
"""Simply print unformatted text. This is the ultimate fallback."""
for text in generator:
if not color:
text = strip_ansi(text)
stream.write(text)
| ProgressBar |
python | Netflix__metaflow | test/test_config/mutable_flow.py | {
"start": 6411,
"end": 8403
} | class ____(FlowSpec):
trigger_param = Parameter(
"trigger_param",
default="",
)
config = Config("config", default_value=default_config)
def _check(self, step_decorators):
for p in self.config.parameters:
assert hasattr(self, p["name"]), "Missing parameter"
assert (
os.environ.get("SHOULD_NOT_EXIST") is None
), "Unexpected environment variable"
if not step_decorators:
assert (
os.environ.get("FLOW_LEVEL")
== self.config.flow_add_environment["vars"]["FLOW_LEVEL"]
), "Flow level environment variable not set"
self.flow_level = os.environ.get("FLOW_LEVEL")
if step_decorators:
assert (
os.environ.get("STEP_LEVEL")
== self.config.step_add_environment.vars.STEP_LEVEL
), "Missing step_level decorator"
assert (
os.environ.get("STEP_LEVEL_2")
== self.config["step_add_environment_2"]["vars"].STEP_LEVEL_2
), "Missing step_level_2 decorator"
self.step_level = os.environ.get("STEP_LEVEL")
self.step_level_2 = os.environ.get("STEP_LEVEL_2")
else:
assert (
os.environ.get("STEP_LEVEL") is None
), "Step level environment variable set"
assert (
os.environ.get("STEP_LEVEL_2") is None
), "Step level 2 environment variable set"
@ModifyStep2
@ModifyStep
@environment(vars={"SHOULD_NOT_EXIST": "1"})
@step
def start(self):
print("Starting start step...")
self._check(step_decorators=True)
print("All checks are good.")
self.next(self.end)
@step
def end(self):
print("Starting end step...")
self._check(step_decorators=False)
print("All checks are good.")
if __name__ == "__main__":
ConfigMutableFlow()
| ConfigMutableFlow |
python | langchain-ai__langchain | libs/langchain/tests/unit_tests/chains/test_base.py | {
"start": 496,
"end": 1048
} | class ____(BaseMemory):
"""Fake memory class for testing purposes."""
@property
def memory_variables(self) -> list[str]:
"""Return baz variable."""
return ["baz"]
@override
def load_memory_variables(
self,
inputs: dict[str, Any] | None = None,
) -> dict[str, str]:
"""Return baz variable."""
return {"baz": "foo"}
def save_context(self, inputs: dict[str, Any], outputs: dict[str, str]) -> None:
"""Pass."""
def clear(self) -> None:
"""Pass."""
| FakeMemory |
python | python-visualization__folium | folium/features.py | {
"start": 7030,
"end": 14959
} | class ____(MacroElement):
"""
Creates a Vega-Lite chart element.
Parameters
----------
data: JSON-like str or object
The Vega-Lite description of the chart.
It can also be any object that has a method `to_json`,
so that you can (for instance) provide an `Altair` chart.
width: int or str, default None
The width of the output element.
If None, either data['width'] (if available) or '100%' will be used.
Ex: 120, '120px', '80%'
height: int or str, default None
The height of the output element.
If None, either data['width'] (if available) or '100%' will be used.
Ex: 120, '120px', '80%'
left: int or str, default '0%'
The horizontal distance of the output with respect to the parent
HTML object. Ex: 120, '120px', '80%'
top: int or str, default '0%'
The vertical distance of the output with respect to the parent
HTML object. Ex: 120, '120px', '80%'
position: str, default 'relative'
The `position` argument that the CSS shall contain.
Ex: 'relative', 'absolute'
"""
_template = Template("")
def __init__(
self,
data: Any,
width: Union[int, str, None] = None,
height: Union[int, str, None] = None,
left: Union[int, str] = "0%",
top: Union[int, str] = "0%",
position: str = "relative",
):
super(self.__class__, self).__init__()
self._name = "VegaLite"
self.data = data.to_json() if hasattr(data, "to_json") else data
if isinstance(self.data, str):
self.data = json.loads(self.data)
self.json = json.dumps(self.data)
# Size Parameters.
self.width = _parse_size(
self.data.get("width", "100%") if width is None else width
)
self.height = _parse_size(
self.data.get("height", "100%") if height is None else height
)
self.left = _parse_size(left)
self.top = _parse_size(top)
self.position = position
def render(self, **kwargs):
"""Renders the HTML representation of the element."""
parent = self._parent
if not isinstance(parent, (Figure, Div, Popup)):
raise TypeError(
"VegaLite elements can only be added to a Figure, Div, or Popup"
)
parent.html.add_child(
Element(
Template(
"""
<div id="{{this.get_name()}}"></div>
"""
).render(this=self, kwargs=kwargs)
),
name=self.get_name(),
)
figure = self.get_root()
assert isinstance(
figure, Figure
), "You cannot render this Element if it is not in a Figure."
figure.header.add_child(
Element(
Template(
"""
<style> #{{this.get_name()}} {
position : {{this.position}};
width : {{this.width[0]}}{{this.width[1]}};
height: {{this.height[0]}}{{this.height[1]}};
left: {{this.left[0]}}{{this.left[1]}};
top: {{this.top[0]}}{{this.top[1]}};
</style>
"""
).render(this=self, **kwargs)
),
name=self.get_name(),
)
embed_mapping = {
1: self._embed_vegalite_v1,
2: self._embed_vegalite_v2,
3: self._embed_vegalite_v3,
4: self._embed_vegalite_v4,
5: self._embed_vegalite_v5,
}
# Version 2 is assumed as the default, if no version is given in the schema.
embed_vegalite = embed_mapping.get(
self.vegalite_major_version, self._embed_vegalite_v2
)
embed_vegalite(figure=figure, parent=parent)
@property
def vegalite_major_version(self) -> Optional[int]:
if "$schema" not in self.data:
return None
schema = self.data["$schema"]
return int(schema.split("/")[-1].split(".")[0].lstrip("v"))
def _embed_vegalite_v5(self, figure: Figure, parent: TypeContainer) -> None:
self._vega_embed(parent=parent)
figure.header.add_child(
JavascriptLink("https://cdn.jsdelivr.net/npm//vega@5"), name="vega"
)
figure.header.add_child(
JavascriptLink("https://cdn.jsdelivr.net/npm/vega-lite@5"), name="vega-lite"
)
figure.header.add_child(
JavascriptLink("https://cdn.jsdelivr.net/npm/vega-embed@6"),
name="vega-embed",
)
def _embed_vegalite_v4(self, figure: Figure, parent: TypeContainer) -> None:
self._vega_embed(parent=parent)
figure.header.add_child(
JavascriptLink("https://cdn.jsdelivr.net/npm//vega@5"), name="vega"
)
figure.header.add_child(
JavascriptLink("https://cdn.jsdelivr.net/npm/vega-lite@4"), name="vega-lite"
)
figure.header.add_child(
JavascriptLink("https://cdn.jsdelivr.net/npm/vega-embed@6"),
name="vega-embed",
)
def _embed_vegalite_v3(self, figure: Figure, parent: TypeContainer) -> None:
self._vega_embed(parent=parent)
figure.header.add_child(
JavascriptLink("https://cdn.jsdelivr.net/npm/vega@4"), name="vega"
)
figure.header.add_child(
JavascriptLink("https://cdn.jsdelivr.net/npm/vega-lite@3"), name="vega-lite"
)
figure.header.add_child(
JavascriptLink("https://cdn.jsdelivr.net/npm/vega-embed@3"),
name="vega-embed",
)
def _embed_vegalite_v2(self, figure: Figure, parent: TypeContainer) -> None:
self._vega_embed(parent=parent)
figure.header.add_child(
JavascriptLink("https://cdn.jsdelivr.net/npm/vega@3"), name="vega"
)
figure.header.add_child(
JavascriptLink("https://cdn.jsdelivr.net/npm/vega-lite@2"), name="vega-lite"
)
figure.header.add_child(
JavascriptLink("https://cdn.jsdelivr.net/npm/vega-embed@3"),
name="vega-embed",
)
def _vega_embed(self, parent: TypeContainer) -> None:
parent.script.add_child(
Element(
Template(
"""
vegaEmbed({{this.get_name()}}, {{this.json}})
.then(function(result) {})
.catch(console.error);
"""
).render(this=self)
),
name=self.get_name(),
)
def _embed_vegalite_v1(self, figure: Figure, parent: TypeContainer) -> None:
parent.script.add_child(
Element(
Template(
"""
var embedSpec = {
mode: "vega-lite",
spec: {{this.json}}
};
vg.embed(
{{this.get_name()}}, embedSpec, function(error, result) {}
);
"""
).render(this=self)
),
name=self.get_name(),
)
figure.header.add_child(
JavascriptLink("https://d3js.org/d3.v3.min.js"), name="d3"
)
figure.header.add_child(
JavascriptLink("https://cdnjs.cloudflare.com/ajax/libs/vega/2.6.5/vega.js"),
name="vega",
)
figure.header.add_child(
JavascriptLink(
"https://cdnjs.cloudflare.com/ajax/libs/vega-lite/1.3.1/vega-lite.js"
),
name="vega-lite",
)
figure.header.add_child(
JavascriptLink(
"https://cdnjs.cloudflare.com/ajax/libs/vega-embed/2.2.0/vega-embed.js"
),
name="vega-embed",
)
| VegaLite |
python | joke2k__faker | faker/providers/currency/fr_CA/__init__.py | {
"start": 46,
"end": 279
} | class ____(CurrencyProvider):
price_formats = ["#,##", "%#,##", "%##,##", "%.###,##", "%#.###,##"]
def pricetag(self) -> str:
return self.numerify(self.random_element(self.price_formats)) + "\N{NO-BREAK SPACE}$"
| Provider |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vectorizers.py | {
"start": 2292,
"end": 5832
} | class ____(str, Enum):
"""The available vectorization modules in Weaviate.
These modules encode binary data into lists of floats called vectors.
See the [docs](https://weaviate.io/developers/weaviate/modules/retriever-vectorizer-modules) for more details.
Attributes:
NONE: No vectorizer.
TEXT2VEC_AWS: Weaviate module backed by AWS text-based embedding models.
TEXT2VEC_COHERE: Weaviate module backed by Cohere text-based embedding models.
TEXT2VEC_CONTEXTIONARY: Weaviate module backed by Contextionary text-based embedding models.
TEXT2VEC_GPT4ALL: Weaviate module backed by GPT-4-All text-based embedding models.
TEXT2VEC_HUGGINGFACE: Weaviate module backed by HuggingFace text-based embedding models.
TEXT2VEC_OPENAI: Weaviate module backed by OpenAI and Azure-OpenAI text-based embedding models.
TEXT2VEC_PALM: Weaviate module backed by PaLM text-based embedding models.
TEXT2VEC_TRANSFORMERS: Weaviate module backed by Transformers text-based embedding models.
TEXT2VEC_JINAAI: Weaviate module backed by Jina AI text-based embedding models.
TEXT2VEC_VOYAGEAI: Weaviate module backed by Voyage AI text-based embedding models.
TEXT2VEC_NVIDIA: Weaviate module backed by NVIDIA text-based embedding models.
TEXT2VEC_WEAVIATE: Weaviate module backed by Weaviate's self-hosted text-based embedding models.
IMG2VEC_NEURAL: Weaviate module backed by a ResNet-50 neural network for images.
MULTI2VEC_CLIP: Weaviate module backed by a Sentence-BERT CLIP model for images and text.
MULTI2VEC_PALM: Weaviate module backed by a palm model for images and text.
MULTI2VEC_BIND: Weaviate module backed by the ImageBind model for images, text, audio, depth, IMU, thermal, and video.
MULTI2VEC_VOYAGEAI: Weaviate module backed by a Voyage AI multimodal embedding models.
MULTI2VEC_NVIDIA: Weaviate module backed by NVIDIA multimodal embedding models.
REF2VEC_CENTROID: Weaviate module backed by a centroid-based model that calculates an object's vectors from its referenced vectors.
"""
NONE = "none"
TEXT2COLBERT_JINAAI = "text2colbert-jinaai"
TEXT2VEC_AWS = "text2vec-aws"
TEXT2VEC_COHERE = "text2vec-cohere"
TEXT2VEC_CONTEXTIONARY = "text2vec-contextionary"
TEXT2VEC_DATABRICKS = "text2vec-databricks"
TEXT2VEC_GPT4ALL = "text2vec-gpt4all"
TEXT2VEC_HUGGINGFACE = "text2vec-huggingface"
TEXT2VEC_MISTRAL = "text2vec-mistral"
TEXT2VEC_MORPH = "text2vec-morph"
TEXT2VEC_MODEL2VEC = "text2vec-model2vec"
TEXT2VEC_NVIDIA = "text2vec-nvidia"
TEXT2VEC_OLLAMA = "text2vec-ollama"
TEXT2VEC_OPENAI = "text2vec-openai"
TEXT2VEC_PALM = "text2vec-palm" # change to google once 1.27 is the lowest supported version
TEXT2VEC_TRANSFORMERS = "text2vec-transformers"
TEXT2VEC_JINAAI = "text2vec-jinaai"
TEXT2VEC_VOYAGEAI = "text2vec-voyageai"
TEXT2VEC_WEAVIATE = "text2vec-weaviate"
IMG2VEC_NEURAL = "img2vec-neural"
MULTI2VEC_AWS = "multi2vec-aws"
MULTI2VEC_CLIP = "multi2vec-clip"
MULTI2VEC_COHERE = "multi2vec-cohere"
MULTI2VEC_JINAAI = "multi2vec-jinaai"
MULTI2MULTI_JINAAI = "multi2multivec-jinaai"
MULTI2VEC_BIND = "multi2vec-bind"
MULTI2VEC_PALM = "multi2vec-palm" # change to google once 1.27 is the lowest supported version
MULTI2VEC_VOYAGEAI = "multi2vec-voyageai"
MULTI2VEC_NVIDIA = "multi2vec-nvidia"
REF2VEC_CENTROID = "ref2vec-centroid"
| Vectorizers |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1485031,
"end": 1486458
} | class ____(sgqlc.types.Type, Node):
"""An event related to sponsorship activity."""
__schema__ = github_schema
__field_names__ = ("action", "previous_sponsors_tier", "sponsor", "sponsorable", "sponsors_tier", "timestamp", "via_bulk_sponsorship")
action = sgqlc.types.Field(sgqlc.types.non_null(SponsorsActivityAction), graphql_name="action")
"""What action this activity indicates took place."""
previous_sponsors_tier = sgqlc.types.Field("SponsorsTier", graphql_name="previousSponsorsTier")
"""The tier that the sponsorship used to use, for tier change events."""
sponsor = sgqlc.types.Field("Sponsor", graphql_name="sponsor")
"""The user or organization who triggered this activity and was/is
sponsoring the sponsorable.
"""
sponsorable = sgqlc.types.Field(sgqlc.types.non_null(Sponsorable), graphql_name="sponsorable")
"""The user or organization that is being sponsored, the maintainer."""
sponsors_tier = sgqlc.types.Field("SponsorsTier", graphql_name="sponsorsTier")
"""The associated sponsorship tier."""
timestamp = sgqlc.types.Field(DateTime, graphql_name="timestamp")
"""The timestamp of this event."""
via_bulk_sponsorship = sgqlc.types.Field(sgqlc.types.non_null(Boolean), graphql_name="viaBulkSponsorship")
"""Was this sponsorship made alongside other sponsorships at the same
time from the same sponsor?
"""
| SponsorsActivity |
python | HypothesisWorks__hypothesis | hypothesis-python/examples/example_hypothesis_entrypoint/example_hypothesis_entrypoint.py | {
"start": 624,
"end": 928
} | class ____:
def __init__(self, x: int):
assert x >= 0, f"got {x}, but only positive numbers are allowed"
self.x = x
def _hypothesis_setup_hook():
import hypothesis.strategies as st
st.register_type_strategy(MyCustomType, st.integers(min_value=0).map(MyCustomType))
| MyCustomType |
python | pandas-dev__pandas | pandas/tests/indexes/numeric/test_indexing.py | {
"start": 22662,
"end": 23259
} | class ____:
@pytest.mark.parametrize("side, expected", [("left", 4), ("right", 5)])
def test_get_slice_bounds_within(self, side, expected):
index = Index(range(6))
result = index.get_slice_bound(4, side=side)
assert result == expected
@pytest.mark.parametrize("side", ["left", "right"])
@pytest.mark.parametrize("bound, expected", [(-1, 0), (10, 6)])
def test_get_slice_bounds_outside(self, side, expected, bound):
index = Index(range(6))
result = index.get_slice_bound(bound, side=side)
assert result == expected
| TestGetSliceBounds |
python | coleifer__peewee | tests/manytomany.py | {
"start": 21131,
"end": 21232
} | class ____(TestModel):
name = TextField()
DeniedThroughDeferred = DeferredThroughModel()
| Permission |
python | django__django | django/contrib/syndication/apps.py | {
"start": 91,
"end": 203
} | class ____(AppConfig):
name = "django.contrib.syndication"
verbose_name = _("Syndication")
| SyndicationConfig |
python | scipy__scipy | scipy/stats/_distribution_infrastructure.py | {
"start": 12230,
"end": 20310
} | class ____(_Domain):
r""" Representation of an interval defined by two endpoints.
Each endpoint may be a finite scalar, positive or negative infinity, or
be given by a single parameter. The domain may include the endpoints or
not.
This class still does not provide an implementation of the __str__ method,
so it is meant for subclassing (e.g. a subclass for domains on the real
line).
Attributes
----------
symbols : dict
Inherited. A map from special values to symbols for use in `__str__`.
endpoints : 2-tuple of float(s) and/or str(s) and/or callable(s).
A tuple with two values. Each may be either a float (the numerical
value of the endpoints of the domain), a string (the name of the
parameters that will define the endpoint), or a callable taking the
parameters used to define the endpoints of the domain as keyword only
arguments and returning a numerical value for the endpoint.
inclusive : 2-tuple of bools
A tuple with two boolean values; each indicates whether the
corresponding endpoint is included within the domain or not.
Methods
-------
define_parameters(*parameters)
Records any parameters used to define the endpoints of the domain
get_numerical_endpoints(parameter_values)
Gets the numerical values of the domain endpoints, which may have been
defined symbolically or through a callable.
contains(item, parameter_values)
Determines whether the argument is contained within the domain
draw(size, rng, proportions, parameter_values)
Draws random values based on the domain.
"""
def __init__(self, endpoints=(-inf, inf), inclusive=(False, False)):
self.symbols = super().symbols.copy()
a, b = endpoints
self.endpoints = np.asarray(a)[()], np.asarray(b)[()]
self.inclusive = inclusive
def define_parameters(self, *parameters):
r""" Records any parameters used to define the endpoints of the domain.
Adds the keyword name of each parameter and its text representation
to the `symbols` attribute as key:value pairs.
For instance, a parameter may be passed into to a distribution's
initializer using the keyword `log_a`, and the corresponding
string representation may be '\log(a)'. To form the text
representation of the domain for use in documentation, the
_Domain object needs to map from the keyword name used in the code
to the string representation.
Returns None, but updates the `symbols` attribute.
Parameters
----------
*parameters : _Parameter objects
Parameters that may define the endpoints of the domain.
"""
new_symbols = {param.name: param.symbol for param in parameters}
self.symbols.update(new_symbols)
def get_numerical_endpoints(self, parameter_values):
r""" Get the numerical values of the domain endpoints.
Domain endpoints may be defined symbolically or through a callable.
This returns numerical values of the endpoints given numerical values for
any variables.
Parameters
----------
parameter_values : dict
A dictionary that maps between string variable names and numerical
values of parameters, which may define the endpoints.
Returns
-------
a, b : ndarray
Numerical values of the endpoints
"""
a, b = self.endpoints
# If `a` (`b`) is a string - the name of the parameter that defines
# the endpoint of the domain - then corresponding numerical values
# will be found in the `parameter_values` dictionary.
# If a callable, it will be executed with `parameter_values` passed as
# keyword arguments, and it will return the numerical values.
# Otherwise, it is itself the array of numerical values of the endpoint.
try:
if callable(a):
a = a(**parameter_values)
else:
a = np.asarray(parameter_values.get(a, a))
if callable(b):
b = b(**parameter_values)
else:
b = np.asarray(parameter_values.get(b, b))
except TypeError as e:
message = ("The endpoints of the distribution are defined by "
"parameters, but their values were not provided. When "
f"using a private method of {self.__class__}, pass "
"all required distribution parameters as keyword "
"arguments.")
raise TypeError(message) from e
# Floating point types are used for even integer parameters.
# Convert to float here to ensure consistency throughout framework.
a, b = xp_promote(a, b, force_floating=True, xp=np)
return a, b
def contains(self, item, parameter_values=None):
r"""Determine whether the argument is contained within the domain.
Parameters
----------
item : ndarray
The argument
parameter_values : dict
A dictionary that maps between string variable names and numerical
values of parameters, which may define the endpoints.
Returns
-------
out : bool
True if `item` is within the domain; False otherwise.
"""
parameter_values = parameter_values or {}
# if self.all_inclusive:
# # Returning a 0d value here makes things much faster.
# # I'm not sure if it's safe, though. If it causes a bug someday,
# # I guess it wasn't.
# # Even if there is no bug because of the shape, it is incorrect for
# # `contains` to return True when there are invalid (e.g. NaN)
# # parameters.
# return np.asarray(True)
a, b = self.get_numerical_endpoints(parameter_values)
left_inclusive, right_inclusive = self.inclusive
in_left = item >= a if left_inclusive else item > a
in_right = item <= b if right_inclusive else item < b
return in_left & in_right
def draw(self, n, type_, min, max, squeezed_base_shape, rng=None):
r""" Draw random values from the domain.
Parameters
----------
n : int
The number of values to be drawn from the domain.
type_ : str
A string indicating whether the values are
- strictly within the domain ('in'),
- at one of the two endpoints ('on'),
- strictly outside the domain ('out'), or
- NaN ('nan').
min, max : ndarray
The endpoints of the domain.
squeezed_based_shape : tuple of ints
See _RealParameter.draw.
rng : np.Generator
The Generator used for drawing random values.
"""
rng = np.random.default_rng(rng)
def ints(*args, **kwargs): return rng.integers(*args, **kwargs, endpoint=True)
uniform = rng.uniform if isinstance(self, _RealInterval) else ints
# get copies of min and max with no nans so that uniform doesn't fail
min_nn, max_nn = min.copy(), max.copy()
i = np.isnan(min_nn) | np.isnan(max_nn)
min_nn[i] = 0
max_nn[i] = 1
shape = (n,) + squeezed_base_shape
if type_ == 'in':
z = uniform(min_nn, max_nn, size=shape)
elif type_ == 'on':
z_on_shape = shape
z = np.ones(z_on_shape)
i = rng.random(size=n) < 0.5
z[i] = min
z[~i] = max
elif type_ == 'out':
z = min_nn - uniform(1, 5, size=shape) # 1, 5 is arbitary; we just want
zr = max_nn + uniform(1, 5, size=shape) # some numbers outside domain
i = rng.random(size=n) < 0.5
z[i] = zr[i]
elif type_ == 'nan':
z = np.full(shape, np.nan)
return z
| _Interval |
python | palantir__python-language-server | versioneer.py | {
"start": 52511,
"end": 68611
} | class ____(Exception):
"""The project root directory is unknown or missing key files."""
def get_versions(verbose=False):
"""Get the project version from whatever source is available.
Returns dict with two keys: 'version' and 'full'.
"""
if "versioneer" in sys.modules:
# see the discussion in cmdclass.py:get_cmdclass()
del sys.modules["versioneer"]
root = get_root()
cfg = get_config_from_root(root)
assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg"
handlers = HANDLERS.get(cfg.VCS)
assert handlers, "unrecognized VCS '%s'" % cfg.VCS
verbose = verbose or cfg.verbose
assert cfg.versionfile_source is not None, \
"please set versioneer.versionfile_source"
assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix"
versionfile_abs = os.path.join(root, cfg.versionfile_source)
# extract version from first of: _version.py, VCS command (e.g. 'git
# describe'), parentdir. This is meant to work for developers using a
# source checkout, for users of a tarball created by 'setup.py sdist',
# and for users of a tarball/zipball created by 'git archive' or github's
# download-from-tag feature or the equivalent in other VCSes.
get_keywords_f = handlers.get("get_keywords")
from_keywords_f = handlers.get("keywords")
if get_keywords_f and from_keywords_f:
try:
keywords = get_keywords_f(versionfile_abs)
ver = from_keywords_f(keywords, cfg.tag_prefix, verbose)
if verbose:
print("got version from expanded keyword %s" % ver)
return ver
except NotThisMethod:
pass
try:
ver = versions_from_file(versionfile_abs)
if verbose:
print("got version from file %s %s" % (versionfile_abs, ver))
return ver
except NotThisMethod:
pass
from_vcs_f = handlers.get("pieces_from_vcs")
if from_vcs_f:
try:
pieces = from_vcs_f(cfg.tag_prefix, root, verbose)
ver = render(pieces, cfg.style)
if verbose:
print("got version from VCS %s" % ver)
return ver
except NotThisMethod:
pass
try:
if cfg.parentdir_prefix:
ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose)
if verbose:
print("got version from parentdir %s" % ver)
return ver
except NotThisMethod:
pass
if verbose:
print("unable to compute version")
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None, "error": "unable to compute version",
"date": None}
def get_version():
"""Get the short version string for this project."""
return get_versions()["version"]
def get_cmdclass():
"""Get the custom setuptools/distutils subclasses used by Versioneer."""
if "versioneer" in sys.modules:
del sys.modules["versioneer"]
# this fixes the "python setup.py develop" case (also 'install' and
# 'easy_install .'), in which subdependencies of the main project are
# built (using setup.py bdist_egg) in the same python process. Assume
# a main project A and a dependency B, which use different versions
# of Versioneer. A's setup.py imports A's Versioneer, leaving it in
# sys.modules by the time B's setup.py is executed, causing B to run
# with the wrong versioneer. Setuptools wraps the sub-dep builds in a
# sandbox that restores sys.modules to it's pre-build state, so the
# parent is protected against the child's "import versioneer". By
# removing ourselves from sys.modules here, before the child build
# happens, we protect the child from the parent's versioneer too.
# Also see https://github.com/warner/python-versioneer/issues/52
cmds = {}
# we add "version" to both distutils and setuptools
from distutils.core import Command
class cmd_version(Command):
description = "report generated version string"
user_options = []
boolean_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
vers = get_versions(verbose=True)
print("Version: %s" % vers["version"])
print(" full-revisionid: %s" % vers.get("full-revisionid"))
print(" dirty: %s" % vers.get("dirty"))
print(" date: %s" % vers.get("date"))
if vers["error"]:
print(" error: %s" % vers["error"])
cmds["version"] = cmd_version
# we override "build_py" in both distutils and setuptools
#
# most invocation pathways end up running build_py:
# distutils/build -> build_py
# distutils/install -> distutils/build ->..
# setuptools/bdist_wheel -> distutils/install ->..
# setuptools/bdist_egg -> distutils/install_lib -> build_py
# setuptools/install -> bdist_egg ->..
# setuptools/develop -> ?
# pip install:
# copies source tree to a tempdir before running egg_info/etc
# if .git isn't copied too, 'git describe' will fail
# then does setup.py bdist_wheel, or sometimes setup.py install
# setup.py egg_info -> ?
# we override different "build_py" commands for both environments
if "setuptools" in sys.modules:
from setuptools.command.build_py import build_py as _build_py
else:
from distutils.command.build_py import build_py as _build_py
class cmd_build_py(_build_py):
def run(self):
root = get_root()
cfg = get_config_from_root(root)
versions = get_versions()
_build_py.run(self)
# now locate _version.py in the new build/ directory and replace
# it with an updated value
if cfg.versionfile_build:
target_versionfile = os.path.join(self.build_lib,
cfg.versionfile_build)
print("UPDATING %s" % target_versionfile)
write_to_version_file(target_versionfile, versions)
cmds["build_py"] = cmd_build_py
if "cx_Freeze" in sys.modules: # cx_freeze enabled?
from cx_Freeze.dist import build_exe as _build_exe
# nczeczulin reports that py2exe won't like the pep440-style string
# as FILEVERSION, but it can be used for PRODUCTVERSION, e.g.
# setup(console=[{
# "version": versioneer.get_version().split("+", 1)[0], # FILEVERSION
# "product_version": versioneer.get_version(),
# ...
class cmd_build_exe(_build_exe):
def run(self):
root = get_root()
cfg = get_config_from_root(root)
versions = get_versions()
target_versionfile = cfg.versionfile_source
print("UPDATING %s" % target_versionfile)
write_to_version_file(target_versionfile, versions)
_build_exe.run(self)
os.unlink(target_versionfile)
with open(cfg.versionfile_source, "w") as f:
LONG = LONG_VERSION_PY[cfg.VCS]
f.write(LONG %
{"DOLLAR": "$",
"STYLE": cfg.style,
"TAG_PREFIX": cfg.tag_prefix,
"PARENTDIR_PREFIX": cfg.parentdir_prefix,
"VERSIONFILE_SOURCE": cfg.versionfile_source,
})
cmds["build_exe"] = cmd_build_exe
del cmds["build_py"]
if 'py2exe' in sys.modules: # py2exe enabled?
try:
from py2exe.distutils_buildexe import py2exe as _py2exe # py3
except ImportError:
from py2exe.build_exe import py2exe as _py2exe # py2
class cmd_py2exe(_py2exe):
def run(self):
root = get_root()
cfg = get_config_from_root(root)
versions = get_versions()
target_versionfile = cfg.versionfile_source
print("UPDATING %s" % target_versionfile)
write_to_version_file(target_versionfile, versions)
_py2exe.run(self)
os.unlink(target_versionfile)
with open(cfg.versionfile_source, "w") as f:
LONG = LONG_VERSION_PY[cfg.VCS]
f.write(LONG %
{"DOLLAR": "$",
"STYLE": cfg.style,
"TAG_PREFIX": cfg.tag_prefix,
"PARENTDIR_PREFIX": cfg.parentdir_prefix,
"VERSIONFILE_SOURCE": cfg.versionfile_source,
})
cmds["py2exe"] = cmd_py2exe
# we override different "sdist" commands for both environments
if "setuptools" in sys.modules:
from setuptools.command.sdist import sdist as _sdist
else:
from distutils.command.sdist import sdist as _sdist
class cmd_sdist(_sdist):
def run(self):
versions = get_versions()
self._versioneer_generated_versions = versions
# unless we update this, the command will keep using the old
# version
self.distribution.metadata.version = versions["version"]
return _sdist.run(self)
def make_release_tree(self, base_dir, files):
root = get_root()
cfg = get_config_from_root(root)
_sdist.make_release_tree(self, base_dir, files)
# now locate _version.py in the new base_dir directory
# (remembering that it may be a hardlink) and replace it with an
# updated value
target_versionfile = os.path.join(base_dir, cfg.versionfile_source)
print("UPDATING %s" % target_versionfile)
write_to_version_file(target_versionfile,
self._versioneer_generated_versions)
cmds["sdist"] = cmd_sdist
return cmds
CONFIG_ERROR = """
setup.cfg is missing the necessary Versioneer configuration. You need
a section like:
[versioneer]
VCS = git
style = pep440
versionfile_source = src/myproject/_version.py
versionfile_build = myproject/_version.py
tag_prefix =
parentdir_prefix = myproject-
You will also need to edit your setup.py to use the results:
import versioneer
setup(version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(), ...)
Please read the docstring in ./versioneer.py for configuration instructions,
edit setup.cfg, and re-run the installer or 'python versioneer.py setup'.
"""
SAMPLE_CONFIG = """
# See the docstring in versioneer.py for instructions. Note that you must
# re-run 'versioneer.py setup' after changing this section, and commit the
# resulting files.
[versioneer]
#VCS = git
#style = pep440
#versionfile_source =
#versionfile_build =
#tag_prefix =
#parentdir_prefix =
"""
INIT_PY_SNIPPET = """
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
"""
def do_setup():
"""Main VCS-independent setup function for installing Versioneer."""
root = get_root()
try:
cfg = get_config_from_root(root)
except (EnvironmentError, configparser.NoSectionError,
configparser.NoOptionError) as e:
if isinstance(e, (EnvironmentError, configparser.NoSectionError)):
print("Adding sample versioneer config to setup.cfg",
file=sys.stderr)
with open(os.path.join(root, "setup.cfg"), "a") as f:
f.write(SAMPLE_CONFIG)
print(CONFIG_ERROR, file=sys.stderr)
return 1
print(" creating %s" % cfg.versionfile_source)
with open(cfg.versionfile_source, "w") as f:
LONG = LONG_VERSION_PY[cfg.VCS]
f.write(LONG % {"DOLLAR": "$",
"STYLE": cfg.style,
"TAG_PREFIX": cfg.tag_prefix,
"PARENTDIR_PREFIX": cfg.parentdir_prefix,
"VERSIONFILE_SOURCE": cfg.versionfile_source,
})
ipy = os.path.join(os.path.dirname(cfg.versionfile_source),
"__init__.py")
if os.path.exists(ipy):
try:
with open(ipy, "r") as f:
old = f.read()
except EnvironmentError:
old = ""
if INIT_PY_SNIPPET not in old:
print(" appending to %s" % ipy)
with open(ipy, "a") as f:
f.write(INIT_PY_SNIPPET)
else:
print(" %s unmodified" % ipy)
else:
print(" %s doesn't exist, ok" % ipy)
ipy = None
# Make sure both the top-level "versioneer.py" and versionfile_source
# (PKG/_version.py, used by runtime code) are in MANIFEST.in, so
# they'll be copied into source distributions. Pip won't be able to
# install the package without this.
manifest_in = os.path.join(root, "MANIFEST.in")
simple_includes = set()
try:
with open(manifest_in, "r") as f:
for line in f:
if line.startswith("include "):
for include in line.split()[1:]:
simple_includes.add(include)
except EnvironmentError:
pass
# That doesn't cover everything MANIFEST.in can do
# (http://docs.python.org/2/distutils/sourcedist.html#commands), so
# it might give some false negatives. Appending redundant 'include'
# lines is safe, though.
if "versioneer.py" not in simple_includes:
print(" appending 'versioneer.py' to MANIFEST.in")
with open(manifest_in, "a") as f:
f.write("include versioneer.py\n")
else:
print(" 'versioneer.py' already in MANIFEST.in")
if cfg.versionfile_source not in simple_includes:
print(" appending versionfile_source ('%s') to MANIFEST.in" %
cfg.versionfile_source)
with open(manifest_in, "a") as f:
f.write("include %s\n" % cfg.versionfile_source)
else:
print(" versionfile_source already in MANIFEST.in")
# Make VCS-specific changes. For git, this means creating/changing
# .gitattributes to mark _version.py for export-subst keyword
# substitution.
do_vcs_install(manifest_in, cfg.versionfile_source, ipy)
return 0
def scan_setup_py():
"""Validate the contents of setup.py against Versioneer's expectations."""
found = set()
setters = False
errors = 0
with open("setup.py", "r") as f:
for line in f.readlines():
if "import versioneer" in line:
found.add("import")
if "versioneer.get_cmdclass()" in line:
found.add("cmdclass")
if "versioneer.get_version()" in line:
found.add("get_version")
if "versioneer.VCS" in line:
setters = True
if "versioneer.versionfile_source" in line:
setters = True
if len(found) != 3:
print("")
print("Your setup.py appears to be missing some important items")
print("(but I might be wrong). Please make sure it has something")
print("roughly like the following:")
print("")
print(" import versioneer")
print(" setup( version=versioneer.get_version(),")
print(" cmdclass=versioneer.get_cmdclass(), ...)")
print("")
errors += 1
if setters:
print("You should remove lines like 'versioneer.VCS = ' and")
print("'versioneer.versionfile_source = ' . This configuration")
print("now lives in setup.cfg, and should be removed from setup.py")
print("")
errors += 1
return errors
if __name__ == "__main__":
cmd = sys.argv[1]
if cmd == "setup":
errors = do_setup()
errors += scan_setup_py()
if errors:
sys.exit(1)
| VersioneerBadRootError |
python | ipython__ipython | tests/test_magic.py | {
"start": 1258,
"end": 10137
} | class ____(magic.Magics):
pass
def test_extract_code_ranges():
instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
expected = [
(0, 1),
(2, 3),
(4, 6),
(6, 9),
(9, 14),
(16, None),
(None, 9),
(9, None),
(None, 13),
(None, None),
]
actual = list(code.extract_code_ranges(instr))
assert actual == expected
def test_extract_symbols():
source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
expected = [
([], ["a"]),
(["def b():\n return 42\n"], []),
(["class A: pass\n"], []),
(["class A: pass\n", "def b():\n return 42\n"], []),
(["class A: pass\n"], ["a"]),
([], ["z"]),
]
for symbols, exp in zip(symbols_args, expected):
assert code.extract_symbols(source, symbols) == exp
def test_extract_symbols_raises_exception_with_non_python_code():
source = "=begin A Ruby program :)=end\n" "def hello\n" "puts 'Hello world'\n" "end"
with pytest.raises(SyntaxError):
code.extract_symbols(source, "hello")
def test_magic_not_found():
# magic not found raises UsageError
with pytest.raises(UsageError):
_ip.run_line_magic("doesntexist", "")
# ensure result isn't success when a magic isn't found
result = _ip.run_cell("%doesntexist")
assert isinstance(result.error_in_exec, UsageError)
def test_cell_magic_not_found():
# magic not found raises UsageError
with pytest.raises(UsageError):
_ip.run_cell_magic("doesntexist", "line", "cell")
# ensure result isn't success when a magic isn't found
result = _ip.run_cell("%%doesntexist")
assert isinstance(result.error_in_exec, UsageError)
def test_magic_error_status():
def fail(shell):
1 / 0
_ip.register_magic_function(fail)
result = _ip.run_cell("%fail")
assert isinstance(result.error_in_exec, ZeroDivisionError)
def test_config():
"""test that config magic does not raise
can happen if Configurable init is moved too early into
Magics.__init__ as then a Config object will be registered as a
magic.
"""
## should not raise.
_ip.run_line_magic("config", "")
def test_config_available_configs():
"""test that config magic prints available configs in unique and
sorted order."""
with capture_output() as captured:
_ip.run_line_magic("config", "")
stdout = captured.stdout
config_classes = stdout.strip().split("\n")[1:]
assert config_classes == sorted(set(config_classes))
def test_config_print_class():
"""test that config with a classname prints the class's options."""
with capture_output() as captured:
_ip.run_line_magic("config", "TerminalInteractiveShell")
stdout = captured.stdout
assert re.match(
"TerminalInteractiveShell.* options", stdout.splitlines()[0]
), f"{stdout}\n\n1st line of stdout not like 'TerminalInteractiveShell.* options'"
def test_rehashx():
# clear up everything
_ip.alias_manager.clear_aliases()
del _ip.db["syscmdlist"]
_ip.run_line_magic("rehashx", "")
# Practically ALL ipython development systems will have more than 10 aliases
assert len(_ip.alias_manager.aliases) > 10
for name, cmd in _ip.alias_manager.aliases:
# we must strip dots from alias names
assert "." not in name
# rehashx must fill up syscmdlist
scoms = _ip.db["syscmdlist"]
assert len(scoms) > 10
def test_magic_parse_options():
"""Test that we don't mangle paths when parsing magic options."""
ip = get_ipython()
path = "c:\\x"
m = DummyMagics(ip)
opts = m.parse_options("-f %s" % path, "f:")[0]
# argv splitting is os-dependent
if os.name == "posix":
expected = "c:x"
else:
expected = path
assert opts["f"] == expected
def test_magic_parse_long_options():
"""Magic.parse_options can handle --foo=bar long options"""
ip = get_ipython()
m = DummyMagics(ip)
opts, _ = m.parse_options("--foo --bar=bubble", "a", "foo", "bar=")
assert "foo" in opts
assert "bar" in opts
assert opts["bar"] == "bubble"
def doctest_hist_f():
"""Test %hist -f with temporary filename.
In [9]: import tempfile, os
In [10]: fd, tfile = tempfile.mkstemp('.py','tmp-ipython-')
In [11]: os.close(fd)
In [12]: %history -nl -y -f $tfile 3
In [14]: import os; os.unlink(tfile)
"""
def doctest_hist_op():
"""Test %hist -op
In [1]: class b(float):
...: pass
...:
In [2]: class s(object):
...: def __str__(self):
...: return 's'
...:
In [3]:
In [4]: class r(b):
...: def __repr__(self):
...: return 'r'
...:
In [5]: class sr(s,r): pass
...:
In [6]:
In [7]: bb=b()
In [8]: ss=s()
In [9]: rr=r()
In [10]: ssrr=sr()
In [11]: 4.5
Out[11]: 4.5
In [12]: str(ss)
Out[12]: 's'
In [13]:
In [14]: %hist -op
>>> class b:
... pass
...
>>> class s(b):
... def __str__(self):
... return 's'
...
>>>
>>> class r(b):
... def __repr__(self):
... return 'r'
...
>>> class sr(s,r): pass
>>>
>>> bb=b()
>>> ss=s()
>>> rr=r()
>>> ssrr=sr()
>>> 4.5
4.5
>>> str(ss)
's'
>>>
"""
def test_hist_pof():
ip = get_ipython()
ip.run_cell("1+2", store_history=True)
# raise Exception(ip.history_manager.session_number)
# raise Exception(list(ip.history_manager._get_range_session()))
with TemporaryDirectory() as td:
tf = os.path.join(td, "hist.py")
ip.run_line_magic("history", "-pof %s" % tf)
assert os.path.isfile(tf)
def test_macro():
ip = get_ipython()
ip.history_manager.reset() # Clear any existing history.
cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
for i, cmd in enumerate(cmds, start=1):
ip.history_manager.store_inputs(i, cmd)
ip.run_line_magic("macro", "test 1-3")
assert ip.user_ns["test"].value == "\n".join(cmds) + "\n"
# List macros
assert "test" in ip.run_line_magic("macro", "")
def test_macro_run():
"""Test that we can run a multi-line macro successfully."""
ip = get_ipython()
ip.history_manager.reset()
cmds = ["a=10", "a+=1", "print(a)", "%macro test 2-3"]
for cmd in cmds:
ip.run_cell(cmd, store_history=True)
assert ip.user_ns["test"].value == "a+=1\nprint(a)\n"
with tt.AssertPrints("12"):
ip.run_cell("test")
with tt.AssertPrints("13"):
ip.run_cell("test")
def test_magic_magic():
"""Test %magic"""
ip = get_ipython()
with capture_output() as captured:
ip.run_line_magic("magic", "")
stdout = captured.stdout
assert "%magic" in stdout
assert "IPython" in stdout
assert "Available" in stdout
@dec.skipif_not_numpy
def test_numpy_reset_array_undec():
"Test '%reset array' functionality"
_ip.ex("import numpy as np")
_ip.ex("a = np.empty(2)")
assert "a" in _ip.user_ns
_ip.run_line_magic("reset", "-f array")
assert "a" not in _ip.user_ns
@pytest.fixture()
def underscore_not_in_builtins():
import builtins
if "_" in builtins.__dict__:
del builtins.__dict__["_"]
def test_reset_out(underscore_not_in_builtins):
"Test '%reset out' magic"
_ip.run_cell("parrot = 'dead'", store_history=True)
# test '%reset -f out', make an Out prompt
_ip.run_cell("parrot", store_history=True)
assert "dead" in [_ip.user_ns[x] for x in ("_", "__", "___")]
_ip.run_line_magic("reset", "-f out")
assert "dead" not in [_ip.user_ns[x] for x in ("_", "__", "___")]
assert len(_ip.user_ns["Out"]) == 0
def test_reset_in():
"Test '%reset in' magic"
# test '%reset -f in'
_ip.run_cell("parrot", store_history=True)
assert "parrot" in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")]
_ip.run_line_magic("reset", "-f in")
assert "parrot" not in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")]
assert len(set(_ip.user_ns["In"])) == 1
def test_reset_dhist():
"Test '%reset dhist' magic"
_ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
_ip.run_line_magic("cd", os.path.dirname(pytest.__file__))
_ip.run_line_magic("cd", "-")
assert len(_ip.user_ns["_dh"]) > 0
_ip.run_line_magic("reset", "-f dhist")
assert len(_ip.user_ns["_dh"]) == 0
_ip.run_cell("_dh = [d for d in tmp]") # restore
def test_reset_in_length():
"Test that '%reset in' preserves In[] length"
_ip.run_cell("print 'foo'")
_ip.run_cell("reset -f in")
assert len(_ip.user_ns["In"]) == _ip.displayhook.prompt_count + 1
| DummyMagics |
python | ApeWorX__ape | src/ape/managers/compilers.py | {
"start": 903,
"end": 14504
} | class ____(BaseManager, ExtraAttributesMixin):
"""
The singleton that manages :class:`~ape.api.compiler.CompilerAPI` instances.
Each compiler plugin typically contains a single :class:`~ape.api.compiler.CompilerAPI`.
**NOTE**: Typically, users compile their projects using the CLI via ``ape compile``,
which uses the :class:`~ape.api.compiler.CompilerAPI` under-the-hood.
Usage example::
from ape import compilers # "compilers" is the CompilerManager singleton
"""
_registered_compilers_cache: dict[Path, dict[str, "CompilerAPI"]] = {}
@log_instead_of_fail(default="<CompilerManager>")
def __repr__(self) -> str:
num_compilers = len(self.registered_compilers)
cls_name = getattr(type(self), "__name__", CompilerManager.__name__)
return f"<{cls_name} len(registered_compilers)={num_compilers}>"
def __ape_extra_attributes__(self) -> Iterator[ExtraModelAttributes]:
yield ExtraModelAttributes(
name="compilers",
# Allow referencing compilers by name e.g. `compilers.vyper`.
attributes=lambda: {c.name: c for c in self.registered_compilers.values()},
)
@only_raise_attribute_error
def __getattr__(self, attr_name: str) -> Any:
return get_attribute_with_extras(self, attr_name)
@cached_property
def registered_compilers(self) -> dict[str, "CompilerAPI"]:
"""
Each compile-able file extension mapped to its respective
:class:`~ape.api.compiler.CompilerAPI` instance.
Returns:
dict[str, :class:`~ape.api.compiler.CompilerAPI`]: The mapping of file-extensions
to compiler API classes.
"""
registered_compilers = {}
for plugin_name, (extensions, compiler_class) in self.plugin_manager.register_compiler:
self.config_manager.get_config(plugin_name)
compiler = compiler_class()
for extension in extensions:
if extension not in registered_compilers:
registered_compilers[extension] = compiler
return registered_compilers
def get_compiler(self, name: str, settings: Optional[dict] = None) -> Optional["CompilerAPI"]:
for compiler in self.registered_compilers.values():
if compiler.name != name:
continue
if settings is not None and settings != compiler.compiler_settings:
# Use a new instance to support multiple compilers of same type.
return compiler.model_copy(update={"compiler_settings": settings})
return compiler
return None
def compile(
self,
contract_filepaths: Union[Path, str, Iterable[Union[Path, str]]],
project: Optional["ProjectManager"] = None,
settings: Optional[dict] = None,
excluded_compilers: Optional[list[str]] = None,
) -> Iterator["ContractType"]:
"""
Invoke :meth:`ape.ape.compiler.CompilerAPI.compile` for each of the given files.
For example, use the `ape-solidity plugin <https://github.com/ApeWorX/ape-solidity>`__
to compile ``'.sol'`` files.
Raises:
:class:`~ape.exceptions.CompilerError`: When there is no compiler found for the given
file-extension as well as when there are contract-type collisions across compilers.
Args:
contract_filepaths (Union[Path, str, Iterable[Union[Path, str]]]): The files to
compile, as ``pathlib.Path`` objects or path-strs.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally
compile a different project that the one from the current-working directory.
settings (Optional[Dict]): Adhoc compiler settings. Defaults to None.
Ensure the compiler name key is present in the dict for it to work.
Returns:
Iterator[``ContractType``]: An iterator of contract types.
"""
pm = project or self.local_project
files_by_ext = defaultdict(list)
if isinstance(contract_filepaths, (str, Path)):
contract_filepaths = (contract_filepaths,)
for path in map(Path, contract_filepaths):
suffix = get_full_extension(path)
if suffix in self.registered_compilers:
files_by_ext[suffix].append(path)
errors = []
tracker: dict[str, str] = {}
settings = settings or {}
for next_ext, path_set in files_by_ext.items():
compiler = self.registered_compilers[next_ext]
if excluded_compilers and compiler.name.lower() in excluded_compilers:
continue
try:
compiler_settings = settings.get(compiler.name, {})
for contract in compiler.compile(path_set, project=pm, settings=compiler_settings):
if contract.name in tracker:
raise CompilerError(
f"ContractType collision. "
f"Contracts '{tracker[contract.name]}' and '{contract.source_id}' "
f"share the name '{contract.name}'."
)
if contract.name and contract.source_id:
tracker[contract.name] = contract.source_id
yield contract
except Exception as err:
# One of the compilers failed. Show the error but carry on.
logger.log_debug_stack_trace()
errors.append(err)
continue
if len(errors) == 1:
# If only 1 error, just raise that.
raise errors[0]
elif len(errors) > 1:
# Raise a combined error.
formatted_errors = [f"{e}" for e in errors]
error_message = "\n\n".join(formatted_errors)
raise CompilerError(error_message)
# else: successfully compiled everything!
def compile_source(
self,
compiler_name: str,
code: str,
project: Optional["ProjectManager"] = None,
settings: Optional[dict] = None,
**kwargs,
) -> ContractContainer:
"""
Compile the given program.
Usage example::
code = '[{"name":"foo","type":"fallback", "stateMutability":"nonpayable"}]'
contract_container = compilers.compile_source(
"ethpm",
code,
contractName="MyContract",
)
Args:
compiler_name (str): The name of the compiler to use.
code (str): The source code to compile.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally
compile a different project that the one from the current-working directory.
settings (Optional[dict]): Compiler settings.
**kwargs (Any): Additional overrides for the ``ethpm_types.ContractType`` model.
Returns:
``ContractContainer``: A contract container ready to be deployed.
"""
compiler = self.get_compiler(compiler_name, settings=settings)
if not compiler:
raise ValueError(f"Compiler '{compiler_name}' not found.")
contract_type = compiler.compile_code(code, project=project, **kwargs)
return ContractContainer(contract_type=contract_type)
def get_imports(
self,
contract_filepaths: Sequence[Path],
project: Optional["ProjectManager"] = None,
) -> dict[str, list[str]]:
"""
Combine import dicts from all compilers, where the key is a contract's source_id
and the value is a list of import source_ids.
Args:
contract_filepaths (Sequence[pathlib.Path]): A list of source file paths to compile.
project (Optional[:class:`~ape.managers.project.ProjectManager`]): Optionally provide
the project.
Returns:
dict[str, list[str]]: A dictionary like ``{source_id: [import_source_id, ...], ...}``
"""
imports_dict: dict[str, list[str]] = {}
for ext, compiler in self.registered_compilers.items():
try:
sources = [
p for p in contract_filepaths if get_full_extension(p) == ext and p.is_file()
]
imports = compiler.get_imports(contract_filepaths=sources, project=project)
except NotImplementedError:
imports = None
if imports:
imports_dict.update(imports)
return imports_dict
def get_references(self, imports_dict: dict[str, list[str]]) -> dict[str, list[str]]:
"""
Provide a mapping containing all referenced source_ids for a given project.
Each entry contains a source_id as a key and list of source_ids that reference a
given contract.
Args:
imports_dict (dict[str, list[str]]): A dictionary of source_ids from all compilers.
Returns:
dict[str, list[str]]: A dictionary like ``{source_id: [referring_source_id, ...], ...}``
"""
references_dict: dict[str, list[str]] = {}
if not imports_dict:
return {}
for key, imports_list in imports_dict.items():
for filepath in imports_list:
if filepath not in references_dict:
references_dict[filepath] = []
references_dict[filepath].append(key)
return references_dict
def enrich_error(self, err: ContractLogicError) -> ContractLogicError:
"""
Enrich a contract logic error using compiler information, such
known PC locations for compiler runtime errors.
Args:
err (:class:`~ape.exceptions.ContractLogicError`): The exception
to enrich.
Returns:
:class:`~ape.exceptions.ContractLogicError`: The enriched exception.
"""
# First, try enriching using their ABI.
err = self.get_custom_error(err) or err
if not (contract_type := err.contract_type):
return err
# Delegate to compiler APIs.
elif source_id := contract_type.source_id:
# Source ID found! Delegate to a CompilerAPI for enrichment.
ext = get_full_extension(Path(source_id))
if ext not in self.registered_compilers:
# Compiler not found.
return err
compiler = self.registered_compilers[ext]
return compiler.enrich_error(err)
# No further enrichment.
return err
def get_custom_error(self, err: ContractLogicError) -> Optional[CustomError]:
"""
Get a custom error for the given contract logic error using the contract-type
found from address-data in the error. Returns ``None`` if the given error is
not a custom-error, or it is not able to find the associated contract type or
address.
Args:
err (:class:`~ape.exceptions.ContractLogicError`): The error to enrich
as a custom error.
Returns:
Optional[:class:`~ape.exceptions.CustomError`]
"""
message = err.revert_message
if not message.startswith("0x"):
return None
elif not (address := err.address):
return None
if provider := self.network_manager.active_provider:
ecosystem = provider.network.ecosystem
else:
# Default to Ethereum.
ecosystem = self.network_manager.ethereum
try:
return ecosystem.decode_custom_error(
HexBytes(message),
address,
base_err=err.base_err,
source_traceback=lambda: err.source_traceback,
trace=err.trace,
txn=err.txn,
)
except NotImplementedError:
return None
def flatten_contract(self, path: Path, **kwargs) -> "Content":
"""
Get the flattened version of a contract via its source path.
Delegates to the matching :class:`~ape.api.compilers.CompilerAPI`.
Args:
path (``pathlib.Path``): The source path of the contract.
Returns:
``ethpm_types.source.Content``: The flattened contract content.
"""
suffix = get_full_extension(path)
if suffix not in self.registered_compilers:
raise CompilerError(f"Unable to flatten contract. Missing compiler for '{suffix}'.")
compiler = self.registered_compilers[suffix]
return compiler.flatten_contract(path, **kwargs)
def can_trace_source(self, filename: str) -> bool:
"""
Check if Ape is able trace the source lines for the given file.
Checks that both the compiler is registered and that it supports
the :meth:`~ape.api.compilers.CompilerAPI.trace_source` API method.
Args:
filename (str): The file to check.
Returns:
bool: ``True`` when the source is traceable.
"""
path = Path(filename)
if not path.is_file():
return False
extension = get_full_extension(path)
if extension in self.registered_compilers:
compiler = self.registered_compilers[extension]
if compiler.supports_source_tracing:
return True
# We are not able to get coverage for this file.
return False
| CompilerManager |
python | pypa__pip | src/pip/_internal/metadata/base.py | {
"start": 24938,
"end": 25159
} | class ____(Wheel):
def __init__(self, location: str) -> None:
self.location = location
def as_zipfile(self) -> zipfile.ZipFile:
return zipfile.ZipFile(self.location, allowZip64=True)
| FilesystemWheel |
python | walkccc__LeetCode | solutions/1037. Valid Boomerang/1037.py | {
"start": 0,
"end": 226
} | class ____:
def isBoomerang(self, points: list[list[int]]) -> bool:
return ((points[1][0] - points[0][0]) * (points[2][1] - points[1][1]) !=
(points[1][1] - points[0][1]) * (points[2][0] - points[1][0]))
| Solution |
python | scipy__scipy | benchmarks/benchmarks/signal.py | {
"start": 6517,
"end": 6762
} | class ____(Benchmark):
param_names = ['n', 'edges']
params = [
[21, 101, 1001, 2001],
[(0.1, 0.9), (0.01, 0.99)],
]
def time_firls(self, n, edges):
signal.firls(n, (0,) + edges + (1,), [1, 1, 0, 0])
| FIRLS |
python | nryoung__algorithms | algorithms/random/mersenne_twister.py | {
"start": 340,
"end": 1594
} | class ____:
def __init__(self):
self.state = []
self.index = 0
def seed(self, seed):
"""
Initialize generator.
:param seed: An integer value to seed the generator with
"""
self.state = []
self.index = 0
self.state.append(seed)
for i in range(1, 624):
n = (0x6c078965 * (self.state[i-1] ^ (self.state[i-1] >> 30)) + i)
n &= 0xffffffff
self.state.append(n)
def randint(self):
"""
Extracts a random number.
:rtype: A random integer
"""
if self.index == 0:
self.generate()
y = self.state[self.index]
y ^= y >> 11
y ^= (y << 7) & 0x9d2c5680
y ^= (y << 15) & 0xefc60000
y ^= y >> 18
self.index = (self.index + 1) % 624
return y
def generate(self):
"""
Generates 624 random numbers and stores in the state list.
"""
for i in range(624):
n = self.state[i] & 0x80000000
n += self.state[(i+1) % 624] & 0x7fffffff
self.state[i] = self.state[(i+397) % 624] ^ (n >> 1)
if n % 2 != 0:
self.state[i] ^= 0x9908b0df
| MersenneTwister |
python | readthedocs__readthedocs.org | readthedocs/search/api/v3/tests/test_api.py | {
"start": 13365,
"end": 19572
} | class ____(SearchAPITest):
host = "project.readthedocs.io"
def get(self, *args, **kwargs):
return self.client.get(*args, HTTP_HOST=self.host, **kwargs)
def test_search_project_number_of_queries(self):
# Default version
with self.assertNumQueries(11):
resp = self.get(self.url, data={"q": "project:project test"})
assert resp.status_code == 200
assert resp.data["results"]
with self.assertNumQueries(17):
resp = self.get(
self.url, data={"q": "project:project project:another-project test"}
)
assert resp.status_code == 200
assert resp.data["results"]
# With explicit version
with self.assertNumQueries(10):
resp = self.get(self.url, data={"q": "project:project/latest test"})
assert resp.status_code == 200
assert resp.data["results"]
with self.assertNumQueries(16):
resp = self.get(
self.url, data={"q": "project:project/latest project:another-project/latest test"}
)
assert resp.status_code == 200
assert resp.data["results"]
@mock.patch("readthedocs.search.api.v3.views.tasks.record_search_query.delay", new=mock.MagicMock())
def test_search_project_number_of_queries_without_search_recording(self):
# Default version
with self.assertNumQueries(8):
resp = self.get(self.url, data={"q": "project:project test"})
assert resp.status_code == 200
assert resp.data["results"]
with self.assertNumQueries(12):
resp = self.get(
self.url, data={"q": "project:project project:another-project test"}
)
assert resp.status_code == 200
assert resp.data["results"]
# With explicit version
with self.assertNumQueries(8):
resp = self.get(self.url, data={"q": "project:project/latest test"})
assert resp.status_code == 200
assert resp.data["results"]
with self.assertNumQueries(12):
resp = self.get(
self.url, data={"q": "project:project/latest project:another-project/latest test"}
)
assert resp.status_code == 200
assert resp.data["results"]
def test_search_subprojects_number_of_queries(self):
subproject = get(
Project,
slug="subproject",
users=[self.user],
privacy_level=PUBLIC,
)
subproject.versions.update(built=True, active=True, privacy_level=PUBLIC)
self.create_index(subproject.versions.first())
self.project.add_subproject(subproject)
# Search on default version.
with self.assertNumQueries(16):
resp = self.get(self.url, data={"q": "subprojects:project test"})
assert resp.status_code == 200
assert resp.data["results"]
# Search on explicit version.
with self.assertNumQueries(14):
resp = self.get(self.url, data={"q": "subprojects:project/latest test"})
assert resp.status_code == 200
assert resp.data["results"]
# Add subprojects.
for i in range(3):
subproject = get(
Project,
slug=f"subproject-{i}",
users=[self.user],
privacy_level=PUBLIC,
)
subproject.versions.update(built=True, active=True, privacy_level=PUBLIC)
self.create_index(subproject.versions.first())
self.project.add_subproject(subproject)
# Search on default version.
with self.assertNumQueries(26):
resp = self.get(self.url, data={"q": "subprojects:project test"})
assert resp.status_code == 200
assert resp.data["results"]
# Search on explicit version.
with self.assertNumQueries(23):
resp = self.get(self.url, data={"q": "subprojects:project/latest test"})
assert resp.status_code == 200
assert resp.data["results"]
@mock.patch("readthedocs.search.api.v3.views.tasks.record_search_query.delay", new=mock.MagicMock())
def test_search_subprojects_number_of_queries_without_search_recording(self):
subproject = get(
Project,
slug="subproject",
users=[self.user],
privacy_level=PUBLIC,
)
subproject.versions.update(built=True, active=True, privacy_level=PUBLIC)
self.create_index(subproject.versions.first())
self.project.add_subproject(subproject)
# Search on default version.
with self.assertNumQueries(10):
resp = self.get(self.url, data={"q": "subprojects:project test"})
assert resp.status_code == 200
assert resp.data["results"]
# Search on explicit version.
with self.assertNumQueries(10):
resp = self.get(self.url, data={"q": "subprojects:project/latest test"})
assert resp.status_code == 200
assert resp.data["results"]
# Add subprojects.
for i in range(3):
subproject = get(
Project,
slug=f"subproject-{i}",
users=[self.user],
privacy_level=PUBLIC,
)
subproject.versions.update(built=True, active=True, privacy_level=PUBLIC)
self.create_index(subproject.versions.first())
self.project.add_subproject(subproject)
# Search on default version.
with self.assertNumQueries(13):
resp = self.get(self.url, data={"q": "subprojects:project test"})
assert resp.status_code == 200
assert resp.data["results"]
# Search on explicit version.
with self.assertNumQueries(13):
resp = self.get(self.url, data={"q": "subprojects:project/latest test"})
assert resp.status_code == 200
assert resp.data["results"]
@override_settings(ALLOW_PRIVATE_REPOS=True)
@override_settings(RTD_ALLOW_ORGANIZATIONS=True)
| ProxiedSearchAPITest |
python | sympy__sympy | sympy/matrices/common.py | {
"start": 92107,
"end": 95395
} | class ____:
"""Wrapper class providing the minimum functionality for a matrix-like
object: .rows, .cols, .shape, indexability, and iterability. CommonMatrix
math operations should work on matrix-like objects. This one is intended for
matrix-like objects which use the same indexing format as SymPy with respect
to returning matrix elements instead of rows for non-tuple indexes.
"""
is_Matrix = False # needs to be here because of __getattr__
is_MatrixLike = True
def __init__(self, mat, shape):
self.mat = mat
self.shape = shape
self.rows, self.cols = shape
def __getitem__(self, key):
if isinstance(key, tuple):
return sympify(self.mat.__getitem__(key))
return sympify(self.mat.__getitem__((key // self.rows, key % self.cols)))
def __iter__(self): # supports numpy.matrix and numpy.array
mat = self.mat
cols = self.cols
return iter(sympify(mat[r, c]) for r in range(self.rows) for c in range(cols))
def _matrixify(mat):
"""If `mat` is a Matrix or is matrix-like,
return a Matrix or MatrixWrapper object. Otherwise
`mat` is passed through without modification."""
if getattr(mat, 'is_Matrix', False) or getattr(mat, 'is_MatrixLike', False):
return mat
if not(getattr(mat, 'is_Matrix', True) or getattr(mat, 'is_MatrixLike', True)):
return mat
shape = None
if hasattr(mat, 'shape'): # numpy, scipy.sparse
if len(mat.shape) == 2:
shape = mat.shape
elif hasattr(mat, 'rows') and hasattr(mat, 'cols'): # mpmath
shape = (mat.rows, mat.cols)
if shape:
return _MatrixWrapper(mat, shape)
return mat
def a2idx(j, n=None):
"""Return integer after making positive and validating against n."""
if not isinstance(j, int):
jindex = getattr(j, '__index__', None)
if jindex is not None:
j = jindex()
else:
raise IndexError("Invalid index a[%r]" % (j,))
if n is not None:
if j < 0:
j += n
if not (j >= 0 and j < n):
raise IndexError("Index out of range: a[%s]" % (j,))
return int(j)
def classof(A, B):
"""
Get the type of the result when combining matrices of different types.
Currently the strategy is that immutability is contagious.
Examples
========
>>> from sympy import Matrix, ImmutableMatrix
>>> from sympy.matrices.matrixbase import classof
>>> M = Matrix([[1, 2], [3, 4]]) # a Mutable Matrix
>>> IM = ImmutableMatrix([[1, 2], [3, 4]])
>>> classof(M, IM)
<class 'sympy.matrices.immutable.ImmutableDenseMatrix'>
"""
priority_A = getattr(A, '_class_priority', None)
priority_B = getattr(B, '_class_priority', None)
if None not in (priority_A, priority_B):
if A._class_priority > B._class_priority:
return A.__class__
else:
return B.__class__
try:
import numpy
except ImportError:
pass
else:
if isinstance(A, numpy.ndarray):
return B.__class__
if isinstance(B, numpy.ndarray):
return A.__class__
raise TypeError("Incompatible classes %s, %s" % (A.__class__, B.__class__))
| _MatrixWrapper |
python | rq__rq | rq/cli/helpers.py | {
"start": 8435,
"end": 11527
} | class ____(Enum):
PLAIN_TEXT = 0
JSON = 1
LITERAL_EVAL = 2
def _parse_json_value(value, keyword, arg_pos):
"""Parse value as JSON with error handling."""
try:
return loads(value)
except JSONDecodeError:
raise click.BadParameter('Unable to parse %s as JSON.' % (keyword or '%s. non keyword argument' % arg_pos))
def _parse_literal_eval_value(value, keyword, arg_pos):
"""Parse value using literal_eval with error handling."""
try:
return literal_eval(value)
except Exception:
raise click.BadParameter(
'Unable to eval %s as Python object. See '
'https://docs.python.org/3/library/ast.html#ast.literal_eval'
% (keyword or '%s. non keyword argument' % arg_pos)
)
def parse_function_arg(argument, arg_pos):
keyword = None
if argument.startswith(':'): # no keyword, json
mode = ParsingMode.JSON
value = argument[1:]
elif argument.startswith('%'): # no keyword, literal_eval
mode = ParsingMode.LITERAL_EVAL
value = argument[1:]
else:
index = argument.find('=')
if index > 0:
if ':' in argument and argument.index(':') + 1 == index: # keyword, json
mode = ParsingMode.JSON
keyword = argument[: index - 1]
elif '%' in argument and argument.index('%') + 1 == index: # keyword, literal_eval
mode = ParsingMode.LITERAL_EVAL
keyword = argument[: index - 1]
else: # keyword, text
mode = ParsingMode.PLAIN_TEXT
keyword = argument[:index]
value = argument[index + 1 :]
else: # no keyword, text
mode = ParsingMode.PLAIN_TEXT
value = argument
if value.startswith('@'):
try:
with open(value[1:]) as file:
value = file.read()
except FileNotFoundError:
raise click.FileError(value[1:], 'Not found')
if mode == ParsingMode.JSON: # json
value = _parse_json_value(value, keyword, arg_pos)
elif mode == ParsingMode.LITERAL_EVAL: # literal_eval
value = _parse_literal_eval_value(value, keyword, arg_pos)
return keyword, value
def parse_function_args(arguments):
args = []
kwargs = {}
for argument in arguments:
keyword, value = parse_function_arg(argument, len(args) + 1)
if keyword is not None:
if keyword in kwargs:
raise click.BadParameter("You can't specify multiple values for the same keyword.")
kwargs[keyword] = value
else:
args.append(value)
return args, kwargs
def parse_schedule(schedule_in, schedule_at):
if schedule_in is not None:
if schedule_at is not None:
raise click.BadArgumentUsage("You can't specify both --schedule-in and --schedule-at")
return now() + timedelta(seconds=parse_timeout(schedule_in))
elif schedule_at is not None:
return datetime.strptime(schedule_at, '%Y-%m-%dT%H:%M:%S')
| ParsingMode |
python | numba__numba | numba/tests/test_record_dtype.py | {
"start": 31915,
"end": 34872
} | class ____(TestCase):
# Test getitem when index is Literal[str]
def test_literal_variable(self):
arr = np.array([1, 2], dtype=recordtype2)
pyfunc = get_field1
jitfunc = njit(pyfunc)
self.assertEqual(pyfunc(arr[0]), jitfunc(arr[0]))
def test_literal_unroll(self):
arr = np.array([1, 2], dtype=recordtype2)
pyfunc = get_field2
jitfunc = njit(pyfunc)
self.assertEqual(pyfunc(arr[0]), jitfunc(arr[0]))
def test_literal_variable_global_tuple(self):
# This tests the getitem of record array when the indexes come from a
# global tuple. It tests getitem behaviour but also tests that a global
# tuple is being typed as a tuple of constants.
arr = np.array([1, 2], dtype=recordtype2)
pyfunc = get_field3
jitfunc = njit(pyfunc)
self.assertEqual(pyfunc(arr[0]), jitfunc(arr[0]))
def test_literal_unroll_global_tuple(self):
# This tests the getitem of record array when the indexes come from a
# global tuple and are being unrolled.
# It tests getitem behaviour but also tests that literal_unroll accepts
# a global tuple as argument
arr = np.array([1, 2], dtype=recordtype2)
pyfunc = get_field4
jitfunc = njit(pyfunc)
self.assertEqual(pyfunc(arr[0]), jitfunc(arr[0]))
def test_literal_unroll_free_var_tuple(self):
# This tests the getitem of record array when the indexes come from a
# free variable tuple (not local, not global) and are being unrolled.
# It tests getitem behaviour but also tests that literal_unroll accepts
# a free variable tuple as argument
fs = ('e', 'f')
arr = np.array([1, 2], dtype=recordtype2)
def get_field(rec):
out = 0
for f in literal_unroll(fs):
out += rec[f]
return out
jitfunc = njit(get_field)
self.assertEqual(get_field(arr[0]), jitfunc(arr[0]))
def test_error_w_invalid_field(self):
arr = np.array([1, 2], dtype=recordtype3)
jitfunc = njit(get_field1)
with self.assertRaises(TypingError) as raises:
jitfunc(arr[0])
self.assertIn("Field 'f' was not found in record with fields "
"('first', 'second')", str(raises.exception))
def test_literal_unroll_dynamic_to_static_getitem_transform(self):
# See issue #6634
keys = ('a', 'b', 'c')
n = 5
def pyfunc(rec):
x = np.zeros((n,))
for o in literal_unroll(keys):
x += rec[o]
return x
dt = np.float64
ldd = [np.arange(dt(n)) for x in keys]
ldk = [(x, np.float64,) for x in keys]
rec = np.rec.fromarrays(ldd, dtype=ldk)
expected = pyfunc(rec)
got = njit(pyfunc)(rec)
np.testing.assert_allclose(expected, got)
| TestRecordArrayGetItem |
python | kubernetes-client__python | kubernetes/client/models/v1_rule_with_operations.py | {
"start": 383,
"end": 9436
} | 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 = {
'api_groups': 'list[str]',
'api_versions': 'list[str]',
'operations': 'list[str]',
'resources': 'list[str]',
'scope': 'str'
}
attribute_map = {
'api_groups': 'apiGroups',
'api_versions': 'apiVersions',
'operations': 'operations',
'resources': 'resources',
'scope': 'scope'
}
def __init__(self, api_groups=None, api_versions=None, operations=None, resources=None, scope=None, local_vars_configuration=None): # noqa: E501
"""V1RuleWithOperations - 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._api_groups = None
self._api_versions = None
self._operations = None
self._resources = None
self._scope = None
self.discriminator = None
if api_groups is not None:
self.api_groups = api_groups
if api_versions is not None:
self.api_versions = api_versions
if operations is not None:
self.operations = operations
if resources is not None:
self.resources = resources
if scope is not None:
self.scope = scope
@property
def api_groups(self):
"""Gets the api_groups of this V1RuleWithOperations. # noqa: E501
APIGroups is the API groups the resources belong to. '*' is all groups. If '*' is present, the length of the slice must be one. Required. # noqa: E501
:return: The api_groups of this V1RuleWithOperations. # noqa: E501
:rtype: list[str]
"""
return self._api_groups
@api_groups.setter
def api_groups(self, api_groups):
"""Sets the api_groups of this V1RuleWithOperations.
APIGroups is the API groups the resources belong to. '*' is all groups. If '*' is present, the length of the slice must be one. Required. # noqa: E501
:param api_groups: The api_groups of this V1RuleWithOperations. # noqa: E501
:type: list[str]
"""
self._api_groups = api_groups
@property
def api_versions(self):
"""Gets the api_versions of this V1RuleWithOperations. # noqa: E501
APIVersions is the API versions the resources belong to. '*' is all versions. If '*' is present, the length of the slice must be one. Required. # noqa: E501
:return: The api_versions of this V1RuleWithOperations. # noqa: E501
:rtype: list[str]
"""
return self._api_versions
@api_versions.setter
def api_versions(self, api_versions):
"""Sets the api_versions of this V1RuleWithOperations.
APIVersions is the API versions the resources belong to. '*' is all versions. If '*' is present, the length of the slice must be one. Required. # noqa: E501
:param api_versions: The api_versions of this V1RuleWithOperations. # noqa: E501
:type: list[str]
"""
self._api_versions = api_versions
@property
def operations(self):
"""Gets the operations of this V1RuleWithOperations. # noqa: E501
Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or * for all of those operations and any future admission operations that are added. If '*' is present, the length of the slice must be one. Required. # noqa: E501
:return: The operations of this V1RuleWithOperations. # noqa: E501
:rtype: list[str]
"""
return self._operations
@operations.setter
def operations(self, operations):
"""Sets the operations of this V1RuleWithOperations.
Operations is the operations the admission hook cares about - CREATE, UPDATE, DELETE, CONNECT or * for all of those operations and any future admission operations that are added. If '*' is present, the length of the slice must be one. Required. # noqa: E501
:param operations: The operations of this V1RuleWithOperations. # noqa: E501
:type: list[str]
"""
self._operations = operations
@property
def resources(self):
"""Gets the resources of this V1RuleWithOperations. # noqa: E501
Resources is a list of resources this rule applies to. For example: 'pods' means pods. 'pods/log' means the log subresource of pods. '*' means all resources, but not subresources. 'pods/*' means all subresources of pods. '*/scale' means all scale subresources. '*/*' means all resources and their subresources. If wildcard is present, the validation rule will ensure resources do not overlap with each other. Depending on the enclosing object, subresources might not be allowed. Required. # noqa: E501
:return: The resources of this V1RuleWithOperations. # noqa: E501
:rtype: list[str]
"""
return self._resources
@resources.setter
def resources(self, resources):
"""Sets the resources of this V1RuleWithOperations.
Resources is a list of resources this rule applies to. For example: 'pods' means pods. 'pods/log' means the log subresource of pods. '*' means all resources, but not subresources. 'pods/*' means all subresources of pods. '*/scale' means all scale subresources. '*/*' means all resources and their subresources. If wildcard is present, the validation rule will ensure resources do not overlap with each other. Depending on the enclosing object, subresources might not be allowed. Required. # noqa: E501
:param resources: The resources of this V1RuleWithOperations. # noqa: E501
:type: list[str]
"""
self._resources = resources
@property
def scope(self):
"""Gets the scope of this V1RuleWithOperations. # noqa: E501
scope specifies the scope of this rule. Valid values are \"Cluster\", \"Namespaced\", and \"*\" \"Cluster\" means that only cluster-scoped resources will match this rule. Namespace API objects are cluster-scoped. \"Namespaced\" means that only namespaced resources will match this rule. \"*\" means that there are no scope restrictions. Subresources match the scope of their parent resource. Default is \"*\". # noqa: E501
:return: The scope of this V1RuleWithOperations. # noqa: E501
:rtype: str
"""
return self._scope
@scope.setter
def scope(self, scope):
"""Sets the scope of this V1RuleWithOperations.
scope specifies the scope of this rule. Valid values are \"Cluster\", \"Namespaced\", and \"*\" \"Cluster\" means that only cluster-scoped resources will match this rule. Namespace API objects are cluster-scoped. \"Namespaced\" means that only namespaced resources will match this rule. \"*\" means that there are no scope restrictions. Subresources match the scope of their parent resource. Default is \"*\". # noqa: E501
:param scope: The scope of this V1RuleWithOperations. # noqa: E501
:type: str
"""
self._scope = scope
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, V1RuleWithOperations):
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, V1RuleWithOperations):
return True
return self.to_dict() != other.to_dict()
| V1RuleWithOperations |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 115769,
"end": 128685
} | class ____(Response):
"""
Response of datasets.get_all endpoint.
:param datasets: List of datasets
:type datasets: Sequence[Dataset]
:param scroll_id: Scroll ID that can be used with the next calls to get_all to
retrieve more data
:type scroll_id: str
"""
_service = "datasets"
_action = "get_all"
_version = "2.23"
_schema = {
"definitions": {
"dataset": {
"properties": {
"comment": {"description": "", "type": ["string", "null"]},
"company": {
"description": "Company ID",
"type": ["string", "null"],
},
"created": {
"description": "Dataset creation time (UTC)",
"format": "date-time",
"type": ["string", "null"],
},
"display_stats": {
"description": "Calculated statistics for the latest committed or published version",
"oneOf": [
{"$ref": "#/definitions/statistics"},
{"type": "null"},
],
},
"display_version_name": {
"description": "The name of the version from which statistics are taken",
"type": ["string", "null"],
},
"head_version": {
"description": (
"The most recent version for write operations. Calculated as the non-published version with"
" the longest path to the root."
),
"oneOf": [{"$ref": "#/definitions/version"}, {"type": "null"}],
},
"id": {"description": "Dataset ID", "type": ["string", "null"]},
"last_update": {
"description": (
"Time of last update (UTC). Updated on dataset update; on any version operation:\nwhen"
" version is created, modified, committed, published or deleted; and on any frame"
" operation: when frames are added,\nmodified or deleted."
),
"format": "date-time",
"type": ["string", "null"],
},
"metadata": {
"additionalProperties": True,
"description": "User-provided metadata",
"type": ["object", "null"],
},
"name": {
"description": "Dataset name",
"type": ["string", "null"],
},
"paradigm": {
"description": (
"'single_version' for datasets whose version tree has only one path, 'general' otherwise"
),
"oneOf": [
{"$ref": "#/definitions/version_paradigm_enum"},
{"type": "null"},
],
},
"project": {
"description": "Associated project ID",
"type": ["string", "null"],
},
"system_tags": {
"description": (
"List of system tags. This field is reserved for system use, please don't use it."
),
"items": {"type": "string"},
"type": ["array", "null"],
},
"tags": {
"description": "List of user-defined tags",
"items": {"type": "string"},
"type": ["array", "null"],
},
"terms_of_use": {
"description": "Terms of use string",
"type": ["string", "null"],
},
"user": {
"description": "Associated user ID",
"type": ["string", "null"],
},
"version_count": {
"description": "Amount of versions in dataset. Only supported by datasets.get_all.",
"type": ["integer", "null"],
},
},
"type": "object",
},
"stat_count": {
"properties": {
"count": {
"description": "Item name",
"type": ["integer", "null"],
},
"name": {
"description": "Number of appearances",
"type": ["string", "null"],
},
},
"type": "object",
},
"statistics": {
"properties": {
"content_types": {
"items": {
"$ref": "#/definitions/stat_count",
"description": (
"List of content type counts for the version (e.g.\n 'image/jpeg',"
" 'image/png', 'video/mp4')"
),
},
"type": ["array", "null"],
},
"frames": {
"items": {
"$ref": "#/definitions/stat_count",
"description": (
"List of frame counts, indicating the\n type of frames included in"
" the version (annotated/"
),
},
"type": ["array", "null"],
},
"labels": {
"items": {
"$ref": "#/definitions/stat_count",
"description": (
"List of labels' counts,\n indicating the categories included in the"
" version"
),
},
"type": ["array", "null"],
},
},
"type": "object",
},
"version": {
"properties": {
"comment": {
"description": "Version comment",
"type": ["string", "null"],
},
"committed": {
"description": "Commit time",
"format": "date-time",
"type": ["string", "null"],
},
"committed_frames_ts": {
"description": "Timestamp of last committed frame",
"type": ["number", "null"],
},
"committed_rois_ts": {
"description": "Timestamp of last committed ROI",
"type": ["number", "null"],
},
"company": {
"description": "Company ID",
"type": ["string", "null"],
},
"created": {
"description": "Version creation time (UTC) ",
"format": "date-time",
"type": ["string", "null"],
},
"dataset": {
"description": "Datset ID",
"type": ["string", "null"],
},
"es_index": {
"description": "Name of elasticsearch index",
"type": ["string", "null"],
},
"id": {"description": "Version ID", "type": ["string", "null"]},
"last_frames_update": {
"description": "Last time version was created, committed or frames were updated or saved",
"format": "date-time",
"type": ["string", "null"],
},
"metadata": {
"additionalProperties": True,
"description": "User-provided metadata",
"type": ["object", "null"],
},
"name": {
"description": "Version name",
"type": ["string", "null"],
},
"parent": {
"description": "Version parent ID",
"type": ["string", "null"],
},
"published": {
"description": "Publish time",
"format": "date-time",
"type": ["string", "null"],
},
"stats": {
"description": "Version statistics",
"oneOf": [
{"$ref": "#/definitions/statistics"},
{"type": "null"},
],
},
"status": {
"description": "Version status",
"oneOf": [
{"$ref": "#/definitions/version_status_enum"},
{"type": "null"},
],
},
"system_tags": {
"description": (
"List of system tags. This field is reserved for system use, please don't use it."
),
"items": {"type": "string"},
"type": ["array", "null"],
},
"tags": {
"description": "List of user-defined tags",
"items": {"type": "string"},
"type": ["array", "null"],
},
"task": {
"description": "Task ID of the task which created the version",
"type": ["string", "null"],
},
"user": {
"description": "Associated user ID",
"type": ["string", "null"],
},
},
"type": "object",
},
"version_paradigm_enum": {
"enum": ["single_version", "general"],
"type": "string",
},
"version_status_enum": {
"enum": ["draft", "committing", "committed", "published"],
"type": "string",
},
},
"properties": {
"datasets": {
"description": "List of datasets",
"items": {"$ref": "#/definitions/dataset"},
"type": ["array", "null"],
},
"scroll_id": {
"description": "Scroll ID that can be used with the next calls to get_all to retrieve more data",
"type": ["string", "null"],
},
},
"type": "object",
}
def __init__(self, datasets=None, scroll_id=None, **kwargs):
super(GetAllResponse, self).__init__(**kwargs)
self.datasets = datasets
self.scroll_id = scroll_id
@schema_property("datasets")
def datasets(self):
return self._property_datasets
@datasets.setter
def datasets(self, value):
if value is None:
self._property_datasets = None
return
self.assert_isinstance(value, "datasets", (list, tuple))
if any(isinstance(v, dict) for v in value):
value = [Dataset.from_dict(v) if isinstance(v, dict) else v for v in value]
else:
self.assert_isinstance(value, "datasets", Dataset, is_array=True)
self._property_datasets = value
@schema_property("scroll_id")
def scroll_id(self):
return self._property_scroll_id
@scroll_id.setter
def scroll_id(self, value):
if value is None:
self._property_scroll_id = None
return
self.assert_isinstance(value, "scroll_id", six.string_types)
self._property_scroll_id = value
| GetAllResponse |
python | lxml__lxml | doc/s5/ep2008/atom.py | {
"start": 2283,
"end": 4468
} | class ____(list):
"""
This list calls on_add or on_remove whenever the list is modified.
"""
on_add = on_remove = None
name = None
def __init__(self, *args, **kw):
on_add = on_remove = name = None
if 'on_add' in kw:
on_add = kw.pop('on_add')
if 'on_remove' in kw:
on_remove = kw.pop('on_remove')
if 'name' in kw:
name = kw.pop('name')
list.__init__(self, *args, **kw)
self.on_add = on_add
self.on_remove = on_remove
self.name = name
def _make_list(self, obj):
if not isinstance(obj, (list, tuple)):
obj = list(obj)
return obj
def _do_add(self, items):
if self.on_add is not None:
for item in items:
self.on_add(self, item)
def _do_remove(self, items):
if self.on_remove is not None:
for item in items:
self.on_remove(self, item)
def __setslice__(self, i, j, other):
other = self._make_list(other)
old = self[i:j]
list.__setslice__(self, i, j, other)
self._do_remove(old)
self._do_add(other)
def __delslice__(self, i, j):
old = self[i:j]
list.__delslice__(self, i, j)
self._do_remove(old)
def __iadd__(self, other):
other = self._make_list(other)
list.__iadd__(self, other)
self._do_add(other)
def __imul__(self, n):
while n > 0:
self += self
n -= 1
def append(self, item):
list.append(self, item)
self._do_add([item])
def insert(self, i, item):
list.insert(self, i, item)
self._do_add([item])
def pop(self, i=-1):
item = self[i]
result = list.pop(self, i)
self._do_remove([item])
return result
def remove(self, item):
list.remove(self, item)
self._do_remove([item])
def extend(self, other):
for item in other:
self.append(item)
def __repr__(self):
name = self.name
if name is None:
name = '_LiveList'
return '%s(%s)' % (name, list.__repr__(self))
| _LiveList |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-coins-for-fruits-ii.py | {
"start": 67,
"end": 788
} | class ____(object):
def minimumCoins(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
dp = [float("inf")]*(len(prices)+1)
dp[0] = 0
dq = collections.deque()
j = 0
for i in xrange(len(prices)):
while dq and dp[dq[-1]]+prices[dq[-1]] >= dp[i]+prices[i]:
dq.pop()
dq.append(i)
while j+(j+1) < i:
assert(len(dq) != 0)
if dq[0] == j:
dq.popleft()
j += 1
dp[i+1] = dp[dq[0]]+prices[dq[0]]
return dp[-1]
# Time: O(nlogn)
# Space: O(n)
# dp, sorted list
from sortedcontainers import SortedList
| Solution |
python | wandb__wandb | wandb/sdk/launch/runner/local_process.py | {
"start": 440,
"end": 2665
} | class ____(AbstractRunner):
"""Runner class, uses a project to create a LocallySubmittedRun.
LocalProcessRunner is very similar to a LocalContainerRunner, except it does not
run the command inside a docker container. Instead, it runs the
command specified as a process directly on the bare metal machine.
"""
async def run( # type: ignore
self,
launch_project: LaunchProject,
*args,
**kwargs,
) -> Optional[AbstractRun]:
if args is not None:
_msg = f"{LOG_PREFIX}LocalProcessRunner.run received unused args {args}"
_logger.warning(_msg)
if kwargs is not None:
_msg = f"{LOG_PREFIX}LocalProcessRunner.run received unused kwargs {kwargs}"
_logger.warning(_msg)
synchronous: bool = self.backend_config[PROJECT_SYNCHRONOUS]
entry_point = (
launch_project.override_entrypoint or launch_project.get_job_entry_point()
)
cmd: List[Any] = []
if launch_project.project_dir is None:
raise LaunchError("Launch LocalProcessRunner received empty project dir")
if launch_project.job:
assert launch_project._job_artifact is not None
try:
validate_wandb_python_deps(
"requirements.frozen.txt",
launch_project.project_dir,
)
except Exception:
wandb.termwarn("Unable to validate python dependencies")
env_vars = launch_project.get_env_vars_dict(
self._api, MAX_ENV_LENGTHS[self.__class__.__name__]
)
for env_key, env_value in env_vars.items():
cmd += [f"{shlex.quote(env_key)}={shlex.quote(env_value)}"]
if entry_point is not None:
cmd += entry_point.command
cmd += launch_project.override_args
command_str = " ".join(cmd).strip()
_msg = f"{LOG_PREFIX}Launching run as a local-process with command {sanitize_wandb_api_key(command_str)}"
wandb.termlog(_msg)
run = _run_entry_point(command_str, launch_project.project_dir)
if synchronous:
await run.wait()
return run
| LocalProcessRunner |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 44657,
"end": 44919
} | class ____(sgqlc.types.Enum):
"""Properties by which enterprise owners can be ordered.
Enumeration Choices:
* `LOGIN`: Order enterprise owners by login.
"""
__schema__ = github_schema
__choices__ = ("LOGIN",)
| OrgEnterpriseOwnerOrderField |
python | astropy__astropy | astropy/units/tests/test_format.py | {
"start": 12472,
"end": 12861
} | class ____(RoundtripBase):
format_ = u_format.VOUnit
@pytest.mark.parametrize(
"unit",
[u for u in u_format.VOUnit._units.values() if not isinstance(u, PrefixUnit)],
ids=str,
)
def test_roundtrip(self, unit):
self.check_roundtrip(unit)
if unit not in (u.mag, u.dB):
self.check_roundtrip_decompose(unit)
| TestRoundtripVOUnit |
python | sympy__sympy | sympy/stats/joint_rv_types.py | {
"start": 26091,
"end": 28364
} | class ____(JointDistribution):
_argnames = ('n', 'p')
is_Continuous=False
is_Discrete = True
@staticmethod
def check(n, p):
_value_check(n > 0,
"number of trials must be a positive integer")
for p_k in p:
_value_check((p_k >= 0, p_k <= 1),
"probability must be in range [0, 1]")
_value_check(Eq(sum(p), 1),
"probabilities must sum to 1")
@property
def set(self):
return Intersection(S.Naturals0, Interval(0, self.n))**len(self.p)
def pdf(self, *x):
n, p = self.n, self.p
term_1 = factorial(n)/Mul.fromiter(factorial(x_k) for x_k in x)
term_2 = Mul.fromiter(p_k**x_k for p_k, x_k in zip(p, x))
return Piecewise((term_1 * term_2, Eq(sum(x), n)), (0, True))
def Multinomial(syms, n, *p):
"""
Creates a discrete random variable with Multinomial Distribution.
The density of the said distribution can be found at [1].
Parameters
==========
n : Positive integer
Represents number of trials
p : List of event probabilities
Must be in the range of $[0, 1]$.
Returns
=======
RandomSymbol
Examples
========
>>> from sympy.stats import density, Multinomial, marginal_distribution
>>> from sympy import symbols
>>> x1, x2, x3 = symbols('x1, x2, x3', nonnegative=True, integer=True)
>>> p1, p2, p3 = symbols('p1, p2, p3', positive=True)
>>> M = Multinomial('M', 3, p1, p2, p3)
>>> density(M)(x1, x2, x3)
Piecewise((6*p1**x1*p2**x2*p3**x3/(factorial(x1)*factorial(x2)*factorial(x3)),
Eq(x1 + x2 + x3, 3)), (0, True))
>>> marginal_distribution(M, M[0])(x1).subs(x1, 1)
3*p1*p2**2 + 6*p1*p2*p3 + 3*p1*p3**2
References
==========
.. [1] https://en.wikipedia.org/wiki/Multinomial_distribution
.. [2] https://mathworld.wolfram.com/MultinomialDistribution.html
"""
if not isinstance(p[0], list):
p = (list(p), )
return multivariate_rv(MultinomialDistribution, syms, n, p[0])
#-------------------------------------------------------------------------------
# Negative Multinomial Distribution --------------------------------------------
| MultinomialDistribution |
python | marshmallow-code__marshmallow | tests/base.py | {
"start": 419,
"end": 544
} | class ____(Enum):
black = "black hair"
brown = "brown hair"
blond = "blond hair"
red = "red hair"
| HairColorEnum |
python | Netflix__metaflow | metaflow/plugins/env_escape/client.py | {
"start": 958,
"end": 25066
} | class ____(object):
def __init__(
self, modules, python_executable, pythonpath, max_pickle_version, config_dir
):
# Wrap with ImportError so that if users are just using the escaped module
# as optional, the typical logic of catching ImportError works properly
try:
self.inner_init(
python_executable, pythonpath, max_pickle_version, config_dir
)
except Exception as e:
# Typically it's one override per config so we just use the first one.
raise ImportError("Error loading module: %s" % str(e), name=modules[0])
def inner_init(self, python_executable, pythonpath, max_pickle_version, config_dir):
# Make sure to init these variables (used in __del__) early on in case we
# have an exception
self._poller = None
self._poller_lock = threading.Lock()
self._active_pid = os.getpid()
self._server_process = None
self._socket_path = None
data_transferer.defaultProtocol = max_pickle_version
self._config_dir = config_dir
server_path, server_config = os.path.split(config_dir)
# The client launches the server when created; we use
# Unix sockets for now
server_module = ".".join([__package__, "server"])
self._socket_path = "/tmp/%s_%d" % (server_config, self._active_pid)
if os.path.exists(self._socket_path):
raise RuntimeError("Existing socket: %s" % self._socket_path)
env = os.environ.copy()
env["PYTHONPATH"] = pythonpath
# When coming from a conda environment, LD_LIBRARY_PATH may be set to
# first include the Conda environment's library. When breaking out to
# the underlying python, we need to reset it to the original LD_LIBRARY_PATH
ld_lib_path = env.get("LD_LIBRARY_PATH")
orig_ld_lib_path = env.get("MF_ORIG_LD_LIBRARY_PATH")
if ld_lib_path is not None and orig_ld_lib_path is not None:
env["LD_LIBRARY_PATH"] = orig_ld_lib_path
if orig_ld_lib_path is not None:
del env["MF_ORIG_LD_LIBRARY_PATH"]
self._server_process = Popen(
[
python_executable,
"-u",
"-m",
server_module,
str(max_pickle_version),
server_config,
self._socket_path,
],
cwd=server_path,
env=env,
stdout=PIPE,
stderr=PIPE,
bufsize=1,
universal_newlines=True, # Forces text as well
)
# Read override configuration
# We can't just import the "overrides" module because that does not
# distinguish it from other modules named "overrides" (either a third party
# lib -- there is one -- or just other escaped modules). We therefore load
# a fuller path to distinguish them from one another.
# This is a bit tricky though:
# - it requires all `configurations` directories to NOT have a __init__.py
# so that configurations can be loaded through extensions too. If this is
# not the case, we will have a `configurations` module that will be registered
# and not be a proper namespace package
# - we want to import a specific file so we:
# - set a prefix that is specific enough to NOT include anything outside
# of the configuration so we end the prefix with "env_escape" (we know
# that is in the path of all configurations). We could technically go
# up to metaflow or metaflow_extensions BUT this then causes issues with
# the extension mechanism and _resolve_relative_path in plugins (because
# there are files loaded from plugins that refer to something outside of
# plugins and if we load plugins and NOT metaflow.plugins, this breaks).
# - set the package root from this prefix to everything up to overrides
# - load the overrides file
#
# This way, we are sure that we are:
# - loading this specific overrides
# - not adding extra stuff to the prefix that we don't care about
# - able to support configurations in both metaflow and extensions at the
# same time
pkg_components = []
prefix, last_basename = os.path.split(config_dir)
while True:
pkg_components.append(last_basename)
possible_prefix, last_basename = os.path.split(prefix)
if last_basename == "env_escape":
break
prefix = possible_prefix
try:
sys.path.insert(0, prefix)
override_module = importlib.import_module(
".overrides", package=".".join(reversed(pkg_components))
)
override_values = override_module.__dict__.values()
except ImportError:
# We ignore so the file can be non-existent if not needed
override_values = []
except Exception as e:
raise RuntimeError(
"Cannot import overrides from '%s': %s" % (sys.path[0], str(e))
)
finally:
sys.path = sys.path[1:]
self._proxied_objects = {}
# Wait for the socket to be up on the other side; we also check if the
# server had issues starting up in which case we report that and crash out
while not os.path.exists(self._socket_path):
returncode = self._server_process.poll()
if returncode is not None:
raise RuntimeError(
"Server did not properly start: %s"
% self._server_process.stderr.read(),
)
time.sleep(1)
# Open up the channel and set up the datatransferer pipeline
self._channel = Channel(SocketByteStream.unixconnect(self._socket_path))
self._datatransferer = DataTransferer(self)
# Make PIPEs non-blocking; this is helpful to be able to
# order the messages properly
for f in (self._server_process.stdout, self._server_process.stderr):
fl = fcntl.fcntl(f, fcntl.F_GETFL)
fcntl.fcntl(f, fcntl.F_SETFL, fl | os.O_NONBLOCK)
# Set up poller
with self._poller_lock:
self._poller = select.poll()
self._poller.register(self._server_process.stdout, select.POLLIN)
self._poller.register(self._server_process.stderr, select.POLLIN)
self._poller.register(self._channel, select.POLLIN | select.POLLHUP)
# Get all exports that we are proxying
response = self._communicate(
{FIELD_MSGTYPE: MSG_CONTROL, FIELD_OPTYPE: CONTROL_GETEXPORTS}
)
self._proxied_classes = {
k: None
for k in itertools.chain(
response[FIELD_CONTENT]["classes"],
response[FIELD_CONTENT]["proxied"],
(e[0] for e in response[FIELD_CONTENT]["exceptions"]),
)
}
self._exception_hierarchy = dict(response[FIELD_CONTENT]["exceptions"])
self._proxied_classnames = set(response[FIELD_CONTENT]["classes"]).union(
response[FIELD_CONTENT]["proxied"]
)
self._aliases = response[FIELD_CONTENT]["aliases"]
# Determine all overrides
self._overrides = {}
self._getattr_overrides = {}
self._setattr_overrides = {}
self._exception_deserializers = {}
for override in override_values:
if isinstance(override, (LocalOverride, LocalAttrOverride)):
for obj_name, obj_funcs in override.obj_mapping.items():
canonical_name = get_canonical_name(obj_name, self._aliases)
if canonical_name not in self._proxied_classes:
raise ValueError(
"%s does not refer to a proxied or override type" % obj_name
)
if isinstance(override, LocalOverride):
override_dict = self._overrides.setdefault(canonical_name, {})
elif override.is_setattr:
override_dict = self._setattr_overrides.setdefault(
canonical_name, {}
)
else:
override_dict = self._getattr_overrides.setdefault(
canonical_name, {}
)
if isinstance(obj_funcs, str):
obj_funcs = (obj_funcs,)
for name in obj_funcs:
if name in override_dict:
raise ValueError(
"%s was already overridden for %s" % (name, obj_name)
)
override_dict[name] = override.func
if isinstance(override, LocalExceptionDeserializer):
canonical_name = get_canonical_name(override.class_path, self._aliases)
if canonical_name not in self._exception_hierarchy:
raise ValueError(
"%s does not refer to an exception type" % override.class_path
)
cur_des = self._exception_deserializers.get(canonical_name, None)
if cur_des is not None:
raise ValueError(
"Exception %s has multiple deserializers" % override.class_path
)
self._exception_deserializers[canonical_name] = override.deserializer
# Proxied standalone functions are functions that are proxied
# as part of other objects like defaultdict for which we create a
# on-the-fly simple class that is just a callable. This is therefore
# a special type of self._proxied_classes
self._proxied_standalone_functions = {}
self._export_info = {
"classes": response[FIELD_CONTENT]["classes"],
"functions": response[FIELD_CONTENT]["functions"],
"values": response[FIELD_CONTENT]["values"],
"exceptions": response[FIELD_CONTENT]["exceptions"],
"aliases": response[FIELD_CONTENT]["aliases"],
}
def __del__(self):
self.cleanup()
def cleanup(self):
# Clean up the server; we drain all messages if any
if self._poller is not None:
# If we have self._poller, we have self._server_process
with self._poller_lock:
self._poller.unregister(self._channel)
last_evts = self._poller.poll(5)
for fd, _ in last_evts:
# Readlines will never block here because `bufsize` is set to
# 1 (line buffering)
if fd == self._server_process.stdout.fileno():
sys.stdout.write(self._server_process.stdout.readline())
elif fd == self._server_process.stderr.fileno():
sys.stderr.write(self._server_process.stderr.readline())
sys.stdout.flush()
sys.stderr.flush()
self._poller = None
if self._server_process is not None:
# Attempt to send it a terminate signal and then wait and kill
try:
self._channel.send(
{FIELD_MSGTYPE: MSG_CONTROL, FIELD_OPTYPE: CONTROL_SHUTDOWN}
)
self._channel.recv(timeout=10) # If we receive, we are sure we
# are good
except: # noqa E722
pass # If there is any issue sending this message, just ignore it
self._server_process.kill()
self._server_process = None
if self._socket_path is not None and os.path.exists(self._socket_path):
os.unlink(self._socket_path)
self._socket_path = None
@property
def name(self):
return self._config_dir
def get_exports(self):
return self._export_info
def get_exception_deserializer(self, name):
cannonical_name = get_canonical_name(name, self._aliases)
return self._exception_deserializers.get(cannonical_name)
def stub_request(self, stub, request_type, *args, **kwargs):
# Encode the operation to send over the wire and wait for the response
target = self.encode(stub)
encoded_args = []
for arg in args:
encoded_args.append(self.encode(arg))
encoded_kwargs = []
for k, v in kwargs.items():
encoded_kwargs.append((self.encode(k), self.encode(v)))
response = self._communicate(
{
FIELD_MSGTYPE: MSG_OP,
FIELD_OPTYPE: request_type,
FIELD_TARGET: target,
FIELD_ARGS: self.encode(args),
FIELD_KWARGS: self.encode([(k, v) for k, v in kwargs.items()]),
}
)
response_type = response[FIELD_MSGTYPE]
if response_type == MSG_REPLY:
return self.decode(response[FIELD_CONTENT])
elif response_type == MSG_EXCEPTION:
raise load_exception(self, response[FIELD_CONTENT])
elif response_type == MSG_INTERNAL_ERROR:
raise RuntimeError(
"Error in the server runtime:\n\n===== SERVER TRACEBACK =====\n%s"
% response[FIELD_CONTENT]
)
def encode(self, obj):
# This encodes an object to transfer back out
# Basic data types will be sent over directly.
# In this direction (client -> server), we error on non-basic
# types. This could be changed by modifying the pickle_object method
# here.
return self._datatransferer.dump(obj)
def decode(self, json_obj):
# This decodes an object that was transferred in. This will call
# unpickle_object where needed. Any remote object that is handled by
# this connection will be converted to a local stub.
return self._datatransferer.load(json_obj)
def get_local_class(
self, name, obj_id=None, is_returned_exception=False, is_parent=False
):
# Gets (and creates if needed), the class mapping to the remote
# class of name 'name'.
# We actually deal with four types of classes:
# - proxied functions
# - classes that are proxied regular classes AND proxied exceptions
# - classes that are proxied regular classes AND NOT proxied exceptions
# - classes that are NOT proxied regular classes AND are proxied exceptions
name = get_canonical_name(name, self._aliases)
def name_to_parent_name(name):
return "parent:%s" % name
if is_parent:
lookup_name = name_to_parent_name(name)
else:
lookup_name = name
if name == "function":
# Special handling of pickled functions. We create a new class that
# simply has a __call__ method that will forward things back to
# the server side.
if obj_id is None:
raise RuntimeError("Local function unpickling without an object ID")
if obj_id not in self._proxied_standalone_functions:
self._proxied_standalone_functions[obj_id] = create_class(
self,
"__main__.__function_%s" % obj_id,
{},
{},
{},
{"__call__": ""},
[],
)
return self._proxied_standalone_functions[obj_id]
local_class = self._proxied_classes.get(lookup_name, None)
if local_class is not None:
return local_class
is_proxied_exception = name in self._exception_hierarchy
is_proxied_non_exception = name in self._proxied_classnames
if not is_proxied_exception and not is_proxied_non_exception:
if is_returned_exception or is_parent:
# In this case, it may be a local exception that we need to
# recreate
try:
ex_module, ex_name = name.rsplit(".", 1)
__import__(ex_module, None, None, "*")
except Exception:
pass
if ex_module in sys.modules and issubclass(
getattr(sys.modules[ex_module], ex_name), BaseException
):
# This is a local exception that we can recreate
local_exception = getattr(sys.modules[ex_module], ex_name)
wrapped_exception = ExceptionMetaClass(
ex_name,
(local_exception,),
dict(getattr(local_exception, "__dict__", {})),
)
wrapped_exception.__module__ = ex_module
self._proxied_classes[lookup_name] = wrapped_exception
return wrapped_exception
raise ValueError("Class '%s' is not known" % name)
# At this stage:
# - we don't have a local_class for this
# - it is not an inbuilt exception so it is either a proxied exception, a
# proxied class or a proxied object that is both an exception and a class.
parents = []
if is_proxied_exception:
# If exception, we need to get the parents from the exception
ex_parents = self._exception_hierarchy[name]
for parent in ex_parents:
# We always consider it to be an exception so that we wrap even non
# proxied builtins exceptions
parents.append(self.get_local_class(parent, is_parent=True))
# For regular classes, we get what it exposes from the server
if is_proxied_non_exception:
remote_methods = self.stub_request(None, OP_GETMETHODS, name)
else:
remote_methods = {}
parent_local_class = None
local_class = None
if is_proxied_exception:
# If we are a proxied exception AND a proxied class, we create two classes:
# actually:
# - the class itself (which is a stub)
# - the class in the capacity of a parent class (to another exception
# presumably). The reason for this is that if we have an exception/proxied
# class A and another B and B inherits from A, the MRO order would be all
# wrong since both A and B would also inherit from `Stub`. Here what we
# do is:
# - A_parent inherits from the actual parents of A (let's assume a
# builtin exception)
# - A inherits from (Stub, A_parent)
# - B_parent inherits from A_parent and the builtin Exception
# - B inherits from (Stub, B_parent)
ex_module, ex_name = name.rsplit(".", 1)
parent_local_class = ExceptionMetaClass(ex_name, (*parents,), {})
parent_local_class.__module__ = ex_module
if is_proxied_non_exception:
local_class = create_class(
self,
name,
self._overrides.get(name, {}),
self._getattr_overrides.get(name, {}),
self._setattr_overrides.get(name, {}),
remote_methods,
(parent_local_class,) if parent_local_class else None,
)
if parent_local_class:
self._proxied_classes[name_to_parent_name(name)] = parent_local_class
if local_class:
self._proxied_classes[name] = local_class
else:
# This is for the case of pure proxied exceptions -- we want the lookup of
# foo.MyException to be the same class as looking of foo.MyException as a parent
# of another exception so `isinstance` works properly
self._proxied_classes[name] = parent_local_class
if is_parent:
# This should never happen but making sure
if not parent_local_class:
raise RuntimeError(
"Exception parent class %s is not a proxied exception" % name
)
return parent_local_class
return self._proxied_classes[name]
def can_pickle(self, obj):
return getattr(obj, "___connection___", None) == self
def pickle_object(self, obj):
# This function is called to pickle obj to be transferred back to the
# server. In this direction, we only allow objects that already exist
# on the remote side so if this is not a stub, we do not allow it to be
# transferred
if getattr(obj, "___connection___", None) == self:
# This is something we can transfer over
return ObjReference(
VALUE_LOCAL, obj.___remote_class_name___, obj.___identifier___
)
raise ValueError(
"Cannot send object of type %s from client to server" % type(obj)
)
def unpickle_object(self, obj):
# This function is called when the server sends a remote reference.
# We create a local stub for it locally
if (not isinstance(obj, ObjReference)) or obj.value_type != VALUE_REMOTE:
raise ValueError("Invalid transferred object: %s" % str(obj))
remote_class_name = obj.class_name
obj_id = obj.identifier
local_instance = self._proxied_objects.get(obj_id)
if not local_instance:
local_class = self.get_local_class(remote_class_name, obj_id=obj_id)
local_instance = local_class(self, remote_class_name, obj_id)
return local_instance
def _communicate(self, msg):
if os.getpid() != self._active_pid:
raise RuntimeError(
"You cannot use the environment escape across process boundaries."
)
# We also disable the GC because in some rare cases, it may try to delete
# a remote object while we are communicating which will cause a deadlock
try:
gc.disable()
with self._poller_lock:
return self._locked_communicate(msg)
finally:
gc.enable()
def _locked_communicate(self, msg):
self._channel.send(msg)
response_ready = False
while not response_ready:
evt_list = self._poller.poll()
for fd, _ in evt_list:
if fd == self._channel.fileno():
# We deal with this last as this basically gives us the
# response, so we stop looking at things on stdout/stderr
response_ready = True
# Readlines will never block here because `bufsize` is set to 1
# (line buffering)
elif fd == self._server_process.stdout.fileno():
sys.stdout.write(self._server_process.stdout.readline())
elif fd == self._server_process.stderr.fileno():
sys.stderr.write(self._server_process.stderr.readline())
# We make sure there is nothing left to read. On the server side a
# flush happens before we respond, so we read until we get an exception;
# this is non-blocking
while True:
try:
line = self._server_process.stdout.readline()
if not line:
break
sys.stdout.write(line)
except (OSError, TypeError):
break
while True:
try:
line = self._server_process.stderr.readline()
if not line:
break
sys.stderr.write(line)
except (OSError, TypeError):
break
sys.stdout.flush()
sys.stderr.flush()
return self._channel.recv()
| Client |
python | kamyu104__LeetCode-Solutions | Python/find-the-k-th-character-in-string-game-i.py | {
"start": 40,
"end": 273
} | class ____(object):
def kthCharacter(self, k):
"""
:type k: int
:rtype: str
"""
def popcount(x):
return bin(x)[2:].count('1')
return chr(ord('a')+popcount(k-1)%26)
| Solution |
python | kamyu104__LeetCode-Solutions | Python/step-by-step-directions-from-a-binary-tree-node-to-another.py | {
"start": 1515,
"end": 2307
} | class ____(object):
def getDirections(self, root, startValue, destValue):
"""
:type root: Optional[TreeNode]
:type startValue: int
:type destValue: int
:rtype: str
"""
def dfs(node, val, path):
if node.val == val:
return True
if node.left and dfs(node.left, val, path):
path.append('L')
elif node.right and dfs(node.right, val, path):
path.append('R')
return path
src, dst = [], []
dfs(root, startValue, src)
dfs(root, destValue, dst)
while len(src) and len(dst) and src[-1] == dst[-1]:
src.pop()
dst.pop()
dst.reverse()
return "".join(['U']*len(src) + dst)
| Solution2 |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-slack/components.py | {
"start": 3401,
"end": 3792
} | class ____(DpathExtractor):
"""
Transform response from a list of strings to list dicts:
from: ['aa', 'bb']
to: [{'member_id': 'aa'}, {{'member_id': 'bb'}]
"""
def extract_records(self, response: requests.Response) -> List[Record]:
records = super().extract_records(response)
return [{"member_id": record} for record in records]
| ChannelMembersExtractor |
python | tornadoweb__tornado | tornado/ioloop.py | {
"start": 1701,
"end": 1876
} | class ____(Protocol):
def fileno(self) -> int:
pass
def close(self) -> None:
pass
_T = TypeVar("_T")
_S = TypeVar("_S", bound=_Selectable)
| _Selectable |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events.py | {
"start": 235297,
"end": 239152
} | class ____(OrganizationEventsEndpointTestBase):
@mock.patch("sentry.search.events.builder.base.raw_snql_query")
def test_profiles_dataset_simple(self, mock_snql_query: mock.MagicMock) -> None:
mock_snql_query.side_effect = [
{
"data": [
{
"project": self.project.id,
"transaction": "foo",
"last_seen": "2022-10-20T16:41:22+00:00",
"latest_event": "a" * 32,
"count": 1,
"count_unique_transaction": 1,
"percentile_profile_duration_0_25": 1,
"p50_profile_duration": 1,
"p75_profile_duration": 1,
"p95_profile_duration": 1,
"p99_profile_duration": 1,
"p100_profile_duration": 1,
"min_profile_duration": 1,
"max_profile_duration": 1,
"avg_profile_duration": 1,
"sum_profile_duration": 1,
},
],
"meta": [
{
"name": "project",
"type": "UInt64",
},
{
"name": "transaction",
"type": "LowCardinality(String)",
},
{
"name": "last_seen",
"type": "DateTime",
},
{
"name": "latest_event",
"type": "String",
},
{
"name": "count",
"type": "UInt64",
},
{
"name": "count_unique_transaction",
"type": "UInt64",
},
{
"name": "percentile_profile_duration_0_25",
"type": "Float64",
},
*[
{
"name": f"{fn}_profile_duration",
"type": "Float64",
}
for fn in ["p50", "p75", "p95", "p99", "p100", "min", "max", "avg", "sum"]
],
],
},
]
fields = [
"project",
"transaction",
"last_seen()",
"latest_event()",
"count()",
"count_unique(transaction)",
"percentile(profile.duration, 0.25)",
"p50(profile.duration)",
"p75(profile.duration)",
"p95(profile.duration)",
"p99(profile.duration)",
"p100(profile.duration)",
"min(profile.duration)",
"max(profile.duration)",
"avg(profile.duration)",
"sum(profile.duration)",
]
query = {
"field": fields,
"project": [self.project.id],
"dataset": "profiles",
}
response = self.do_request(query, features={"organizations:profiling": True})
assert response.status_code == 200, response.content
# making sure the response keys are in the form we expect and not aliased
data_keys = {key for row in response.data["data"] for key in row}
field_keys = {key for key in response.data["meta"]["fields"]}
unit_keys = {key for key in response.data["meta"]["units"]}
assert set(fields) == data_keys
assert set(fields) == field_keys
assert set(fields) == unit_keys
| OrganizationEventsProfilesDatasetEndpointTest |
python | getsentry__sentry | src/sentry/similarity/backends/metrics.py | {
"start": 110,
"end": 1767
} | class ____(AbstractIndexBackend):
def __init__(self, backend, template="similarity.{}", scope_tag_name="scope"):
self.backend = backend
self.template = template
self.scope_tag_name = scope_tag_name
def __getattr__(self, name):
return getattr(self.backend, name)
def __instrumented_method_call(self, method, scope, *args, **kwargs):
tags = {}
if self.scope_tag_name is not None:
tags[self.scope_tag_name] = scope
with timer(self.template.format(method), tags=tags):
return getattr(self.backend, method)(scope, *args, **kwargs)
def record(self, *args, **kwargs):
return self.__instrumented_method_call("record", *args, **kwargs)
def classify(self, *args, **kwargs):
return self.__instrumented_method_call("classify", *args, **kwargs)
def compare(self, *args, **kwargs):
return self.__instrumented_method_call("compare", *args, **kwargs)
def merge(self, *args, **kwargs):
return self.__instrumented_method_call("merge", *args, **kwargs)
def delete(self, *args, **kwargs):
return self.__instrumented_method_call("delete", *args, **kwargs)
def scan(self, *args, **kwargs):
return self.__instrumented_method_call("scan", *args, **kwargs)
def flush(self, *args, **kwargs):
return self.__instrumented_method_call("flush", *args, **kwargs)
def export(self, *args, **kwargs):
return self.__instrumented_method_call("export", *args, **kwargs)
def import_(self, *args, **kwargs):
return self.__instrumented_method_call("import_", *args, **kwargs)
| MetricsWrapper |
python | kubernetes-client__python | kubernetes/client/models/v1alpha3_device_selector.py | {
"start": 383,
"end": 3394
} | 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 = {
'cel': 'V1alpha3CELDeviceSelector'
}
attribute_map = {
'cel': 'cel'
}
def __init__(self, cel=None, local_vars_configuration=None): # noqa: E501
"""V1alpha3DeviceSelector - 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._cel = None
self.discriminator = None
if cel is not None:
self.cel = cel
@property
def cel(self):
"""Gets the cel of this V1alpha3DeviceSelector. # noqa: E501
:return: The cel of this V1alpha3DeviceSelector. # noqa: E501
:rtype: V1alpha3CELDeviceSelector
"""
return self._cel
@cel.setter
def cel(self, cel):
"""Sets the cel of this V1alpha3DeviceSelector.
:param cel: The cel of this V1alpha3DeviceSelector. # noqa: E501
:type: V1alpha3CELDeviceSelector
"""
self._cel = cel
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, V1alpha3DeviceSelector):
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, V1alpha3DeviceSelector):
return True
return self.to_dict() != other.to_dict()
| V1alpha3DeviceSelector |
python | scikit-learn__scikit-learn | sklearn/feature_extraction/_dict_vectorizer.py | {
"start": 438,
"end": 16022
} | class ____(TransformerMixin, BaseEstimator):
"""Transforms lists of feature-value mappings to vectors.
This transformer turns lists of mappings (dict-like objects) of feature
names to feature values into Numpy arrays or scipy.sparse matrices for use
with scikit-learn estimators.
When feature values are strings, this transformer will do a binary one-hot
(aka one-of-K) coding: one boolean-valued feature is constructed for each
of the possible string values that the feature can take on. For instance,
a feature "f" that can take on the values "ham" and "spam" will become two
features in the output, one signifying "f=ham", the other "f=spam".
If a feature value is a sequence or set of strings, this transformer
will iterate over the values and will count the occurrences of each string
value.
However, note that this transformer will only do a binary one-hot encoding
when feature values are of type string. If categorical features are
represented as numeric values such as int or iterables of strings, the
DictVectorizer can be followed by
:class:`~sklearn.preprocessing.OneHotEncoder` to complete
binary one-hot encoding.
Features that do not occur in a sample (mapping) will have a zero value
in the resulting array/matrix.
For an efficiency comparison of the different feature extractors, see
:ref:`sphx_glr_auto_examples_text_plot_hashing_vs_dict_vectorizer.py`.
Read more in the :ref:`User Guide <dict_feature_extraction>`.
Parameters
----------
dtype : dtype, default=np.float64
The type of feature values. Passed to Numpy array/scipy.sparse matrix
constructors as the dtype argument.
separator : str, default="="
Separator string used when constructing new features for one-hot
coding.
sparse : bool, default=True
Whether transform should produce scipy.sparse matrices.
sort : bool, default=True
Whether ``feature_names_`` and ``vocabulary_`` should be
sorted when fitting.
Attributes
----------
vocabulary_ : dict
A dictionary mapping feature names to feature indices.
feature_names_ : list
A list of length n_features containing the feature names (e.g., "f=ham"
and "f=spam").
See Also
--------
FeatureHasher : Performs vectorization using only a hash function.
sklearn.preprocessing.OrdinalEncoder : Handles nominal/categorical
features encoded as columns of arbitrary data types.
Examples
--------
>>> from sklearn.feature_extraction import DictVectorizer
>>> v = DictVectorizer(sparse=False)
>>> D = [{'foo': 1, 'bar': 2}, {'foo': 3, 'baz': 1}]
>>> X = v.fit_transform(D)
>>> X
array([[2., 0., 1.],
[0., 1., 3.]])
>>> v.inverse_transform(X) == [{'bar': 2.0, 'foo': 1.0},
... {'baz': 1.0, 'foo': 3.0}]
True
>>> v.transform({'foo': 4, 'unseen_feature': 3})
array([[0., 0., 4.]])
"""
# This isn't something that people should be routing / using in a pipeline.
__metadata_request__inverse_transform = {"dict_type": metadata_routing.UNUSED}
_parameter_constraints: dict = {
"dtype": "no_validation", # validation delegated to numpy,
"separator": [str],
"sparse": ["boolean"],
"sort": ["boolean"],
}
def __init__(self, *, dtype=np.float64, separator="=", sparse=True, sort=True):
self.dtype = dtype
self.separator = separator
self.sparse = sparse
self.sort = sort
def _add_iterable_element(
self,
f,
v,
feature_names,
vocab,
*,
fitting=True,
transforming=False,
indices=None,
values=None,
):
"""Add feature names for iterable of strings"""
for vv in v:
if isinstance(vv, str):
feature_name = "%s%s%s" % (f, self.separator, vv)
vv = 1
else:
raise TypeError(
f"Unsupported type {type(vv)} in iterable "
"value. Only iterables of string are "
"supported."
)
if fitting and feature_name not in vocab:
vocab[feature_name] = len(feature_names)
feature_names.append(feature_name)
if transforming and feature_name in vocab:
indices.append(vocab[feature_name])
values.append(self.dtype(vv))
@_fit_context(prefer_skip_nested_validation=True)
def fit(self, X, y=None):
"""Learn a list of feature name -> indices mappings.
Parameters
----------
X : Mapping or iterable over Mappings
Dict(s) or Mapping(s) from feature names (arbitrary Python
objects) to feature values (strings or convertible to dtype).
.. versionchanged:: 0.24
Accepts multiple string values for one categorical feature.
y : (ignored)
Ignored parameter.
Returns
-------
self : object
DictVectorizer class instance.
"""
feature_names = []
vocab = {}
for x in X:
for f, v in x.items():
if isinstance(v, str):
feature_name = "%s%s%s" % (f, self.separator, v)
elif isinstance(v, Number) or (v is None):
feature_name = f
elif isinstance(v, Mapping):
raise TypeError(
f"Unsupported value type {type(v)} "
f"for {f}: {v}.\n"
"Mapping objects are not supported."
)
elif isinstance(v, Iterable):
feature_name = None
self._add_iterable_element(f, v, feature_names, vocab)
if feature_name is not None:
if feature_name not in vocab:
vocab[feature_name] = len(feature_names)
feature_names.append(feature_name)
if self.sort:
feature_names.sort()
vocab = {f: i for i, f in enumerate(feature_names)}
self.feature_names_ = feature_names
self.vocabulary_ = vocab
return self
def _transform(self, X, fitting):
# Sanity check: Python's array has no way of explicitly requesting the
# signed 32-bit integers that scipy.sparse needs, so we use the next
# best thing: typecode "i" (int). However, if that gives larger or
# smaller integers than 32-bit ones, np.frombuffer screws up.
assert array("i").itemsize == 4, (
"sizeof(int) != 4 on your platform; please report this at"
" https://github.com/scikit-learn/scikit-learn/issues and"
" include the output from platform.platform() in your bug report"
)
dtype = self.dtype
if fitting:
feature_names = []
vocab = {}
else:
feature_names = self.feature_names_
vocab = self.vocabulary_
transforming = True
# Process everything as sparse regardless of setting
X = [X] if isinstance(X, Mapping) else X
indices = array("i")
indptr = [0]
# XXX we could change values to an array.array as well, but it
# would require (heuristic) conversion of dtype to typecode...
values = []
# collect all the possible feature names and build sparse matrix at
# same time
for x in X:
for f, v in x.items():
if isinstance(v, str):
feature_name = "%s%s%s" % (f, self.separator, v)
v = 1
elif isinstance(v, Number) or (v is None):
feature_name = f
elif not isinstance(v, Mapping) and isinstance(v, Iterable):
feature_name = None
self._add_iterable_element(
f,
v,
feature_names,
vocab,
fitting=fitting,
transforming=transforming,
indices=indices,
values=values,
)
else:
raise TypeError(
f"Unsupported value Type {type(v)} "
f"for {f}: {v}.\n"
f"{type(v)} objects are not supported."
)
if feature_name is not None:
if fitting and feature_name not in vocab:
vocab[feature_name] = len(feature_names)
feature_names.append(feature_name)
if feature_name in vocab:
indices.append(vocab[feature_name])
values.append(self.dtype(v))
indptr.append(len(indices))
if len(indptr) == 1:
raise ValueError("Sample sequence X is empty.")
indices = np.frombuffer(indices, dtype=np.intc)
shape = (len(indptr) - 1, len(vocab))
result_matrix = sp.csr_matrix(
(values, indices, indptr), shape=shape, dtype=dtype
)
# Sort everything if asked
if fitting and self.sort:
feature_names.sort()
map_index = np.empty(len(feature_names), dtype=np.int32)
for new_val, f in enumerate(feature_names):
map_index[new_val] = vocab[f]
vocab[f] = new_val
result_matrix = result_matrix[:, map_index]
if self.sparse:
result_matrix.sort_indices()
else:
result_matrix = result_matrix.toarray()
if fitting:
self.feature_names_ = feature_names
self.vocabulary_ = vocab
return result_matrix
@_fit_context(prefer_skip_nested_validation=True)
def fit_transform(self, X, y=None):
"""Learn a list of feature name -> indices mappings and transform X.
Like fit(X) followed by transform(X), but does not require
materializing X in memory.
Parameters
----------
X : Mapping or iterable over Mappings
Dict(s) or Mapping(s) from feature names (arbitrary Python
objects) to feature values (strings or convertible to dtype).
.. versionchanged:: 0.24
Accepts multiple string values for one categorical feature.
y : (ignored)
Ignored parameter.
Returns
-------
Xa : {array, sparse matrix}
Feature vectors; always 2-d.
"""
return self._transform(X, fitting=True)
def inverse_transform(self, X, dict_type=dict):
"""Transform array or sparse matrix X back to feature mappings.
X must have been produced by this DictVectorizer's transform or
fit_transform method; it may only have passed through transformers
that preserve the number of features and their order.
In the case of one-hot/one-of-K coding, the constructed feature
names and values are returned rather than the original ones.
Parameters
----------
X : {array-like, sparse matrix} of shape (n_samples, n_features)
Sample matrix.
dict_type : type, default=dict
Constructor for feature mappings. Must conform to the
collections.Mapping API.
Returns
-------
X_original : list of dict_type objects of shape (n_samples,)
Feature mappings for the samples in X.
"""
check_is_fitted(self, "feature_names_")
# COO matrix is not subscriptable
X = check_array(X, accept_sparse=["csr", "csc"])
n_samples = X.shape[0]
names = self.feature_names_
dicts = [dict_type() for _ in range(n_samples)]
if sp.issparse(X):
for i, j in zip(*X.nonzero()):
dicts[i][names[j]] = X[i, j]
else:
for i, d in enumerate(dicts):
for j, v in enumerate(X[i, :]):
if v != 0:
d[names[j]] = X[i, j]
return dicts
def transform(self, X):
"""Transform feature->value dicts to array or sparse matrix.
Named features not encountered during fit or fit_transform will be
silently ignored.
Parameters
----------
X : Mapping or iterable over Mappings of shape (n_samples,)
Dict(s) or Mapping(s) from feature names (arbitrary Python
objects) to feature values (strings or convertible to dtype).
Returns
-------
Xa : {array, sparse matrix}
Feature vectors; always 2-d.
"""
check_is_fitted(self, ["feature_names_", "vocabulary_"])
return self._transform(X, fitting=False)
def get_feature_names_out(self, input_features=None):
"""Get output feature names for transformation.
Parameters
----------
input_features : array-like of str or None, default=None
Not used, present here for API consistency by convention.
Returns
-------
feature_names_out : ndarray of str objects
Transformed feature names.
"""
check_is_fitted(self, "feature_names_")
if any(not isinstance(name, str) for name in self.feature_names_):
feature_names = [str(name) for name in self.feature_names_]
else:
feature_names = self.feature_names_
return np.asarray(feature_names, dtype=object)
def restrict(self, support, indices=False):
"""Restrict the features to those in support using feature selection.
This function modifies the estimator in-place.
Parameters
----------
support : array-like
Boolean mask or list of indices (as returned by the get_support
member of feature selectors).
indices : bool, default=False
Whether support is a list of indices.
Returns
-------
self : object
DictVectorizer class instance.
Examples
--------
>>> from sklearn.feature_extraction import DictVectorizer
>>> from sklearn.feature_selection import SelectKBest, chi2
>>> v = DictVectorizer()
>>> D = [{'foo': 1, 'bar': 2}, {'foo': 3, 'baz': 1}]
>>> X = v.fit_transform(D)
>>> support = SelectKBest(chi2, k=2).fit(X, [0, 1])
>>> v.get_feature_names_out()
array(['bar', 'baz', 'foo'], ...)
>>> v.restrict(support.get_support())
DictVectorizer()
>>> v.get_feature_names_out()
array(['bar', 'foo'], ...)
"""
check_is_fitted(self, "feature_names_")
if not indices:
support = np.where(support)[0]
names = self.feature_names_
new_vocab = {}
for i in support:
new_vocab[names[i]] = len(new_vocab)
self.vocabulary_ = new_vocab
self.feature_names_ = [
f for f, i in sorted(new_vocab.items(), key=itemgetter(1))
]
return self
def __sklearn_tags__(self):
tags = super().__sklearn_tags__()
tags.input_tags.dict = True
tags.input_tags.two_d_array = False
return tags
| DictVectorizer |
python | walkccc__LeetCode | solutions/781. Rabbits in Forest/781.py | {
"start": 0,
"end": 252
} | class ____:
def numRabbits(self, answers: list[int]) -> int:
ans = 0
count = collections.Counter()
for answer in answers:
if count[answer] % (answer + 1) == 0:
ans += answer + 1
count[answer] += 1
return ans
| Solution |
python | falconry__falcon | tests/test_sinks.py | {
"start": 149,
"end": 339
} | class ____:
def __init__(self):
self._proxy = Proxy()
def __call__(self, req, resp, **kwargs):
resp.status = self._proxy.forward(req)
self.kwargs = kwargs
| Sink |
python | getsentry__sentry | src/sentry/analytics/events/repo_linked.py | {
"start": 68,
"end": 268
} | class ____(analytics.Event):
user_id: int | None = None
default_user_id: int
organization_id: int
repository_id: int
provider: str
analytics.register(RepoLinkedEvent)
| RepoLinkedEvent |
python | kamyu104__LeetCode-Solutions | Python/sequential-digits.py | {
"start": 78,
"end": 560
} | class ____(object):
def sequentialDigits(self, low, high):
"""
:type low: int
:type high: int
:rtype: List[int]
"""
result = []
q = collections.deque(range(1, 9))
while q:
num = q.popleft()
if num > high:
continue
if low <= num:
result.append(num)
if num%10+1 < 10:
q.append(num*10+num%10+1)
return result
| Solution |
python | scipy__scipy | scipy/sparse/tests/test_base.py | {
"start": 221658,
"end": 221727
} | class ____(_NonCanonicalCSMixin, TestCSC):
pass
| TestCSCNonCanonical |
python | dask__dask | dask/dataframe/dask_expr/_cumulative.py | {
"start": 326,
"end": 1185
} | class ____(Expr):
_parameters = ["frame", "axis", "skipna"]
_defaults = {"axis": None}
chunk_operation = None
aggregate_operation: Callable | None = None
neutral_element: int | None = None
def _divisions(self):
return self.frame._divisions()
@functools.cached_property
def _meta(self):
return self.frame._meta
def _lower(self):
chunks = CumulativeBlockwise(
self.frame, self.axis, self.skipna, self.chunk_operation
)
chunks_last = TakeLast(chunks, self.skipna)
return CumulativeFinalize(
chunks, chunks_last, self.aggregate_operation, self.neutral_element
)
def _simplify_up(self, parent, dependents):
if isinstance(parent, Projection):
return plain_column_projection(self, parent, dependents)
| CumulativeAggregations |
python | cython__cython | Cython/Plex/Regexps.py | {
"start": 2237,
"end": 5118
} | class ____:
"""RE is the base class for regular expression constructors.
The following operators are defined on REs:
re1 + re2 is an RE which matches |re1| followed by |re2|
re1 | re2 is an RE which matches either |re1| or |re2|
"""
nullable = 1 # True if this RE can match 0 input symbols
match_nl = 1 # True if this RE can match a string ending with '\n'
str = None # Set to a string to override the class's __str__ result
def build_machine(self, machine, initial_state, final_state,
match_bol, nocase):
"""
This method should add states to |machine| to implement this
RE, starting at |initial_state| and ending at |final_state|.
If |match_bol| is true, the RE must be able to match at the
beginning of a line. If nocase is true, upper and lower case
letters should be treated as equivalent.
"""
raise NotImplementedError("%s.build_machine not implemented" %
self.__class__.__name__)
def build_opt(self, m, initial_state, c):
"""
Given a state |s| of machine |m|, return a new state
reachable from |s| on character |c| or epsilon.
"""
s = m.new_state()
initial_state.link_to(s)
initial_state.add_transition(c, s)
return s
def __add__(self, other):
return Seq(self, other)
def __or__(self, other):
return Alt(self, other)
def __str__(self):
if self.str:
return self.str
else:
return self.calc_str()
def check_re(self, num, value):
if not isinstance(value, RE):
self.wrong_type(num, value, "Plex.RE instance")
def check_string(self, num, value):
if type(value) is not str:
self.wrong_type(num, value, "string")
def check_char(self, num, value):
self.check_string(num, value)
if len(value) != 1:
raise Errors.PlexValueError("Invalid value for argument %d of Plex.%s."
"Expected a string of length 1, got: %s" % (
num, self.__class__.__name__, repr(value)))
def wrong_type(self, num, value, expected):
raise Errors.PlexTypeError(
f"Invalid type for argument {num:d} of {self.__class__.__qualname__} "
f"(expected {expected}, got {type(value).__name__}"
)
#
# Primitive RE constructors
# -------------------------
#
# These are the basic REs from which all others are built.
#
def Char(c):
"""
Char(c) is an RE which matches the character |c|.
"""
if len(c) == 1:
result = CodeRange(ord(c), ord(c) + 1)
else:
result = SpecialSymbol(c)
result.str = "Char(%s)" % repr(c)
return result
| RE |
python | skorch-dev__skorch | skorch/exceptions.py | {
"start": 474,
"end": 541
} | class ____(UserWarning):
"""Base skorch warning."""
| SkorchWarning |
python | pytorch__pytorch | torch/_inductor/index_propagation.py | {
"start": 1629,
"end": 2396
} | class ____:
"""A SymPy expression with associated type"""
expr: _ExprType
dtype: torch.dtype
def is_constant(self):
return _is_constant(self.expr)
def __post_init__(self):
if _is_constant(self.expr):
expr = self.expr
if isinstance(expr, sympy.Expr):
expr = expr.expand(identity=True)
expr = dtype_to_type(self.dtype)(expr)
if is_integer_dtype(self.dtype):
bits = torch.iinfo(self.dtype).bits
if self.dtype.is_signed:
expr = expr + 2 ** (bits - 1)
expr = expr % 2**bits
if self.dtype.is_signed:
expr = expr - 2 ** (bits - 1)
self.expr = expr
| TypedExpr |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 112819,
"end": 112961
} | class ____(MaybeAlignPartitions):
_parameters = ["frame", "other", "join", "axis", "fill_value"]
_expr_cls = _Align
| AlignAlignPartitions |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 1044115,
"end": 1044676
} | class ____(sgqlc.types.Type, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("actor", "block_duration", "created_at", "subject")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
block_duration = sgqlc.types.Field(
sgqlc.types.non_null(UserBlockDuration), graphql_name="blockDuration"
)
created_at = sgqlc.types.Field(
sgqlc.types.non_null(DateTime), graphql_name="createdAt"
)
subject = sgqlc.types.Field(User, graphql_name="subject")
| UserBlockedEvent |
python | astropy__astropy | astropy/io/fits/tests/test_core.py | {
"start": 976,
"end": 20244
} | class ____(FitsTestCase):
def test_missing_file(self):
with pytest.raises(OSError):
fits.open(self.temp("does-not-exist.fits"))
def test_naxisj_check(self):
with fits.open(self.data("o4sp040b0_raw.fits")) as hdulist:
hdulist[1].header["NAXIS3"] = 500
assert "NAXIS3" in hdulist[1].header
hdulist.verify("silentfix")
assert "NAXIS3" not in hdulist[1].header
def test_byteswap(self):
p = fits.PrimaryHDU()
lst = fits.HDUList()
n = np.array([1, 60000, 0], dtype="u2").astype("i2")
c = fits.Column(name="foo", format="i2", bscale=1, bzero=32768, array=n)
t = fits.BinTableHDU.from_columns([c])
lst.append(p)
lst.append(t)
lst.writeto(self.temp("test.fits"), overwrite=True)
with fits.open(self.temp("test.fits")) as p:
assert p[1].data[1]["foo"] == 60000.0
def test_fits_file_path_object(self):
"""
Testing when fits file is passed as pathlib.Path object #4412.
"""
fpath = pathlib.Path(self.data("tdim.fits"))
with fits.open(fpath) as hdulist:
assert hdulist[0].filebytes() == 2880
assert hdulist[1].filebytes() == 5760
with fits.open(self.data("tdim.fits")) as hdulist2:
assert FITSDiff(hdulist2, hdulist).identical is True
def test_fits_pathlike_object(self):
"""
Testing when fits file is passed as os.PathLike object #11579.
"""
class TPath(os.PathLike):
def __init__(self, path):
self.path = path
def __fspath__(self):
return str(self.path)
fpath = TPath(self.data("tdim.fits"))
with fits.open(fpath) as hdulist:
assert hdulist[0].filebytes() == 2880
assert hdulist[1].filebytes() == 5760
with fits.open(self.data("tdim.fits")) as hdulist2:
assert FITSDiff(hdulist2, hdulist).identical is True
def test_fits_file_bytes_object(self):
"""
Testing when fits file is passed as bytes.
"""
with fits.open(self.data("tdim.fits").encode()) as hdulist:
assert hdulist[0].filebytes() == 2880
assert hdulist[1].filebytes() == 5760
with fits.open(self.data("tdim.fits")) as hdulist2:
assert FITSDiff(hdulist2, hdulist).identical is True
def test_add_del_columns(self):
p = fits.ColDefs([])
p.add_col(fits.Column(name="FOO", format="3J"))
p.add_col(fits.Column(name="BAR", format="1I"))
assert p.names == ["FOO", "BAR"]
p.del_col("FOO")
assert p.names == ["BAR"]
def test_add_del_columns2(self):
hdulist = fits.open(self.data("tb.fits"))
table = hdulist[1]
assert table.data.dtype.names == ("c1", "c2", "c3", "c4")
assert table.columns.names == ["c1", "c2", "c3", "c4"]
table.columns.del_col("c1")
assert table.data.dtype.names == ("c2", "c3", "c4")
assert table.columns.names == ["c2", "c3", "c4"]
table.columns.del_col("c3")
assert table.data.dtype.names == ("c2", "c4")
assert table.columns.names == ["c2", "c4"]
table.columns.add_col(fits.Column("foo", "3J"))
assert table.data.dtype.names == ("c2", "c4", "foo")
assert table.columns.names == ["c2", "c4", "foo"]
hdulist.writeto(self.temp("test.fits"), overwrite=True)
hdulist.close()
# NOTE: If you see a warning, might be related to
# https://github.com/spacetelescope/PyFITS/issues/44
with fits.open(self.temp("test.fits")) as hdulist:
table = hdulist[1]
assert table.data.dtype.names == ("c2", "c4", "foo")
assert table.columns.names == ["c2", "c4", "foo"]
def test_update_header_card(self):
"""A very basic test for the Header.update method--I'd like to add a
few more cases to this at some point.
"""
header = fits.Header()
comment = "number of bits per data pixel"
header["BITPIX"] = (16, comment)
assert "BITPIX" in header
assert header["BITPIX"] == 16
assert header.comments["BITPIX"] == comment
header.update(BITPIX=32)
assert header["BITPIX"] == 32
assert header.comments["BITPIX"] == ""
def test_set_card_value(self):
"""Similar to test_update_header_card(), but tests the
`header['FOO'] = 'bar'` method of updating card values.
"""
header = fits.Header()
comment = "number of bits per data pixel"
card = fits.Card.fromstring(f"BITPIX = 32 / {comment}")
header.append(card)
header["BITPIX"] = 32
assert "BITPIX" in header
assert header["BITPIX"] == 32
assert header.cards[0].keyword == "BITPIX"
assert header.cards[0].value == 32
assert header.cards[0].comment == comment
def test_uint(self):
filename = self.data("o4sp040b0_raw.fits")
with fits.open(filename, uint=False) as hdulist_f:
with fits.open(filename, uint=True) as hdulist_i:
assert hdulist_f[1].data.dtype == np.float32
assert hdulist_i[1].data.dtype == np.uint16
assert np.all(hdulist_f[1].data == hdulist_i[1].data)
def test_fix_missing_card_append(self):
hdu = fits.ImageHDU()
errs = hdu.req_cards("TESTKW", None, None, "foo", "silentfix", [])
assert len(errs) == 1
assert "TESTKW" in hdu.header
assert hdu.header["TESTKW"] == "foo"
assert hdu.header.cards[-1].keyword == "TESTKW"
def test_fix_invalid_keyword_value(self):
hdu = fits.ImageHDU()
hdu.header["TESTKW"] = "foo"
errs = hdu.req_cards("TESTKW", None, lambda v: v == "foo", "foo", "ignore", [])
assert len(errs) == 0
# Now try a test that will fail, and ensure that an error will be
# raised in 'exception' mode
errs = hdu.req_cards(
"TESTKW", None, lambda v: v == "bar", "bar", "exception", []
)
assert len(errs) == 1
assert errs[0][1] == "'TESTKW' card has invalid value 'foo'."
# See if fixing will work
hdu.req_cards("TESTKW", None, lambda v: v == "bar", "bar", "silentfix", [])
assert hdu.header["TESTKW"] == "bar"
def test_unfixable_missing_card(self):
class TestHDU(fits.hdu.base.NonstandardExtHDU):
def _verify(self, option="warn"):
errs = super()._verify(option)
hdu.req_cards("TESTKW", None, None, None, "fix", errs)
return errs
@classmethod
def match_header(cls, header):
# Since creating this HDU class adds it to the registry we
# don't want the file reader to possibly think any actual
# HDU from a file should be handled by this class
return False
hdu = TestHDU(header=fits.Header())
with pytest.raises(fits.VerifyError):
hdu.verify("fix")
def test_exception_on_verification_error(self):
hdu = fits.ImageHDU()
del hdu.header["XTENSION"]
with pytest.raises(fits.VerifyError):
hdu.verify("exception")
def test_ignore_verification_error(self):
hdu = fits.ImageHDU()
del hdu.header["NAXIS"]
# The default here would be to issue a warning; ensure that no warnings
# or exceptions are raised
hdu.verify("ignore")
# Make sure the error wasn't fixed either, silently or otherwise
assert "NAXIS" not in hdu.header
def test_unrecognized_verify_option(self):
hdu = fits.ImageHDU()
with pytest.raises(ValueError):
hdu.verify("foobarbaz")
def test_errlist_basic(self):
# Just some tests to make sure that _ErrList is setup correctly.
# No arguments
error_list = fits.verify._ErrList()
assert error_list == []
# Some contents - this is not actually working, it just makes sure they
# are kept.
error_list = fits.verify._ErrList([1, 2, 3])
assert error_list == [1, 2, 3]
def test_combined_verify_options(self):
"""
Test verify options like fix+ignore.
"""
def make_invalid_hdu():
hdu = fits.ImageHDU()
# Add one keyword to the header that contains a fixable defect, and one
# with an unfixable defect
c1 = fits.Card.fromstring("test = ' test'")
c2 = fits.Card.fromstring("P.I. = ' Hubble'")
hdu.header.append(c1)
hdu.header.append(c2)
return hdu
# silentfix+ignore should be completely silent
hdu = make_invalid_hdu()
hdu.verify("silentfix+ignore")
# silentfix+warn should be quiet about the fixed HDU and only warn
# about the unfixable one
hdu = make_invalid_hdu()
with pytest.warns(fits.verify.VerifyWarning) as w:
hdu.verify("silentfix+warn")
assert len(w) == 4
assert "Illegal keyword name 'P.I.'" in str(w.list[2].message)
# silentfix+exception should only mention the unfixable error in the
# exception
hdu = make_invalid_hdu()
with pytest.raises(fits.VerifyError, match=r"Illegal keyword name") as excinfo:
hdu.verify("silentfix+exception")
assert "not upper case" not in str(excinfo.value)
# fix+ignore is not too useful, but it should warn about the fixed
# problems while saying nothing about the unfixable problems
hdu = make_invalid_hdu()
with pytest.warns(fits.verify.VerifyWarning) as w:
hdu.verify("fix+ignore")
assert len(w) == 4
assert "not upper case" not in str(w.list[0].message)
# fix+warn
hdu = make_invalid_hdu()
with pytest.warns(AstropyUserWarning) as w:
hdu.verify("fix+warn")
assert len(w) == 6
assert "not upper case" in str(w[2].message)
assert "Illegal keyword name" in str(w[4].message)
# fix+exception
hdu = make_invalid_hdu()
with pytest.raises(fits.VerifyError, match=r"Illegal keyword name") as excinfo:
hdu.verify("fix+exception")
assert "not upper case" in str(excinfo.value)
def test_getext(self):
"""
Test the various different ways of specifying an extension header in
the convenience functions.
"""
filename = self.data("test0.fits")
hl, ext = _getext(filename, "readonly", 1)
assert ext == 1
hl.close()
pytest.raises(ValueError, _getext, filename, "readonly", 1, 2)
pytest.raises(ValueError, _getext, filename, "readonly", (1, 2))
pytest.raises(ValueError, _getext, filename, "readonly", "sci", "sci")
pytest.raises(TypeError, _getext, filename, "readonly", 1, 2, 3)
hl, ext = _getext(filename, "readonly", ext=1)
assert ext == 1
hl.close()
hl, ext = _getext(filename, "readonly", ext=("sci", 2))
assert ext == ("sci", 2)
hl.close()
pytest.raises(
TypeError, _getext, filename, "readonly", 1, ext=("sci", 2), extver=3
)
pytest.raises(
TypeError, _getext, filename, "readonly", ext=("sci", 2), extver=3
)
hl, ext = _getext(filename, "readonly", "sci")
assert ext == ("sci", 1)
hl.close()
hl, ext = _getext(filename, "readonly", "sci", 1)
assert ext == ("sci", 1)
hl.close()
hl, ext = _getext(filename, "readonly", ("sci", 1))
assert ext == ("sci", 1)
hl.close()
hl, ext = _getext(
filename, "readonly", "sci", extver=1, do_not_scale_image_data=True
)
assert ext == ("sci", 1)
hl.close()
pytest.raises(TypeError, _getext, filename, "readonly", "sci", ext=1)
pytest.raises(TypeError, _getext, filename, "readonly", "sci", 1, extver=2)
hl, ext = _getext(filename, "readonly", extname="sci")
assert ext == ("sci", 1)
hl.close()
hl, ext = _getext(filename, "readonly", extname="sci", extver=1)
assert ext == ("sci", 1)
hl.close()
pytest.raises(TypeError, _getext, filename, "readonly", extver=1)
def test_extension_name_case_sensitive(self):
"""
Tests that setting fits.conf.extension_name_case_sensitive at
runtime works.
"""
hdu = fits.ImageHDU()
hdu.name = "sCi"
assert hdu.name == "SCI"
assert hdu.header["EXTNAME"] == "SCI"
with fits.conf.set_temp("extension_name_case_sensitive", True):
hdu = fits.ImageHDU()
hdu.name = "sCi"
assert hdu.name == "sCi"
assert hdu.header["EXTNAME"] == "sCi"
hdu.name = "sCi"
assert hdu.name == "SCI"
assert hdu.header["EXTNAME"] == "SCI"
def test_hdu_fromstring(self):
"""
Tests creating a fully-formed HDU object from a string containing the
bytes of the HDU.
"""
infile = self.data("test0.fits")
outfile = self.temp("test.fits")
with open(infile, "rb") as fin:
dat = fin.read()
offset = 0
with fits.open(infile) as hdul:
hdulen = hdul[0]._data_offset + hdul[0]._data_size
hdu = fits.PrimaryHDU.fromstring(dat[:hdulen])
assert isinstance(hdu, fits.PrimaryHDU)
assert hdul[0].header == hdu.header
assert hdu.data is None
hdu.header["TEST"] = "TEST"
hdu.writeto(outfile)
with fits.open(outfile) as hdul:
assert isinstance(hdu, fits.PrimaryHDU)
assert hdul[0].header[:-1] == hdu.header[:-1]
assert hdul[0].header["TEST"] == "TEST"
assert hdu.data is None
with fits.open(infile) as hdul:
for ext_hdu in hdul[1:]:
offset += hdulen
hdulen = len(str(ext_hdu.header)) + ext_hdu._data_size
hdu = fits.ImageHDU.fromstring(dat[offset : offset + hdulen])
assert isinstance(hdu, fits.ImageHDU)
assert ext_hdu.header == hdu.header
assert (ext_hdu.data == hdu.data).all()
def test_nonstandard_hdu(self):
"""
Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/157
Tests that "Nonstandard" HDUs with SIMPLE = F are read and written
without prepending a superfluous and unwanted standard primary HDU.
"""
data = np.arange(100, dtype=np.uint8)
hdu = fits.PrimaryHDU(data=data)
hdu.header["SIMPLE"] = False
hdu.writeto(self.temp("test.fits"))
info = [(0, "", 1, "NonstandardHDU", 5, (), "", "")]
with fits.open(self.temp("test.fits")) as hdul:
assert hdul.info(output=False) == info
# NonstandardHDUs just treat the data as an unspecified array of
# bytes. The first 100 bytes should match the original data we
# passed in...the rest should be zeros padding out the rest of the
# FITS block
assert (hdul[0].data[:100] == data).all()
assert (hdul[0].data[100:] == 0).all()
def test_extname(self):
"""Test getting/setting the EXTNAME of an HDU."""
h1 = fits.PrimaryHDU()
assert h1.name == "PRIMARY"
# Normally a PRIMARY HDU should not have an EXTNAME, though it should
# have a default .name attribute
assert "EXTNAME" not in h1.header
# The current version of the FITS standard does allow PRIMARY HDUs to
# have an EXTNAME, however.
h1.name = "NOTREAL"
assert h1.name == "NOTREAL"
assert h1.header.get("EXTNAME") == "NOTREAL"
# Updating the EXTNAME in the header should update the .name
h1.header["EXTNAME"] = "TOOREAL"
assert h1.name == "TOOREAL"
# If we delete an EXTNAME keyword from a PRIMARY HDU it should go back
# to the default
del h1.header["EXTNAME"]
assert h1.name == "PRIMARY"
# For extension HDUs the situation is a bit simpler:
h2 = fits.ImageHDU()
assert h2.name == ""
assert "EXTNAME" not in h2.header
h2.name = "HELLO"
assert h2.name == "HELLO"
assert h2.header.get("EXTNAME") == "HELLO"
h2.header["EXTNAME"] = "GOODBYE"
assert h2.name == "GOODBYE"
def test_extver_extlevel(self):
"""Test getting/setting the EXTVER and EXTLEVEL of and HDU."""
# EXTVER and EXTNAME work exactly the same; their semantics are, for
# now, to be inferred by the user. Although they should never be less
# than 1, the standard does not explicitly forbid any value so long as
# it's an integer
h1 = fits.PrimaryHDU()
assert h1.ver == 1
assert h1.level == 1
assert "EXTVER" not in h1.header
assert "EXTLEVEL" not in h1.header
h1.ver = 2
assert h1.header.get("EXTVER") == 2
h1.header["EXTVER"] = 3
assert h1.ver == 3
del h1.header["EXTVER"]
assert h1.ver == 1
h1.level = 2
assert h1.header.get("EXTLEVEL") == 2
h1.header["EXTLEVEL"] = 3
assert h1.level == 3
del h1.header["EXTLEVEL"]
assert h1.level == 1
pytest.raises(TypeError, setattr, h1, "ver", "FOO")
pytest.raises(TypeError, setattr, h1, "level", "BAR")
def test_consecutive_writeto(self):
"""
Regression test for an issue where calling writeto twice on the same
HDUList could write a corrupted file.
https://github.com/spacetelescope/PyFITS/issues/40 is actually a
particular instance of this problem, though isn't unique to sys.stdout.
"""
with fits.open(self.data("test0.fits")) as hdul1:
# Add a bunch of header keywords so that the data will be forced to
# new offsets within the file:
for idx in range(40):
hdul1[1].header[f"TEST{idx}"] = "test"
hdul1.writeto(self.temp("test1.fits"))
hdul1.writeto(self.temp("test2.fits"))
# Open a second handle to the original file and compare it to hdul1
# (We only compare part of the one header that was modified)
# Compare also with the second writeto output
with fits.open(self.data("test0.fits")) as hdul2:
with fits.open(self.temp("test2.fits")) as hdul3:
for hdul in (hdul1, hdul3):
for idx, hdus in enumerate(zip(hdul2, hdul)):
hdu2, hdu = hdus
if idx != 1:
assert hdu.header == hdu2.header
else:
assert hdu2.header == hdu.header[: len(hdu2.header)]
assert np.all(hdu.data == hdu2.data)
| TestCore |
python | python-openxml__python-docx | src/docx/shared.py | {
"start": 2670,
"end": 2885
} | class ____(Length):
"""Convenience value class for specifying a length in points."""
def __new__(cls, points: float):
emu = int(points * Length._EMUS_PER_PT)
return Length.__new__(cls, emu)
| Pt |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_basic.py | {
"start": 24673,
"end": 26249
} | class ____(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
global t1, t2
t1 = Table(
"t1",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("type", String(10), nullable=False),
Column("info", String(255)),
)
t2 = Table(
"t2",
metadata,
Column("id", Integer, ForeignKey("t1.id"), primary_key=True),
Column("data", String(10), nullable=False),
)
def test_polymorphic_synonym(self):
class T1(ComparableEntity):
def info(self):
return "THE INFO IS:" + self._info
def _set_info(self, x):
self._info = x
info = property(info, _set_info)
class T2(T1):
pass
self.mapper_registry.map_imperatively(
T1,
t1,
polymorphic_on=t1.c.type,
polymorphic_identity="t1",
properties={"info": synonym("_info", map_column=True)},
)
self.mapper_registry.map_imperatively(
T2, t2, inherits=T1, polymorphic_identity="t2"
)
sess = fixture_session()
at1 = T1(info="at1")
at2 = T2(info="at2", data="t2 data")
sess.add(at1)
sess.add(at2)
sess.flush()
sess.expunge_all()
eq_(sess.query(T2).filter(T2.info == "at2").one(), at2)
eq_(at2.info, "THE INFO IS:at2")
| PolymorphicSynonymTest |
python | weaviate__weaviate-python-client | weaviate/exceptions.py | {
"start": 7272,
"end": 7510
} | class ____(WeaviateQueryError):
"""Is raised if a gRPC batch query to Weaviate fails in any way."""
def __init__(self, message: str):
super().__init__(message, "GRPC batch")
self.message = message
| WeaviateBatchError |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-cohere-citation-chat/llama_index/packs/cohere_citation_chat/citations_context_chat_engine.py | {
"start": 8549,
"end": 9951
} | class ____(VectorStoreIndex):
"""Vector Store Index with Citations Chat."""
def set_embed_model_input_type(self, input_type: str) -> None:
try:
from llama_index.embeddings.cohere import CohereEmbedding
except ImportError:
raise ImportError(
"Please run `pip install llama-index-embeddings-cohere` "
"to use the Cohere."
)
# Set the embed model input type. We need to change the Cohere embed input type to the 'search_query' value.
if isinstance(self._embed_model, CohereEmbedding):
self._embed_model.input_type = input_type
def as_chat_engine(
self,
chat_mode: ChatModeCitations = ChatModeCitations.COHERE_CITATIONS_CONTEXT,
llm: Optional[LLMType] = None,
**kwargs: Any,
) -> BaseChatEngine:
if chat_mode not in [ChatModeCitations.COHERE_CITATIONS_CONTEXT]:
return super().as_chat_engine(chat_mode=chat_mode, llm=llm, **kwargs)
else:
llm = (
resolve_llm(llm, callback_manager=self._callback_manager)
if llm
else Settings.llm
)
return CitationsContextChatEngine.from_defaults(
retriever=self.as_retriever(**kwargs),
llm=llm,
**kwargs,
)
| VectorStoreIndexWithCitationsChat |
python | numpy__numpy | numpy/distutils/system_info.py | {
"start": 72436,
"end": 76399
} | class ____(system_info):
notfounderror = BlasNotFoundError
# List of all known BLAS libraries, in the default order
blas_order = ['armpl', 'mkl', 'ssl2', 'blis', 'openblas',
'accelerate', 'atlas', 'blas']
order_env_var_name = 'NPY_BLAS_ORDER'
def _calc_info_armpl(self):
info = get_info('blas_armpl')
if info:
self.set_info(**info)
return True
return False
def _calc_info_mkl(self):
info = get_info('blas_mkl')
if info:
self.set_info(**info)
return True
return False
def _calc_info_ssl2(self):
info = get_info('blas_ssl2')
if info:
self.set_info(**info)
return True
return False
def _calc_info_blis(self):
info = get_info('blis')
if info:
self.set_info(**info)
return True
return False
def _calc_info_openblas(self):
info = get_info('openblas')
if info:
self.set_info(**info)
return True
return False
def _calc_info_atlas(self):
info = get_info('atlas_3_10_blas_threads')
if not info:
info = get_info('atlas_3_10_blas')
if not info:
info = get_info('atlas_blas_threads')
if not info:
info = get_info('atlas_blas')
if info:
self.set_info(**info)
return True
return False
def _calc_info_accelerate(self):
info = get_info('accelerate')
if info:
self.set_info(**info)
return True
return False
def _calc_info_blas(self):
# Warn about a non-optimized BLAS library
warnings.warn(BlasOptNotFoundError.__doc__ or '', stacklevel=3)
info = {}
dict_append(info, define_macros=[('NO_ATLAS_INFO', 1)])
blas = get_info('blas')
if blas:
dict_append(info, **blas)
else:
# Not even BLAS was found!
warnings.warn(BlasNotFoundError.__doc__ or '', stacklevel=3)
blas_src = get_info('blas_src')
if not blas_src:
warnings.warn(BlasSrcNotFoundError.__doc__ or '', stacklevel=3)
return False
dict_append(info, libraries=[('fblas_src', blas_src)])
self.set_info(**info)
return True
def _calc_info_from_envvar(self):
info = {}
info['language'] = 'f77'
info['libraries'] = []
info['include_dirs'] = []
info['define_macros'] = []
info['extra_link_args'] = os.environ['NPY_BLAS_LIBS'].split()
if 'NPY_CBLAS_LIBS' in os.environ:
info['define_macros'].append(('HAVE_CBLAS', None))
info['extra_link_args'].extend(
os.environ['NPY_CBLAS_LIBS'].split())
self.set_info(**info)
return True
def _calc_info(self, name):
return getattr(self, '_calc_info_{}'.format(name))()
def calc_info(self):
blas_order, unknown_order = _parse_env_order(self.blas_order, self.order_env_var_name)
if len(unknown_order) > 0:
raise ValueError("blas_opt_info user defined BLAS order has unacceptable values: {}".format(unknown_order))
if 'NPY_BLAS_LIBS' in os.environ:
# Bypass autodetection, set language to F77 and use env var linker
# flags directly
self._calc_info_from_envvar()
return
for blas in blas_order:
if self._calc_info(blas):
return
if 'blas' not in blas_order:
# Since the user may request *not* to use any library, we still need
# to raise warnings to signal missing packages!
warnings.warn(BlasNotFoundError.__doc__ or '', stacklevel=2)
warnings.warn(BlasSrcNotFoundError.__doc__ or '', stacklevel=2)
| blas_opt_info |
python | walkccc__LeetCode | solutions/63. Unique Paths II/63.py | {
"start": 0,
"end": 485
} | class ____:
def uniquePathsWithObstacles(self, obstacleGrid: list[list[int]]) -> int:
m = len(obstacleGrid)
n = len(obstacleGrid[0])
# dp[i][j] := the number of unique paths from (0, 0) to (i, j)
dp = [[0] * (n + 1) for _ in range(m + 1)]
dp[0][1] = 1 # Can also set dp[1][0] = 1.
for i in range(1, m + 1):
for j in range(1, n + 1):
if obstacleGrid[i - 1][j - 1] == 0:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[m][n]
| Solution |
python | rapidsai__cudf | cpp/scripts/gdb-pretty-printers.py | {
"start": 1000,
"end": 1914
} | class ____(gdb.printing.PrettyPrinter):
"""Print a cudf::device_span"""
def __init__(self, val):
self.val = val
self.pointer = val["_data"]
self.size = int(val["_size"])
def children(self):
return DeviceIterator(self.pointer, self.size)
def to_string(self):
return f"{self.val.type} of length {self.size} at {hex(self.pointer)}"
def display_hint(self):
return "array"
def lookup_cudf_type(val):
if not str(val.type.unqualified()).startswith("cudf::"):
return None
suffix = str(val.type.unqualified())[6:]
if not is_template_type_not_alias(suffix):
return None
if template_match(suffix, "host_span"):
return CudfHostSpanPrinter(val)
if template_match(suffix, "device_span"):
return CudfDeviceSpanPrinter(val)
return None
gdb.pretty_printers.append(lookup_cudf_type)
| CudfDeviceSpanPrinter |
python | google__pytype | pytype/tests/test_classes2.py | {
"start": 7844,
"end": 16438
} | class ____(test_base.BaseTest):
"""Tests for classes."""
def test_class_starargs(self):
ty = self.Infer("""
class Foo: pass
class Bar: pass
bases = (Foo, Bar)
class Baz(*bases): pass
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import Tuple, Type
bases: Tuple[Type[Foo], Type[Bar]]
class Foo: ...
class Bar: ...
class Baz(Foo, Bar): ...
""",
)
def test_class_kwargs(self):
ty = self.Infer("""
# x, y are passed to type() or the metaclass. We currently ignore them.
class Thing(x=True, y="foo"): pass
""")
self.assertTypesMatchPytd(
ty,
"""
class Thing: ...
""",
)
def test_metaclass_kwarg(self):
self.Check("""
import abc
class Example(metaclass=abc.ABCMeta):
@abc.abstractmethod
def foo(self) -> int:
return None
""")
def test_class_starargs_with_metaclass(self):
self.Check("""
class Foo: pass
class Bar: pass
bases = (Foo, Bar)
class Baz(*bases, metaclass=type): pass
""")
def test_build_class_quick(self):
# A() hits maximum stack depth
ty = self.Infer(
"""
def f():
class A: pass
return {A: A()}
""",
quick=True,
maximum_depth=1,
)
self.assertTypesMatchPytd(
ty,
"""
def f() -> dict: ...
""",
)
def test_type_change(self):
ty = self.Infer("""
class A:
def __init__(self):
self.__class__ = int
x = "" % type(A())
""")
self.assertTypesMatchPytd(
ty,
"""
class A:
def __init__(self) -> None: ...
x = ... # type: str
""",
)
def test_ambiguous_base_class(self):
with test_utils.Tempdir() as d:
d.create_file(
"foo.pyi",
"""
from typing import Any
class Foo(Any): ...
""",
)
self.Check(
"""
from typing import Tuple
import foo
def f() -> Tuple[int]:
return foo.Foo()
""",
pythonpath=[d.path],
)
def test_callable_inheritance(self):
self.Check("""
from typing import Callable
Foo = Callable[[], None]
class Bar(Foo):
def __call__(self):
pass
def f(x: Foo):
pass
f(Bar(__any_object__, __any_object__))
""")
def test_init_test_class_in_setup(self):
ty = self.Infer("""
import unittest
class A(unittest.TestCase):
def setUp(self):
self.x = 10
def fooTest(self):
return self.x
""")
self.assertTypesMatchPytd(
ty,
"""
import unittest
class A(unittest.case.TestCase):
x = ... # type: int
def fooTest(self) -> int: ...
def setUp(self) -> None : ...
""",
)
def test_init_inherited_test_class_in_setup(self):
ty = self.Infer("""
import unittest
class A(unittest.TestCase):
def setUp(self):
self.x = 10
class B(A):
def fooTest(self):
return self.x
""")
self.assertTypesMatchPytd(
ty,
"""
import unittest
class A(unittest.case.TestCase):
x = ... # type: int
def setUp(self) -> None : ...
class B(A):
x = ... # type: int
def fooTest(self) -> int: ...
""",
)
def test_init_test_class_in_init_and_setup(self):
ty = self.Infer("""
import unittest
class A(unittest.TestCase):
def __init__(self, foo: str):
self.foo = foo
def setUp(self):
self.x = 10
def fooTest(self):
return self.x
""")
self.assertTypesMatchPytd(
ty,
"""
import unittest
class A(unittest.case.TestCase):
x = ... # type: int
foo = ... # type: str
def __init__(self, foo: str) -> NoneType: ...
def fooTest(self) -> int: ...
def setUp(self) -> None : ...
""",
)
def test_set_metaclass(self):
ty = self.Infer("""
class A(type):
def f(self):
return 3.14
class X(metaclass=A):
pass
v = X.f()
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import Type
class A(type):
def f(self) -> float: ...
class X(metaclass=A):
pass
v = ... # type: float
""",
)
def test_no_metaclass(self):
# In this case, the metaclass should not actually be set.
ty = self.Infer("""
class X(metaclass=type):
pass
""")
self.assertTypesMatchPytd(
ty,
"""
class X:
pass
""",
)
def test_metaclass(self):
with test_utils.Tempdir() as d:
d.create_file(
"foo.pyi",
"""
T = TypeVar("T")
class MyMeta(type):
def register(self, cls: type) -> None: ...
def mymethod(funcobj: T) -> T: ...
""",
)
ty = self.Infer(
"""
import foo
class X(metaclass=foo.MyMeta):
@foo.mymethod
def f(self):
return 42
X.register(tuple)
v = X().f()
""",
pythonpath=[d.path],
)
self.assertTypesMatchPytd(
ty,
"""
import foo
from typing import Type
class X(metaclass=foo.MyMeta):
def f(self) -> int: ...
v = ... # type: int
""",
)
@test_base.skip("Setting metaclass to a function doesn't work yet.")
def test_function_as_metaclass(self):
ty = self.Infer("""
def MyMeta(name, bases, members):
return type(name, bases, members)
class X(metaclass=MyMeta):
pass
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import Any
def MyMeta(names, bases, members) -> Any: ...
class X(metaclass=MyMeta):
pass
""",
)
def test_unknown_metaclass(self):
self.Check("""
class Foo(metaclass=__any_object__):
def foo(self):
self.bar()
@classmethod
def bar(cls):
pass
""")
def test_py2_metaclass(self):
errors = self.CheckWithErrors("""
import abc
class Foo: # ignored-metaclass[e]
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def f(self) -> int: ...
""")
self.assertErrorRegexes(errors, {"e": r"abc\.ABCMeta.*Foo"})
def test_new_no_bases(self):
self.Check("""
class Foo:
def __new__(cls, x):
self = super().__new__(cls)
self.x = x
return self
Foo(0)
""")
def test_new_pyi_no_bases(self):
with test_utils.Tempdir() as d:
d.create_file(
"foo.pyi",
"""
class Foo:
def __new__(cls, x) -> Foo: ...
""",
)
self.Check(
"""
import foo
foo.Foo(0)
""",
pythonpath=[d.path],
)
def test_type_subclass(self):
self.Check("""
class A(type):
def __init__(self, name, bases, dct):
super().__init__(name, bases, dct)
class B(type, metaclass=A):
pass
""")
def test_attribute_in_decorated_init(self):
self.Check("""
from typing import Any
def decorate(f) -> Any:
return f
class X:
@decorate
def __init__(self):
self.x = 0
x = X()
assert_type(x.x, int)
""")
def test_attribute_in_decorated_init_inference(self):
ty = self.Infer("""
from typing import Any
def decorate(f) -> Any:
return f
class X:
@decorate
def __init__(self):
self.x = 0
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import Any
def decorate(f) -> Any: ...
class X:
__init__: Any
x: int
""",
)
def test_init_subclass_super(self):
self.Check("""
class A:
def __init_subclass__(cls):
pass
class B(A):
def __init_subclass__(cls):
super().__init_subclass__()
""")
def test_init_subclass_explicit_classmethod(self):
ty = self.Infer("""
class Foo:
@classmethod
def __init_subclass__(cls):
pass
""")
self.assertTypesMatchPytd(
ty,
"""
class Foo:
def __init_subclass__(cls) -> None: ...
""",
)
if __name__ == "__main__":
test_base.main()
| ClassesTestPython3Feature |
python | django__django | tests/serializers/models/data.py | {
"start": 3260,
"end": 3333
} | class ____(models.Model):
data = models.ManyToManyField(Anchor)
| M2MData |
python | django__django | tests/backends/tests.py | {
"start": 11537,
"end": 11591
} | class ____(EscapingChecks):
pass
| EscapingChecksDebug |
python | pennersr__django-allauth | allauth/idp/oidc/admin.py | {
"start": 1191,
"end": 1415
} | class ____(admin.ModelAdmin):
raw_id_fields = ("client", "user")
list_display = (
"client",
"type",
"user",
"created_at",
"expires_at",
)
list_filter = ("type",)
| TokenAdmin |
python | Lightning-AI__lightning | src/lightning/pytorch/strategies/launchers/subprocess_script.py | {
"start": 1322,
"end": 7015
} | class ____(_Launcher):
r"""A process launcher that invokes the current script as many times as desired in a single node.
This launcher needs to be invoked on each node.
In its default behavior, the main process in each node then spawns N-1 child processes via :func:`subprocess.Popen`,
where N is the number of devices (e.g. GPU) per node. It is very similar to how :mod:`torch.distributed.run`
launches processes.
For example, if the script gets invoked with the command
.. code-block:: bash
python train.py --devices 4
The launcher will create three additional subprocesses that get called like so:
.. code-block:: bash
LOCAL_RANK=1 python train.py --devices 4
LOCAL_RANK=2 python train.py --devices 4
LOCAL_RANK=3 python train.py --devices 4
It is implied that the main process which launched the others has ``LOCAL_RANK=0``.
Beside the local rank, the following other environment variables also get set, but unlike the local rank, these
get determined by the cluster environment:
1. `MASTER_ADDR`: The IP address of the main node.
2. `MASTER_PORT`: The port number of the main node through which all processes communicate.
3. `NODE_RANK`: The index of the node the current process is running on. Ranges from 0 to ``num_nodes - 1``.
4. `WORLD_SIZE`: The total number of processes across all nodes, i.e., ``num_processes * num_nodes``.
Arguments:
cluster_environment: A cluster environment that provides access to world size, node rank, etc.
num_processes: The number of processes to launch in the current node.
num_nodes: The total number of nodes that participate in this process group.
"""
def __init__(self, cluster_environment: ClusterEnvironment, num_processes: int, num_nodes: int) -> None:
super().__init__()
self.cluster_environment = cluster_environment
self.num_processes = num_processes
self.num_nodes = num_nodes
self.procs: list[subprocess.Popen] = [] # launched child subprocesses, does not include the launcher
@property
@override
def is_interactive_compatible(self) -> bool:
return False
@override
def launch(self, function: Callable, *args: Any, trainer: Optional["pl.Trainer"] = None, **kwargs: Any) -> Any:
"""Creates new processes, then calls the given function.
Arguments:
function: A callback function to execute after all processes have been created.
It is up to the implementation of this function to synchronize the processes, e.g., with barriers.
*args: Optional positional arguments to be passed to the given function.
trainer: Optional reference to the :class:`~lightning.pytorch.trainer.trainer.Trainer`.
**kwargs: Optional keyword arguments to be passed to the given function.
"""
self.cluster_environment.validate_settings(num_devices=self.num_processes, num_nodes=self.num_nodes)
if not self.cluster_environment.creates_processes_externally:
self._call_children_scripts()
_launch_process_observer(self.procs)
_set_num_threads_if_needed(num_processes=self.num_processes)
return function(*args, **kwargs)
@override
def kill(self, signum: _SIGNUM) -> None:
for proc in self.procs:
log.debug(f"Process {os.getpid()} is terminating {proc.pid} with {signum}")
# this skips subprocesses already terminated
proc.send_signal(signum)
def _call_children_scripts(self) -> None:
# bookkeeping of spawned processes
self._check_can_spawn_children()
self.procs = [] # reset in case it's called twice
# DDP Environment variables
os.environ["MASTER_ADDR"] = self.cluster_environment.main_address
os.environ["MASTER_PORT"] = str(self.cluster_environment.main_port)
# allow the user to pass the node rank
os.environ["NODE_RANK"] = str(self.cluster_environment.node_rank())
os.environ["LOCAL_RANK"] = str(self.cluster_environment.local_rank())
os.environ["WORLD_SIZE"] = f"{self.num_processes * self.num_nodes}"
for local_rank in range(1, self.num_processes):
env_copy = os.environ.copy()
env_copy["LOCAL_RANK"] = f"{local_rank}"
# remove env var if global seed not set
if os.environ.get("PL_GLOBAL_SEED") is None and "PL_GLOBAL_SEED" in env_copy:
del env_copy["PL_GLOBAL_SEED"]
hydra_in_use = False
cwd: Optional[str] = None
if _HYDRA_AVAILABLE:
from hydra.core.hydra_config import HydraConfig
hydra_in_use = HydraConfig.initialized()
if hydra_in_use:
command, cwd = _hydra_subprocess_cmd(local_rank)
else:
command = _basic_subprocess_cmd()
new_process = subprocess.Popen(command, env=env_copy, cwd=cwd)
self.procs.append(new_process)
def _check_can_spawn_children(self) -> None:
if len(self.procs) > 0:
raise RuntimeError("The launcher can only create subprocesses once.")
if self.cluster_environment.local_rank() != 0:
raise RuntimeError(
"Lightning attempted to launch new distributed processes with `local_rank > 0`. This should not happen."
" Possible reasons: 1) LOCAL_RANK environment variable was incorrectly modified by the user,"
" 2) `ClusterEnvironment.creates_processes_externally` incorrectly implemented."
)
| _SubprocessScriptLauncher |
python | huggingface__transformers | src/transformers/models/switch_transformers/modular_switch_transformers.py | {
"start": 11265,
"end": 11342
} | class ____(T5LayerSelfAttention):
pass
| SwitchTransformersLayerSelfAttention |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 59783,
"end": 60142
} | class ____(BaseModel):
usage: Optional["Usage"] = Field(default=None, description="")
time: Optional[float] = Field(default=None, description="Time spent to process this request")
status: Optional[str] = Field(default=None, description="")
result: Optional["SearchMatrixOffsetsResponse"] = Field(default=None, description="")
| InlineResponse20024 |
python | gevent__gevent | src/greentest/3.11/test_signal.py | {
"start": 6974,
"end": 9057
} | class ____(unittest.TestCase):
def test_valid_signals(self):
s = signal.valid_signals()
self.assertIsInstance(s, set)
self.assertGreaterEqual(len(s), 6)
self.assertIn(signal.Signals.SIGINT, s)
self.assertNotIn(0, s)
self.assertNotIn(signal.NSIG, s)
self.assertLess(len(s), signal.NSIG)
def test_issue9324(self):
# Updated for issue #10003, adding SIGBREAK
handler = lambda x, y: None
checked = set()
for sig in (signal.SIGABRT, signal.SIGBREAK, signal.SIGFPE,
signal.SIGILL, signal.SIGINT, signal.SIGSEGV,
signal.SIGTERM):
# Set and then reset a handler for signals that work on windows.
# Issue #18396, only for signals without a C-level handler.
if signal.getsignal(sig) is not None:
signal.signal(sig, signal.signal(sig, handler))
checked.add(sig)
# Issue #18396: Ensure the above loop at least tested *something*
self.assertTrue(checked)
with self.assertRaises(ValueError):
signal.signal(-1, handler)
with self.assertRaises(ValueError):
signal.signal(7, handler)
@unittest.skipUnless(sys.executable, "sys.executable required.")
@support.requires_subprocess()
def test_keyboard_interrupt_exit_code(self):
"""KeyboardInterrupt triggers an exit using STATUS_CONTROL_C_EXIT."""
# We don't test via os.kill(os.getpid(), signal.CTRL_C_EVENT) here
# as that requires setting up a console control handler in a child
# in its own process group. Doable, but quite complicated. (see
# @eryksun on https://github.com/python/cpython/pull/11862)
process = subprocess.run(
[sys.executable, "-c", "raise KeyboardInterrupt"],
stderr=subprocess.PIPE)
self.assertIn(b"KeyboardInterrupt", process.stderr)
STATUS_CONTROL_C_EXIT = 0xC000013A
self.assertEqual(process.returncode, STATUS_CONTROL_C_EXIT)
| WindowsSignalTests |
python | tensorflow__tensorflow | tensorflow/python/distribute/parameter_server_strategy_test.py | {
"start": 3959,
"end": 22723
} | class ____(
multi_worker_test_base.MultiWorkerTestBase):
def setUp(self):
self._result = 0
self._lock = threading.Lock()
self._init_condition = threading.Condition()
self._init_reached = 0
self._finish_condition = threading.Condition()
self._finish_reached = 0
self._sess_config = config_pb2.ConfigProto(allow_soft_placement=True)
super(ParameterServerStrategyTestBase, self).setUp()
def _get_test_objects(self, task_type, task_id, num_gpus):
return create_test_objects(
cluster_spec=self._cluster_spec,
task_type=task_type,
task_id=task_id,
num_gpus=num_gpus,
sess_config=self._sess_config)
def _test_device_assignment_distributed(self, task_type, task_id, num_gpus):
worker_device = '/job:%s/replica:0/task:%d' % (task_type, task_id)
d, _, sess_config = self._get_test_objects(task_type, task_id, num_gpus)
with ops.Graph().as_default(), \
self.cached_session(target=self._default_target,
config=sess_config) as sess, \
d.scope():
# Define a variable outside the call_for_each_replica scope.
n = variable_scope.get_variable('n', initializer=10.0)
self.assertEqual(n.device, '/job:ps/task:0')
def model_fn():
if num_gpus == 0:
last_part_device = 'device:CPU:0'
else:
replica_id = _get_replica_id_integer()
last_part_device = ('device:GPU:%d' % replica_id)
a = constant_op.constant(1.0)
b = constant_op.constant(2.0)
c = a + b
self.assertEqual(a.device, worker_device + '/' + last_part_device)
self.assertEqual(b.device, worker_device + '/' + last_part_device)
self.assertEqual(c.device, worker_device + '/' + last_part_device)
# The device scope is ignored for variables but not for normal ops.
with ops.device('/job:worker/task:0'):
x = variable_scope.get_variable(
'x', initializer=10.0,
aggregation=variable_scope.VariableAggregation.SUM)
x_add = x.assign_add(c)
e = a + c
# The variable x is on the task 1 since the device_function has been
# called once before the model_fn.
self.assertEqual(x.device, '/job:ps/task:1')
self.assertEqual(x_add.device, x.device)
self.assertEqual(e.device,
'/job:worker/replica:0/task:0/%s' % last_part_device)
# The colocate_vars_with can override the distribution's device.
with d.extended.colocate_vars_with(x):
y = variable_scope.get_variable(
'y', initializer=20.0,
aggregation=variable_scope.VariableAggregation.SUM)
# We add an identity here to avoid complaints about summing
# non-distributed values.
y_add = y.assign_add(array_ops.identity(x_add))
self.assertEqual(y.device, '/job:ps/task:1')
self.assertEqual(y_add.device, y.device)
self.assertEqual(y.device, x.device)
z = variable_scope.get_variable(
'z', initializer=10.0,
aggregation=variable_scope.VariableAggregation.SUM)
self.assertEqual(z.device, '/job:ps/task:0')
self.assertNotEqual(z.device, x.device)
with ops.control_dependencies([y_add]):
# We add an identity here to avoid complaints about summing
# non-distributed values.
z_add = z.assign_add(array_ops.identity(y))
with ops.control_dependencies([z_add]):
f = z + c
self.assertEqual(f.device, worker_device + '/' + last_part_device)
# The device scope would merge with the default worker device.
with ops.device('/CPU:1'):
g = e + 1.0
self.assertEqual(g.device, worker_device + '/device:CPU:1')
# This ops.colocate_with will be ignored when defining a variable
# but not for a normal tensor.
with ops.colocate_with(x):
u = variable_scope.get_variable('u', initializer=30.0)
v = variable_scope.get_variable('v', initializer=30.0)
h = f + 1.0
self.assertIn('/job:ps/', u.device)
self.assertIn('/job:ps/', v.device)
# u and v are on different parameter servers.
self.assertTrue(u.device != x.device or v.device != x.device)
self.assertTrue(u.device == x.device or v.device == x.device)
# Here h is not on one worker. Note h.device is canonical while x.device
# is not but.
self.assertIn('/job:ps/', h.device)
return y_add, z_add, f
y, z, f = d.extended.call_for_each_replica(model_fn)
self.assertNotEqual(y, None)
self.assertNotEqual(z, None)
self.assertNotEqual(f, None)
if context.num_gpus() >= 1 and num_gpus <= 1:
self.evaluate(variables.global_variables_initializer())
y_val, z_val, f_val = sess.run([y, z, f])
self.assertEqual(y_val, 33.0)
self.assertEqual(z_val, 43.0)
self.assertEqual(f_val, 46.0)
def _test_device_assignment_distributed_enable_partitioner(
self, task_type, task_id, num_gpus):
d, _, sess_config = self._get_test_objects(task_type, task_id, num_gpus)
num_shards = len(d.extended.parameter_devices)
partitioner = partitioned_variables.fixed_size_partitioner(num_shards)
with ops.Graph().as_default(), \
self.cached_session(target=self._default_target,
config=sess_config) as sess, \
d.scope():
n = variable_scope.get_variable(
'n',
initializer=constant_op.constant([10.0, 20.0]),
aggregation=variable_scope.VariableAggregation.SUM,
partitioner=partitioner)
for part_id, var in enumerate(n):
self.assertEqual(var.device, '/job:ps/task:%d' % part_id)
def model_fn():
a = constant_op.constant([3.0, 5.0])
# The device scope is ignored for variables but not for normal ops.
with ops.device('/job:worker/task:0'):
x = variable_scope.get_variable(
'x',
initializer=constant_op.constant([10.0, 20.0]),
aggregation=variable_scope.VariableAggregation.SUM,
partitioner=partitioner)
x_add = x.assign_add(a, name='x_add')
# The variable x is on the task 1 since the device_function has been
# called once before the model_fn.
for part_id, var in enumerate(x):
self.assertEqual(var.device, '/job:ps/task:%d' % part_id)
self.assertEqual(var.device, x_add[part_id].device)
return x_add
x = d.extended.call_for_each_replica(model_fn)
if context.num_gpus() >= 1:
self.evaluate(variables.global_variables_initializer())
x_val = sess.run(x)
if num_gpus < 1:
self.assertEqual(x_val, [13.0, 25.0])
else:
x_expect = [10.0 + 3 * num_gpus, 20.0 + 5 * num_gpus]
self.assertEqual(x_val, x_expect)
def _test_device_assignment_local(self,
d,
compute_device='CPU',
variable_device='CPU',
num_gpus=0):
with ops.Graph().as_default(), \
self.cached_session(target=self._default_target,
config=self._sess_config) as sess, \
d.scope():
def model_fn():
if 'CPU' in compute_device:
replica_compute_device = '/device:CPU:0'
else:
replica_id = _get_replica_id_integer()
replica_compute_device = ('/device:GPU:%d' % replica_id)
replica_compute_device = device_util.canonicalize(
replica_compute_device)
if 'CPU' in variable_device:
replica_variable_device = '/device:CPU:0'
else:
replica_id = _get_replica_id_integer()
replica_variable_device = ('/device:GPU:%d' % replica_id)
replica_variable_device = device_util.canonicalize(
replica_variable_device)
a = constant_op.constant(1.0)
b = constant_op.constant(2.0)
c = a + b
self.assertEqual(a.device, replica_compute_device)
self.assertEqual(b.device, replica_compute_device)
self.assertEqual(c.device, replica_compute_device)
# The device scope is ignored for variables but not for normal ops.
with ops.device('/device:GPU:2'):
x = variable_scope.get_variable(
'x', initializer=10.0,
aggregation=variable_scope.VariableAggregation.SUM)
x_add = x.assign_add(c)
e = a + c
self.assertEqual(
device_util.canonicalize(x.device), replica_variable_device)
self.assertEqual(x_add.device, x.device)
self.assertEqual(e.device, device_util.canonicalize('/device:GPU:2'))
# The colocate_vars_with can override the distribution's device.
with d.extended.colocate_vars_with(x):
y = variable_scope.get_variable(
'y', initializer=20.0,
aggregation=variable_scope.VariableAggregation.SUM)
# We add an identity here to avoid complaints about summing
# non-distributed values.
y_add = y.assign_add(array_ops.identity(x_add))
self.assertEqual(
device_util.canonicalize(y.device), replica_variable_device)
self.assertEqual(y_add.device, y.device)
self.assertEqual(y.device, x.device)
z = variable_scope.get_variable(
'z', initializer=10.0,
aggregation=variable_scope.VariableAggregation.SUM)
self.assertEqual(
device_util.canonicalize(z.device), replica_variable_device)
with ops.control_dependencies([y_add]):
# We add an identity here to avoid complaints about summing
# non-distributed values.
z_add = z.assign_add(array_ops.identity(y))
with ops.control_dependencies([z_add]):
f = z + c
self.assertEqual(f.device, replica_compute_device)
# The device scope would merge with the default worker device.
with ops.device('/CPU:1'):
g = e + 1.0
self.assertEqual(g.device, device_util.canonicalize('/device:CPU:1'))
# This ops.colocate_with will be ignored when defining a variable
# but not for a normal tensor.
with ops.colocate_with(x):
u = variable_scope.get_variable('u', initializer=30.0)
h = f + 1.0
self.assertEqual(
device_util.canonicalize(u.device), replica_variable_device)
self.assertEqual(
device_util.canonicalize(x.device),
device_util.canonicalize(h.device))
return y_add, z_add, f
y, z, f = d.extended.call_for_each_replica(model_fn)
self.assertNotEqual(y, None)
self.assertNotEqual(z, None)
self.assertNotEqual(f, None)
if context.num_gpus() >= 1 and num_gpus <= 1:
self.evaluate(variables.global_variables_initializer())
y_val, z_val, f_val = sess.run([y, z, f])
self.assertEqual(y_val, 33.0)
self.assertEqual(z_val, 43.0)
self.assertEqual(f_val, 46.0)
def _test_simple_increment(self, task_type, task_id, num_gpus):
d, master_target, sess_config = self._get_test_objects(
task_type, task_id, num_gpus)
if d.extended._cluster_spec:
num_workers = len(d.extended._cluster_spec.as_dict().get(WORKER))
if 'chief' in d.extended._cluster_spec.as_dict():
num_workers += 1
else:
num_workers = 1
with ops.Graph().as_default(), \
self.cached_session(target=master_target,
config=sess_config) as sess, \
d.scope():
def model_fn():
x = variable_scope.get_variable(
'x', initializer=10.0,
aggregation=variable_scope.VariableAggregation.SUM)
y = variable_scope.get_variable(
'y', initializer=20.0,
aggregation=variable_scope.VariableAggregation.SUM)
z = variable_scope.get_variable(
'z', initializer=30.0,
aggregation=variable_scope.VariableAggregation.ONLY_FIRST_REPLICA)
# We explicitly make a constant tensor here to avoid complaints about
# summing non-distributed values.
one = constant_op.constant(1.0)
x_add = x.assign_add(one, use_locking=True)
y_add = y.assign_add(one, use_locking=True)
z_add = z.assign_add(one, use_locking=True)
train_op = control_flow_ops.group(x_add, y_add, z_add)
return x, y, z, train_op
x, y, z, train_op = d.extended.call_for_each_replica(model_fn)
train_op = d.group(train_op)
if task_id == 0:
self.evaluate(variables.global_variables_initializer())
# Workers waiting for chief worker's initializing variables.
self._init_condition.acquire()
self._init_reached += 1
while self._init_reached != num_workers:
self._init_condition.wait()
self._init_condition.notify_all()
self._init_condition.release()
sess.run(train_op)
# Wait for other workers to finish training.
self._finish_condition.acquire()
self._finish_reached += 1
while self._finish_reached != num_workers:
self._finish_condition.wait()
self._finish_condition.notify_all()
self._finish_condition.release()
x_val, y_val, z_val = sess.run([x, y, z])
self.assertEqual(x_val, 10.0 + 1.0 * num_workers * d.num_replicas_in_sync)
self.assertEqual(y_val, 20.0 + 1.0 * num_workers * d.num_replicas_in_sync)
self.assertEqual(z_val, 30.0 + 1.0 * num_workers)
def _test_minimize_loss_graph(self, task_type, task_id, num_gpus):
d, master_target, sess_config = self._get_test_objects(
task_type, task_id, num_gpus)
if task_type:
# Multi-worker
assert hasattr(d.extended, '_cluster_spec') and d.extended._cluster_spec
num_workers = len(d.extended._cluster_spec.as_dict().get(WORKER))
if CHIEF in d.extended._cluster_spec.as_dict():
num_workers += 1
else:
# local
num_workers = 1
with ops.Graph().as_default(), \
self.cached_session(target=master_target,
config=sess_config) as sess, \
d.scope():
kernel = strategy_test_lib.create_variable_like_keras_layer(
'kernel', (1, 1), dtypes.float32,)
def loss_fn(x):
y = array_ops.reshape(
math_ops.matmul(x, kernel), []) - constant_op.constant(1.)
return y * y
# TODO(yuefengz, apassos): eager.backprop.implicit_grad is not safe for
# multiple graphs (b/111216820).
def grad_fn(x):
loss = loss_fn(x)
var_list = (
variables.trainable_variables() + ops.get_collection(
ops.GraphKeys.TRAINABLE_RESOURCE_VARIABLES))
grads = gradients.gradients(loss, var_list)
ret = list(zip(grads, var_list))
return ret
def update(v, g):
return v.assign_sub(0.05 * g, use_locking=True)
one = constant_op.constant([[1.]])
def step():
"""Perform one optimization step."""
# Run forward & backward to get gradients, variables list.
g_v = d.extended.call_for_each_replica(grad_fn, args=(one,))
# Update the variables using the gradients and the update() function.
before_list = []
after_list = []
for g, v in g_v:
fetched = d.extended.read_var(v)
before_list.append(fetched)
with ops.control_dependencies([fetched]):
# TODO(yuefengz): support non-Mirrored variable as destinations.
g = d.extended.reduce_to(
reduce_util.ReduceOp.SUM, g, destinations=v)
with ops.control_dependencies(
d.extended.update(v, update, args=(g,), group=False)):
after_list.append(d.extended.read_var(v))
return before_list, after_list
before_out, after_out = step()
if (not task_type or
multi_worker_util.is_chief(
d.extended._cluster_spec, task_type, task_id)):
self.evaluate(variables.global_variables_initializer())
# Workers waiting for chief worker's initializing variables.
self._init_condition.acquire()
self._init_reached += 1
while self._init_reached != num_workers:
self._init_condition.wait()
self._init_condition.notify_all()
self._init_condition.release()
for i in range(10):
b, a = sess.run((before_out, after_out))
if i == 0:
before, = b
after, = a
error_before = abs(before - 1)
error_after = abs(after - 1)
# Error should go down
self.assertLess(error_after, error_before)
def _test_input_fn_iterator(self,
task_type,
task_id,
num_gpus,
input_fn,
expected_values,
test_reinitialize=True,
ignore_order=False):
distribution, master_target, config = self._get_test_objects(
task_type, task_id, num_gpus)
devices = distribution.extended.worker_devices
with ops.Graph().as_default(), \
self.cached_session(config=config,
target=master_target) as sess:
iterator = distribution.make_input_fn_iterator(input_fn)
sess.run(iterator.initializer)
for expected_value in expected_values:
next_element = iterator.get_next()
computed_value = sess.run([distribute_utils.select_replica(
r, next_element) for r in range(len(devices))])
if ignore_order:
self.assertCountEqual(expected_value, computed_value)
else:
self.assertEqual(expected_value, computed_value)
with self.assertRaises(errors.OutOfRangeError):
next_element = iterator.get_next()
sess.run([distribute_utils.select_replica(r, next_element)
for r in range(len(devices))])
# After re-initializing the iterator, should be able to iterate again.
if test_reinitialize:
sess.run(iterator.initializer)
for expected_value in expected_values:
next_element = iterator.get_next()
computed_value = sess.run([distribute_utils.select_replica(
r, next_element) for r in range(len(devices))])
if ignore_order:
self.assertCountEqual(expected_value, computed_value)
else:
self.assertEqual(expected_value, computed_value)
| ParameterServerStrategyTestBase |
python | openai__openai-python | src/openai/types/realtime/realtime_transcription_session_create_response.py | {
"start": 861,
"end": 1551
} | class ____(BaseModel):
format: Optional[RealtimeAudioFormats] = None
"""The PCM audio format. Only a 24kHz sample rate is supported."""
noise_reduction: Optional[AudioInputNoiseReduction] = None
"""Configuration for input audio noise reduction."""
transcription: Optional[AudioTranscription] = None
"""Configuration of the transcription model."""
turn_detection: Optional[RealtimeTranscriptionSessionTurnDetection] = None
"""Configuration for turn detection.
Can be set to `null` to turn off. Server VAD means that the model will detect
the start and end of speech based on audio volume and respond at the end of user
speech.
"""
| AudioInput |
python | getsentry__sentry | src/sentry/web/frontend/csv.py | {
"start": 336,
"end": 411
} | class ____:
def write(self, value: str) -> str:
return value
| Echo |
python | jackfrued__Python-100-Days | Day31-35/code/example07.py | {
"start": 114,
"end": 1285
} | class ____():
"""摘要生成器"""
def __init__(self, algorithm='md5', size=4096):
"""初始化方法
@params:
algorithm - 哈希摘要算法
size - 每次读取数据的大小
"""
self.size = size
cls = getattr(__import__('hashlib'), algorithm.lower())
self.hasher = cls()
def digest(self, file_stream):
"""生成十六进制的摘要字符串"""
# data = file_stream.read(self.size)
# while data:
# self.hasher.update(data)
# data = file_stream.read(self.size)
for data in iter(lambda: file_stream.read(self.size), b''):
self.hasher.update(data)
return self.hasher.hexdigest()
def __call__(self, file_stream):
return self.digest(file_stream)
def main():
"""主函数"""
hasher1 = StreamHasher()
hasher2 = StreamHasher('sha1')
hasher3 = StreamHasher('sha256')
with open('Python-3.7.2.tar.xz', 'rb') as file_stream:
print(hasher1.digest(file_stream))
file_stream.seek(0, 0)
print(hasher2.digest(file_stream))
file_stream.seek(0, 0)
print(hasher3(file_stream))
if __name__ == '__main__':
main()
| StreamHasher |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-perplexity/llama_index/llms/perplexity/base.py | {
"start": 826,
"end": 19102
} | class ____(LLM):
"""
Perplexity LLM.
Examples:
`pip install llama-index-llms-perplexity`
```python
from llama_index.llms.perplexity import Perplexity
from llama_index.core.llms import ChatMessage
pplx_api_key = "your-perplexity-api-key"
llm = Perplexity(
api_key=pplx_api_key, model="sonar-pro", temperature=0.5
)
messages_dict = [
{"role": "system", "content": "Be precise and concise."},
{"role": "user", "content": "Tell me 5 sentences about Perplexity."},
]
messages = [ChatMessage(**msg) for msg in messages_dict]
response = llm.chat(messages)
print(str(response))
```
"""
model: str = Field(
default="sonar-pro",
description="The Perplexity model to use.",
)
temperature: float = Field(description="The temperature to use during generation.")
max_tokens: Optional[int] = Field(
default=None,
description="The maximum number of tokens to generate.",
)
context_window: Optional[int] = Field(
default=None,
description="The context window to use during generation.",
)
api_key: Optional[str] = Field(
description="The Perplexity API key.",
exclude=True,
)
api_base: str = Field(
default="https://api.perplexity.ai",
description="The base URL for Perplexity API.",
)
additional_kwargs: dict[str, Any] = Field(
default_factory=dict, description="Additional kwargs for the Perplexity API."
)
max_retries: int = Field(
default=10, description="The maximum number of API retries."
)
headers: dict[str, str] = Field(
default_factory=dict, description="Headers for API requests."
)
enable_search_classifier: bool = Field(
default=False,
description="Whether to enable the search classifier. Default is False.",
)
is_chat_model: bool = Field(
default=True,
description="Whether this is a chat model or not. Default is True.",
)
timeout: float = Field(default=10.0, description="HTTP Timeout")
def __init__(
self,
model: str = "sonar-pro",
temperature: float = 0.2,
max_tokens: Optional[int] = None,
api_key: Optional[str] = None,
api_base: Optional[str] = "https://api.perplexity.ai",
additional_kwargs: Optional[dict[str, Any]] = None,
max_retries: int = 10,
context_window: Optional[int] = None,
callback_manager: Optional[CallbackManager] = None,
system_prompt: Optional[str] = None,
messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None,
completion_to_prompt: Optional[Callable[[str], str]] = None,
pydantic_program_mode: PydanticProgramMode = PydanticProgramMode.DEFAULT,
output_parser: Optional[BaseOutputParser] = None,
enable_search_classifier: bool = False,
timeout: float = 30.0,
**kwargs: Any,
) -> None:
api_key = api_key or getenv("PPLX_API_KEY")
additional_kwargs = additional_kwargs or {}
headers = {
"accept": "application/json",
"content-type": "application/json",
"authorization": f"Bearer {api_key}",
}
super().__init__(
model=model,
temperature=temperature,
max_tokens=max_tokens,
additional_kwargs=additional_kwargs,
max_retries=max_retries,
callback_manager=callback_manager,
api_key=api_key,
api_base=api_base,
headers=headers,
context_window=context_window,
system_prompt=system_prompt,
messages_to_prompt=messages_to_prompt,
completion_to_prompt=completion_to_prompt,
pydantic_program_mode=pydantic_program_mode,
output_parser=output_parser,
enable_search_classifier=enable_search_classifier,
timeout=timeout,
**kwargs,
)
@classmethod
def class_name(cls) -> str:
return "perplexity_llm"
@property
def metadata(self) -> LLMMetadata:
return LLMMetadata(
context_window=(
self.context_window
if self.context_window is not None
else self._get_context_window()
),
num_output=self.max_tokens or -1,
is_chat_model=self.is_chat_model,
model_name=self.model,
)
def _get_context_window(self) -> int:
"""
For latest model information, check:
https://docs.perplexity.ai/guides/model-cards.
"""
model_context_windows = {
"sonar-deep-research": 127072,
"sonar-reasoning-pro": 127072,
"sonar-reasoning": 127072,
"sonar": 127072,
"r1-1776": 127072,
"sonar-pro": 200000,
}
return model_context_windows.get(self.model, 127072)
def _get_all_kwargs(self, **kwargs: Any) -> dict[str, Any]:
"""Get all data for the request as a dictionary."""
base_kwargs = {
"model": self.model,
"temperature": self.temperature,
"enable_search_classifier": self.enable_search_classifier,
}
if self.max_tokens is not None:
base_kwargs["max_tokens"] = self.max_tokens
return {**base_kwargs, **self.additional_kwargs, **kwargs}
def _complete(self, prompt: str, **kwargs: Any) -> CompletionResponse:
url = f"{self.api_base}/chat/completions"
messages = [{"role": "user", "content": prompt}]
if self.system_prompt:
messages.insert(0, {"role": "system", "content": self.system_prompt})
payload = {
"model": self.model,
"messages": messages,
**self._get_all_kwargs(**kwargs),
}
response = requests.post(
url, json=payload, headers=self.headers, timeout=self.timeout
)
response.raise_for_status()
data = response.json()
return CompletionResponse(
text=data["choices"][0]["message"]["content"], raw=data
)
@llm_completion_callback()
def complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponse:
@retry(stop=stop_after_attempt(self.max_retries), wait=wait_fixed(1))
def _complete_retry():
return self._complete(prompt, **kwargs)
return _complete_retry()
def _chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse:
url = f"{self.api_base}/chat/completions"
message_dicts = to_openai_message_dicts(messages)
payload = {
"model": self.model,
"messages": message_dicts,
**self._get_all_kwargs(**kwargs),
}
response = requests.post(
url, json=payload, headers=self.headers, timeout=self.timeout
)
response.raise_for_status()
data = response.json()
message = ChatMessage(
role="assistant", content=data["choices"][0]["message"]["content"]
)
return ChatResponse(message=message, raw=data)
@llm_chat_callback()
def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse:
@retry(stop=stop_after_attempt(self.max_retries), wait=wait_fixed(1))
def _chat_retry():
return self._chat(messages, **kwargs)
return _chat_retry()
async def _acomplete(self, prompt: str, **kwargs: Any) -> CompletionResponse:
url = f"{self.api_base}/chat/completions"
messages = [{"role": "user", "content": prompt}]
if self.system_prompt:
messages.insert(0, {"role": "system", "content": self.system_prompt})
payload = {
"model": self.model,
"messages": messages,
**self._get_all_kwargs(**kwargs),
}
async with httpx.AsyncClient() as client:
response = await client.post(
url, json=payload, headers=self.headers, timeout=self.timeout
)
response.raise_for_status()
data = response.json()
return CompletionResponse(
text=data["choices"][0]["message"]["content"], raw=data
)
@llm_completion_callback()
async def acomplete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponse:
@retry(stop=stop_after_attempt(self.max_retries), wait=wait_fixed(1))
async def _acomplete_retry(prompt, **kwargs):
return await self._acomplete(prompt, **kwargs)
return await _acomplete_retry(prompt, **kwargs)
async def _achat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponse:
message_dicts = to_openai_message_dicts(messages)
payload = {
"model": self.model,
"messages": message_dicts,
**self._get_all_kwargs(**kwargs),
}
url = f"{self.api_base}/chat/completions"
async with httpx.AsyncClient() as client:
response = await client.post(
url, json=payload, headers=self.headers, timeout=self.timeout
)
response.raise_for_status()
data = response.json()
message = ChatMessage(
role="assistant", content=data["choices"][0]["message"]["content"]
)
return ChatResponse(message=message, raw=data)
@llm_chat_callback()
async def achat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponse:
@retry(stop=stop_after_attempt(self.max_retries), wait=wait_fixed(1))
async def _achat_retry():
return await self._achat(messages, **kwargs)
return await _achat_retry()
def _stream_complete(self, prompt: str, **kwargs: Any) -> CompletionResponseGen:
url = f"{self.api_base}/chat/completions"
messages = [{"role": "user", "content": prompt}]
if self.system_prompt:
messages.insert(0, {"role": "system", "content": self.system_prompt})
payload = {
"model": self.model,
"messages": messages,
"stream": True,
**self._get_all_kwargs(**kwargs),
}
@retry(stop=stop_after_attempt(self.max_retries), wait=wait_fixed(1))
def make_request():
response = requests.post(
url,
json=payload,
headers=self.headers,
stream=True,
timeout=self.timeout,
)
response.raise_for_status()
return response
def gen() -> CompletionResponseGen:
response = make_request()
text = ""
for line in response.iter_lines(decode_unicode=True):
if line.startswith("data:"):
line = line[5:] # Remove "data: " prefix
if line.strip() == "[DONE]":
break
try:
data = json.loads(line)
if "choices" in data and data["choices"]:
delta = data["choices"][0]["delta"].get("content", "")
if delta:
text += delta
yield CompletionResponse(
delta=delta, text=text, raw=data
)
except json.JSONDecodeError:
continue # Skip malformed JSON
return gen()
@llm_completion_callback()
def stream_complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponseGen:
return self._stream_complete(prompt, **kwargs)
async def _astream_complete(
self, prompt: str, **kwargs: Any
) -> CompletionResponseAsyncGen:
url = f"{self.api_base}/chat/completions"
messages = [{"role": "user", "content": prompt}]
if self.system_prompt:
messages.insert(0, {"role": "system", "content": self.system_prompt})
payload = {
"model": self.model,
"messages": messages,
"stream": True,
**self._get_all_kwargs(**kwargs),
}
@retry(stop=stop_after_attempt(self.max_retries), wait=wait_fixed(1))
async def make_request():
async with aiohttp.ClientSession() as session:
response = await session.post(
url, json=payload, headers=self.headers, timeout=self.timeout
)
response.raise_for_status()
return response
async def gen() -> CompletionResponseAsyncGen:
response = await make_request()
text = ""
async for line in response.content:
line_text = line.decode("utf-8").strip()
if line_text.startswith("data:"):
line_text = line_text[5:]
if line_text.strip() == "[DONE]":
break
try:
data = json.loads(line_text)
if "choices" in data and data["choices"]:
delta = data["choices"][0]["delta"].get("content", "")
if delta:
text += delta
yield CompletionResponse(
delta=delta, text=text, raw=data
)
except json.JSONDecodeError:
continue # Skip malformed JSON
return gen()
@llm_completion_callback()
async def astream_complete(
self, prompt: str, formatted: bool = False, **kwargs: Any
) -> CompletionResponseAsyncGen:
return await self._astream_complete(prompt, **kwargs)
def _stream_chat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponseGen:
url = f"{self.api_base}/chat/completions"
message_dicts = to_openai_message_dicts(messages)
payload = {
"model": self.model,
"messages": message_dicts,
"stream": True,
**self._get_all_kwargs(**kwargs),
}
@retry(stop=stop_after_attempt(self.max_retries), wait=wait_fixed(1))
def make_request():
response = requests.post(
url,
json=payload,
headers=self.headers,
stream=True,
timeout=self.timeout,
)
response.raise_for_status()
return response
def gen() -> ChatResponseGen:
response = make_request()
text = ""
for line in response.iter_lines(decode_unicode=True):
if line.startswith("data:"):
line = line[5:] # Remove "data: " prefix
if line.strip() == "[DONE]":
break
try:
data = json.loads(line)
if "choices" in data and data["choices"]:
delta = data["choices"][0]["delta"].get("content", "")
if delta:
text += delta
yield ChatResponse(
message=ChatMessage(role="assistant", content=text),
delta=delta,
raw=data,
)
except json.JSONDecodeError:
continue # Skip malformed JSON
return gen()
@llm_chat_callback()
def stream_chat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponseGen:
return self._stream_chat(messages, **kwargs)
async def _astream_chat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponseAsyncGen:
url = f"{self.api_base}/chat/completions"
message_dicts = to_openai_message_dicts(messages)
payload = {
"model": self.model,
"messages": message_dicts,
"stream": True,
**self._get_all_kwargs(**kwargs),
}
@retry(stop=stop_after_attempt(self.max_retries), wait=wait_fixed(1))
async def make_request():
async with aiohttp.ClientSession() as session:
response = await session.post(
url, json=payload, headers=self.headers, timeout=self.timeout
)
response.raise_for_status()
return response
async def gen():
response = await make_request()
text = ""
async for line in response.content:
line_text = line.decode("utf-8").strip()
if line_text.startswith("data:"):
line_text = line_text[5:]
if line_text.strip() == "[DONE]":
break
try:
data = json.loads(line_text)
if "choices" in data and data["choices"]:
delta = data["choices"][0]["delta"].get("content", "")
if delta:
text += delta
yield ChatResponse(
message=ChatMessage(role="assistant", content=text),
delta=delta,
raw=data,
)
except json.JSONDecodeError:
continue # Skip malformed JSON
return gen()
@llm_chat_callback()
async def astream_chat(
self, messages: Sequence[ChatMessage], **kwargs: Any
) -> ChatResponseAsyncGen:
return await self._astream_chat(messages, **kwargs)
| Perplexity |
python | plotly__plotly.py | plotly/graph_objs/scatterpolar/_legendgrouptitle.py | {
"start": 233,
"end": 2975
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatterpolar"
_path_str = "scatterpolar.legendgrouptitle"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this legend group's title font.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.scatterpolar.legendgrouptitle.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Returns
-------
plotly.graph_objs.scatterpolar.legendgrouptitle.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
@property
def text(self):
"""
Sets the title of the legend group.
The 'text' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["text"]
@text.setter
def text(self, val):
self["text"] = val
@property
def _prop_descriptions(self):
return """\
font
Sets this legend group's title font.
text
Sets the title of the legend group.
"""
def __init__(self, arg=None, font=None, text=None, **kwargs):
"""
Construct a new Legendgrouptitle object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.scatterpolar.L
egendgrouptitle`
font
Sets this legend group's title font.
text
Sets the title of the legend group.
Returns
-------
Legendgrouptitle
"""
super().__init__("legendgrouptitle")
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.scatterpolar.Legendgrouptitle
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatterpolar.Legendgrouptitle`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("font", arg, font)
self._set_property("text", arg, text)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Legendgrouptitle |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/utils/connection_wrapper.py | {
"start": 1419,
"end": 2608
} | class ____:
"""
Connection metadata data-class.
This class implements main :ref:`~airflow.models.connection.Connection` attributes
and use in AwsConnectionWrapper for avoid circular imports.
Only for internal usage, this class might change or removed in the future.
"""
conn_id: str | None = None
conn_type: str | None = None
description: str | None = None
host: str | None = None
login: str | None = None
password: str | None = None
schema: str | None = None
port: int | None = None
extra: str | dict | None = None
@property
def extra_dejson(self):
if not self.extra:
return {}
extra = deepcopy(self.extra)
if isinstance(extra, str):
try:
extra = json.loads(extra)
except json.JSONDecodeError as err:
raise AirflowException(
f"'extra' expected valid JSON-Object string. Original error:\n * {err}"
) from None
if not isinstance(extra, dict):
raise TypeError(f"Expected JSON-Object or dict, got {type(extra).__name__}.")
return extra
@dataclass
| _ConnectionMetadata |
python | scipy__scipy | scipy/signal/_ltisys.py | {
"start": 9045,
"end": 14862
} | class ____(LinearTimeInvariant):
r"""
Discrete-time linear time invariant system base class.
Parameters
----------
*system: arguments
The `dlti` class can be instantiated with either 2, 3 or 4 arguments.
The following gives the number of arguments and the corresponding
discrete-time subclass that is created:
* 2: `TransferFunction`: (numerator, denominator)
* 3: `ZerosPolesGain`: (zeros, poles, gain)
* 4: `StateSpace`: (A, B, C, D)
Each argument can be an array or a sequence.
dt: float, optional
Sampling time [s] of the discrete-time systems. Defaults to ``True``
(unspecified sampling time). Must be specified as a keyword argument,
for example, ``dt=0.1``.
See Also
--------
ZerosPolesGain, StateSpace, TransferFunction, lti
Notes
-----
`dlti` instances do not exist directly. Instead, `dlti` creates an instance
of one of its subclasses: `StateSpace`, `TransferFunction` or
`ZerosPolesGain`.
Changing the value of properties that are not directly part of the current
system representation (such as the `zeros` of a `StateSpace` system) is
very inefficient and may lead to numerical inaccuracies. It is better to
convert to the specific system representation first. For example, call
``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain.
If (numerator, denominator) is passed in for ``*system``, coefficients for
both the numerator and denominator should be specified in descending
exponent order (e.g., ``z^2 + 3z + 5`` would be represented as ``[1, 3,
5]``).
.. versionadded:: 0.18.0
Examples
--------
>>> from scipy import signal
>>> signal.dlti(1, 2, 3, 4)
StateSpaceDiscrete(
array([[1]]),
array([[2]]),
array([[3]]),
array([[4]]),
dt: True
)
>>> signal.dlti(1, 2, 3, 4, dt=0.1)
StateSpaceDiscrete(
array([[1]]),
array([[2]]),
array([[3]]),
array([[4]]),
dt: 0.1
)
Construct the transfer function
:math:`H(z) = \frac{5(z - 1)(z - 2)}{(z - 3)(z - 4)}` with a sampling time
of 0.1 seconds:
>>> signal.dlti([1, 2], [3, 4], 5, dt=0.1)
ZerosPolesGainDiscrete(
array([1, 2]),
array([3, 4]),
5,
dt: 0.1
)
Construct the transfer function :math:`H(z) = \frac{3z + 4}{1z + 2}` with
a sampling time of 0.1 seconds:
>>> signal.dlti([3, 4], [1, 2], dt=0.1)
TransferFunctionDiscrete(
array([3., 4.]),
array([1., 2.]),
dt: 0.1
)
"""
def __new__(cls, *system, **kwargs):
"""Create an instance of the appropriate subclass."""
if cls is dlti:
N = len(system)
if N == 2:
return TransferFunctionDiscrete.__new__(
TransferFunctionDiscrete, *system, **kwargs)
elif N == 3:
return ZerosPolesGainDiscrete.__new__(ZerosPolesGainDiscrete,
*system, **kwargs)
elif N == 4:
return StateSpaceDiscrete.__new__(StateSpaceDiscrete, *system,
**kwargs)
else:
raise ValueError("`system` needs to be an instance of `dlti` "
"or have 2, 3 or 4 arguments.")
# __new__ was called from a subclass, let it call its own functions
return super().__new__(cls)
def __init__(self, *system, **kwargs):
"""
Initialize the `lti` baseclass.
The heavy lifting is done by the subclasses.
"""
dt = kwargs.pop('dt', True)
super().__init__(*system, **kwargs)
self.dt = dt
@property
def dt(self):
"""Return the sampling time of the system."""
return self._dt
@dt.setter
def dt(self, dt):
self._dt = dt
def impulse(self, x0=None, t=None, n=None):
"""
Return the impulse response of the discrete-time `dlti` system.
See `dimpulse` for details.
"""
return dimpulse(self, x0=x0, t=t, n=n)
def step(self, x0=None, t=None, n=None):
"""
Return the step response of the discrete-time `dlti` system.
See `dstep` for details.
"""
return dstep(self, x0=x0, t=t, n=n)
def output(self, u, t, x0=None):
"""
Return the response of the discrete-time system to input `u`.
See `dlsim` for details.
"""
return dlsim(self, u, t, x0=x0)
def bode(self, w=None, n=100):
r"""
Calculate Bode magnitude and phase data of a discrete-time system.
Returns a 3-tuple containing arrays of frequencies [rad/s], magnitude
[dB] and phase [deg]. See `dbode` for details.
Examples
--------
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
Construct the transfer function :math:`H(z) = \frac{1}{z^2 + 2z + 3}`
with sampling time 0.5s:
>>> sys = signal.TransferFunction([1], [1, 2, 3], dt=0.5)
Equivalent: signal.dbode(sys)
>>> w, mag, phase = sys.bode()
>>> plt.figure()
>>> plt.semilogx(w, mag) # Bode magnitude plot
>>> plt.figure()
>>> plt.semilogx(w, phase) # Bode phase plot
>>> plt.show()
"""
return dbode(self, w=w, n=n)
def freqresp(self, w=None, n=10000, whole=False):
"""
Calculate the frequency response of a discrete-time system.
Returns a 2-tuple containing arrays of frequencies [rad/s] and
complex magnitude.
See `dfreqresp` for details.
"""
return dfreqresp(self, w=w, n=n, whole=whole)
| dlti |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.