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/ops/control_flow_v2_disable_test.py | {
"start": 1080,
"end": 1303
} | class ____(test.TestCase):
def testIsDisabled(self):
self.assertTrue(tf2.enabled())
self.assertFalse(control_flow_util.ENABLE_CONTROL_FLOW_V2)
if __name__ == "__main__":
googletest.main()
| ControlFlowV2DisableTest |
python | Farama-Foundation__Gymnasium | gymnasium/wrappers/vector/vectorize_action.py | {
"start": 8698,
"end": 10769
} | class ____(VectorizeTransformAction):
"""Affinely rescales the continuous action space of the environment to the range [min_action, max_action].
Example - Without action scaling:
>>> import numpy as np
>>> import gymnasium as gym
>>> envs = gym.make_vec("MountainCarContinuous-v0", num_envs=3)
>>> _ = envs.action_space.seed(123)
>>> obs, info = envs.reset(seed=123)
>>> for _ in range(10):
... obs, rew, term, trunc, info = envs.step(0.5 * np.ones((3, 1)))
...
>>> envs.close()
>>> obs
array([[-0.44799727, 0.00266526],
[-0.4351738 , 0.00133522],
[-0.42683297, 0.00048403]], dtype=float32)
Example - With action scaling:
>>> import numpy as np
>>> import gymnasium as gym
>>> envs = gym.make_vec("MountainCarContinuous-v0", num_envs=3)
>>> envs = RescaleAction(envs, 0.0, 1.0)
>>> _ = envs.action_space.seed(123)
>>> obs, info = envs.reset(seed=123)
>>> for _ in range(10):
... obs, rew, term, trunc, info = envs.step(0.5 * np.ones((3, 1)))
...
>>> envs.close()
>>> obs
array([[-0.48657528, -0.00395268],
[-0.47377947, -0.00529102],
[-0.46546045, -0.00614867]], dtype=float32)
"""
def __init__(
self,
env: VectorEnv,
min_action: float | int | np.ndarray,
max_action: float | int | np.ndarray,
):
"""Initializes the :class:`RescaleAction` wrapper.
Args:
env (Env): The vector environment to wrap
min_action (float, int or np.ndarray): The min values for each action. This may be a numpy array or a scalar.
max_action (float, int or np.ndarray): The max values for each action. This may be a numpy array or a scalar.
"""
super().__init__(
env,
transform_action.RescaleAction,
min_action=min_action,
max_action=max_action,
)
| RescaleAction |
python | numba__numba | numba/cuda/simulator/kernel.py | {
"start": 1522,
"end": 4996
} | class ____(object):
'''
Wraps a @cuda.jit-ed function.
'''
def __init__(
self, fn, device, fastmath=False, extensions=None, debug=False
):
if extensions is None:
extensions = []
self.fn = fn
self._device = device
self._fastmath = fastmath
self._debug = debug
self.extensions = list(extensions) # defensive copy
# Initial configuration: grid unconfigured, stream 0, no dynamic shared
# memory.
self.grid_dim = None
self.block_dim = None
self.stream = 0
self.dynshared_size = 0
functools.update_wrapper(self, fn)
def __call__(self, *args):
if self._device:
with swapped_cuda_module(self.fn, _get_kernel_context()):
return self.fn(*args)
# Ensure we've been given a valid grid configuration
grid_dim, block_dim = normalize_kernel_dimensions(self.grid_dim,
self.block_dim)
fake_cuda_module = FakeCUDAModule(grid_dim, block_dim,
self.dynshared_size)
with _push_kernel_context(fake_cuda_module):
# fake_args substitutes all numpy arrays for FakeCUDAArrays
# because they implement some semantics differently
retr = []
def fake_arg(arg):
# map the arguments using any extension you've registered
_, arg = functools.reduce(
lambda ty_val, extension: extension.prepare_args(
*ty_val,
stream=0,
retr=retr),
self.extensions,
(None, arg)
)
if isinstance(arg, np.ndarray) and arg.ndim > 0:
ret = wrap_arg(arg).to_device(retr)
elif isinstance(arg, ArgHint):
ret = arg.to_device(retr)
elif isinstance(arg, np.void):
ret = FakeCUDAArray(arg) # In case a np record comes in.
else:
ret = arg
if isinstance(ret, FakeCUDAArray):
return FakeWithinKernelCUDAArray(ret)
return ret
fake_args = [fake_arg(arg) for arg in args]
with swapped_cuda_module(self.fn, fake_cuda_module):
# Execute one block at a time
for grid_point in np.ndindex(*grid_dim):
bm = BlockManager(self.fn, grid_dim, block_dim, self._debug)
bm.run(grid_point, *fake_args)
for wb in retr:
wb()
def __getitem__(self, configuration):
self.grid_dim, self.block_dim = \
normalize_kernel_dimensions(*configuration[:2])
if len(configuration) == 4:
self.dynshared_size = configuration[3]
return self
def bind(self):
pass
def specialize(self, *args):
return self
def forall(self, ntasks, tpb=0, stream=0, sharedmem=0):
if ntasks < 0:
raise ValueError("Can't create ForAll with negative task count: %s"
% ntasks)
return self[ntasks, 1, stream, sharedmem]
@property
def overloads(self):
return FakeOverloadDict()
@property
def py_func(self):
return self.fn
# Thread emulation
| FakeCUDAKernel |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/errors.py | {
"start": 8020,
"end": 8326
} | class ____(DagsterError):
"""Thrown when the user specifies execution step keys that do not exist."""
def __init__(self, *args, **kwargs):
self.step_keys = check.list_param(kwargs.pop("step_keys"), "step_keys", str)
super().__init__(*args, **kwargs)
| DagsterExecutionStepNotFoundError |
python | django__django | tests/decorators/test_cache.py | {
"start": 4115,
"end": 4512
} | class ____(SimpleTestCase):
def test_cache_page(self):
def my_view(request):
return "response"
my_view_cached = cache_page(123)(my_view)
self.assertEqual(my_view_cached(HttpRequest()), "response")
my_view_cached2 = cache_page(123, key_prefix="test")(my_view)
self.assertEqual(my_view_cached2(HttpRequest()), "response")
| CachePageDecoratorTest |
python | tensorflow__tensorflow | tensorflow/python/distribute/cluster_resolver/sagemaker_cluster_resolver.py | {
"start": 2286,
"end": 6784
} | class ____(ClusterResolver):
"""Implementation of a ClusterResolver which reads the Sagemaker EnvVars. This is an implementation of cluster resolvers when running in a SageMaker environment to set information about the cluster.
The cluster spec returned will be initialized from the SageMaker
environment variables.
Currently this Cluster Resolver only supports Multi-Worker Mirrored Strategy.
It assumes all nodes in a SageMaker Cluster are workers.
"""
def __init__(self,
port=2223,
task_type=None,
task_id=None,
rpc_layer=None,
environment=None):
"""Creates a new SageMakerClusterResolver.
Args:
port: (integer, optional) Override default port usage of 2223
task_type: (String, optional) Overrides the task type.
task_id: (Integer, optional) Overrides the task index.
rpc_layer: (String, optional) Overrides the rpc layer TensorFlow uses.
environment: (String, optional) Overrides the environment TensorFlow
operates in.
"""
self._task_type = task_type
self._task_id = task_id
self._rpc_layer = rpc_layer
self._environment = environment
self._port = str(port)
@property
def task_type(self):
if self._task_type is None:
task_info = _get_value_in_tfconfig(_TASK_KEY, self._port, {})
return str(task_info['type']) if 'type' in task_info else None
else:
return str(self._task_type)
@property
def task_id(self):
if self._task_id is None:
task_info = _get_value_in_tfconfig(_TASK_KEY, self._port, {})
return int(task_info['index']) if 'index' in task_info else None
else:
return int(self._task_id)
@task_type.setter
def task_type(self, task_type):
self._task_type = task_type
@task_id.setter
def task_id(self, task_id):
self._task_id = task_id
@property
def environment(self):
return self._environment
@property
def rpc_layer(self):
if self._rpc_layer is None:
return _get_value_in_tfconfig(_RPC_LAYER_KEY, self._port)
else:
return self._rpc_layer
@rpc_layer.setter
def rpc_layer(self, rpc_layer):
self._rpc_layer = rpc_layer
def num_accelerators(self, task_type=None, task_id=None, config_proto=None):
task_type = self.task_type if task_type is None else task_type
task_id = self.task_id if task_id is None else task_id
return super(SageMakerClusterResolver,
self).num_accelerators(task_type, task_id, config_proto)
def cluster_spec(self):
"""Returns a ClusterSpec based on the SageMaker environment variables.
Returns:
A ClusterSpec with information from the SageMaker environment variables.
"""
tf_config = _load_tf_config(self._port)
if 'cluster' not in tf_config:
return ClusterSpec({})
return ClusterSpec(tf_config['cluster'])
def master(self, task_type=None, task_id=None, rpc_layer=None):
"""Returns the master address to use when creating a TensorFlow session.
Note: this is only useful for TensorFlow 1.x.
Args:
task_type: (String, optional) Overrides and sets the task_type of the
master.
task_id: (Integer, optional) Overrides and sets the task id of the master.
rpc_layer: (String, optional) Overrides and sets the protocol over which
TensorFlow nodes communicate with each other.
Returns:
The address of the master.
Raises:
RuntimeError: If the task_type or task_id is not specified and the
SageMaker environment variables does not contain a task section.
"""
# If `session_master` is set, just use that.
session_master = _get_value_in_tfconfig(_SESSION_MASTER_KEY, self._port)
if session_master is not None:
return session_master
# Return an empty string if we are the only job in the ClusterSpec.
cluster_spec = self.cluster_spec()
if (not cluster_spec.jobs or
(len(cluster_spec.jobs) == 1 and
len(cluster_spec.job_tasks(cluster_spec.jobs[0])) == 1)):
return ''
# We try to auto-detect the task type and id, but uses the user-supplied one
# where available
task_type = task_type if task_type is not None else self.task_type
task_id = task_id if task_id is not None else self.task_id
rpc_layer = rpc_layer if rpc_layer is not None else self.rpc_layer
return format_master_url(
cluster_spec.task_address(task_type, task_id), rpc_layer)
| SageMakerClusterResolver |
python | dagster-io__dagster | python_modules/dagster/dagster/_grpc/types.py | {
"start": 19034,
"end": 20551
} | class ____(
NamedTuple(
"_JobSubsetSnapshotArgs",
[
("job_origin", RemoteJobOrigin),
("op_selection", Optional[Sequence[str]]),
("asset_selection", Optional[AbstractSet[AssetKey]]),
("asset_check_selection", Optional[AbstractSet[AssetCheckKey]]),
("include_parent_snapshot", bool),
],
)
):
def __new__(
cls,
job_origin: RemoteJobOrigin,
op_selection: Optional[Sequence[str]],
asset_selection: Optional[AbstractSet[AssetKey]] = None,
asset_check_selection: Optional[AbstractSet[AssetCheckKey]] = None,
include_parent_snapshot: Optional[bool] = None,
):
return super().__new__(
cls,
job_origin=check.inst_param(job_origin, "job_origin", RemoteJobOrigin),
op_selection=check.opt_nullable_sequence_param(
op_selection, "op_selection", of_type=str
),
asset_selection=check.opt_nullable_set_param(asset_selection, "asset_selection"),
asset_check_selection=check.opt_nullable_set_param(
asset_check_selection, "asset_check_selection"
),
include_parent_snapshot=(
include_parent_snapshot if include_parent_snapshot is not None else True
),
)
# Different storage field name for backcompat
@whitelist_for_serdes(storage_field_names={"code_location_origin": "repository_location_origin"})
| JobSubsetSnapshotArgs |
python | tensorflow__tensorflow | tensorflow/python/framework/ops_enable_eager_test.py | {
"start": 885,
"end": 1752
} | class ____(googletest.TestCase):
def setUp(self):
super().setUp()
# test for enable eager test
ops.enable_eager_execution()
self.assertTrue(context.executing_eagerly())
# Calling enable eager execution a second time should not cause an error.
ops.enable_eager_execution()
self.assertTrue(context.executing_eagerly())
def testEnableDisableEagerExecution(self):
# The entirety of the test runs in setUp/tearDown methods
pass
def tearDown(self):
super().tearDown()
# test for disable eager test
ops.disable_eager_execution()
self.assertFalse(context.executing_eagerly())
# Calling disable eager execution a second time should not cause an error.
ops.disable_eager_execution()
self.assertFalse(context.executing_eagerly())
if __name__ == '__main__':
googletest.main()
| OpsEnableAndDisableEagerTest |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip_text.py | {
"start": 20213,
"end": 20920
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = BlipTextPredictionHeadTransform(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->BlipText
| BlipTextLMPredictionHead |
python | huggingface__transformers | src/transformers/models/wavlm/modeling_wavlm.py | {
"start": 4153,
"end": 11230
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
num_buckets: int = 320,
max_distance: int = 800,
has_relative_position_bias: bool = True,
):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
if (self.head_dim * num_heads) != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
f" and `num_heads`: {num_heads})."
)
self.scaling = self.head_dim**-0.5
self.k_proj = nn.Linear(embed_dim, embed_dim)
self.v_proj = nn.Linear(embed_dim, embed_dim)
self.q_proj = nn.Linear(embed_dim, embed_dim)
self.out_proj = nn.Linear(embed_dim, embed_dim)
self.num_buckets = num_buckets
self.max_distance = max_distance
self.gru_rel_pos_const = nn.Parameter(torch.ones(1, self.num_heads, 1, 1))
self.gru_rel_pos_linear = nn.Linear(self.head_dim, 8)
if has_relative_position_bias:
self.rel_attn_embed = nn.Embedding(self.num_buckets, self.num_heads)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_bias: Optional[torch.Tensor] = None,
output_attentions: bool = False,
index=0,
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
"""Attention layer with relative attention"""
bsz, tgt_len, _ = hidden_states.size()
# first pass of attention layer creates position bias
if position_bias is None:
position_bias = self.compute_bias(tgt_len, tgt_len)
position_bias = (
position_bias.unsqueeze(0).repeat(bsz, 1, 1, 1).view(bsz * self.num_heads, tgt_len, tgt_len)
)
# Compute relative position bias:
# 1) get reshape hidden_states
gated_hidden_states = hidden_states.view(hidden_states.shape[:-1] + (self.num_heads, -1))
gated_hidden_states = gated_hidden_states.permute(0, 2, 1, 3)
# 2) project hidden states
relative_position_proj = self.gru_rel_pos_linear(gated_hidden_states)
relative_position_proj = relative_position_proj.view(gated_hidden_states.shape[:-1] + (2, 4)).sum(-1)
# 3) compute gate for position bias from projected hidden states
gate_a, gate_b = torch.sigmoid(relative_position_proj).chunk(2, dim=-1)
gate_output = gate_a * (gate_b * self.gru_rel_pos_const - 1.0) + 2.0
# 4) apply gate to position bias to compute gated position_bias
gated_position_bias = gate_output.view(bsz * self.num_heads, -1, 1) * position_bias
gated_position_bias = gated_position_bias.view((-1, tgt_len, tgt_len))
attn_output, attn_weights = self.torch_multi_head_self_attention(
hidden_states, attention_mask, gated_position_bias, output_attentions
)
return attn_output, attn_weights, position_bias
def torch_multi_head_self_attention(
self,
hidden_states: torch.FloatTensor,
attention_mask: Union[torch.LongTensor, torch.BoolTensor],
gated_position_bias: torch.FloatTensor,
output_attentions: bool,
) -> tuple[torch.FloatTensor, torch.FloatTensor]:
"""simple wrapper around torch's multi_head_attention_forward function"""
# self-attention assumes q = k = v
query = key = value = hidden_states.transpose(0, 1)
key_padding_mask = attention_mask.ne(1) if attention_mask is not None else None
# disable bias and add_zero_attn
bias_k = bias_v = None
add_zero_attn = False
# PyTorch 1.3.0 has F.multi_head_attention_forward defined
# so no problem with backwards compatibility
attn_output, attn_weights = F.multi_head_attention_forward(
query,
key,
value,
self.embed_dim,
self.num_heads,
torch.empty([0]),
torch.cat((self.q_proj.bias, self.k_proj.bias, self.v_proj.bias)),
bias_k,
bias_v,
add_zero_attn,
self.dropout,
self.out_proj.weight,
self.out_proj.bias,
self.training,
key_padding_mask,
output_attentions,
gated_position_bias,
use_separate_proj_weight=True,
q_proj_weight=self.q_proj.weight,
k_proj_weight=self.k_proj.weight,
v_proj_weight=self.v_proj.weight,
)
# [Seq_Len, Batch Size, ...] -> [Batch Size, Seq_Len, ...]
attn_output = attn_output.transpose(0, 1)
if attn_weights is not None:
# IMPORTANT: Attention weights are averaged weights
# here which should not be the case. This is an open issue
# on PyTorch: https://github.com/pytorch/pytorch/issues/32590
attn_weights = attn_weights[:, None].broadcast_to(
attn_weights.shape[:1] + (self.num_heads,) + attn_weights.shape[1:]
)
return attn_output, attn_weights
def compute_bias(self, query_length: int, key_length: int) -> torch.FloatTensor:
context_position = torch.arange(query_length, dtype=torch.long)[:, None]
memory_position = torch.arange(key_length, dtype=torch.long)[None, :]
relative_position = memory_position - context_position
relative_position_bucket = self._relative_positions_bucket(relative_position)
relative_position_bucket = relative_position_bucket.to(self.rel_attn_embed.weight.device)
values = self.rel_attn_embed(relative_position_bucket)
values = values.permute([2, 0, 1])
return values
def _relative_positions_bucket(self, relative_positions: torch.FloatTensor) -> torch.FloatTensor:
num_buckets = self.num_buckets // 2
relative_buckets = (relative_positions > 0).to(torch.long) * num_buckets
relative_positions = torch.abs(relative_positions)
max_exact = num_buckets // 2
is_small = relative_positions < max_exact
relative_positions_if_large = torch.log(relative_positions.float() / max_exact)
relative_positions_if_large = relative_positions_if_large / math.log(self.max_distance / max_exact)
relative_positions_if_large = relative_positions_if_large * (num_buckets - max_exact)
relative_position_if_large = (max_exact + relative_positions_if_large).to(torch.long)
relative_position_if_large = torch.min(
relative_position_if_large, torch.full_like(relative_position_if_large, num_buckets - 1)
)
relative_buckets += torch.where(is_small, relative_positions, relative_position_if_large)
return relative_buckets
| WavLMAttention |
python | aimacode__aima-python | deep_learning4e.py | {
"start": 1447,
"end": 1597
} | class ____(Activation):
def function(self, x):
return max(0, x)
def derivative(self, value):
return 1 if value > 0 else 0
| ReLU |
python | encode__django-rest-framework | rest_framework/parsers.py | {
"start": 3856,
"end": 7717
} | class ____(BaseParser):
"""
Parser for file upload data.
"""
media_type = '*/*'
errors = {
'unhandled': 'FileUpload parse error - none of upload handlers can handle the stream',
'no_filename': 'Missing filename. Request should include a Content-Disposition header with a filename parameter.',
}
def parse(self, stream, media_type=None, parser_context=None):
"""
Treats the incoming bytestream as a raw file upload and returns
a `DataAndFiles` object.
`.data` will be None (we expect request body to be a file content).
`.files` will be a `QueryDict` containing one 'file' element.
"""
parser_context = parser_context or {}
request = parser_context['request']
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
meta = request.META
upload_handlers = request.upload_handlers
filename = self.get_filename(stream, media_type, parser_context)
if not filename:
raise ParseError(self.errors['no_filename'])
# Note that this code is extracted from Django's handling of
# file uploads in MultiPartParser.
content_type = meta.get('HTTP_CONTENT_TYPE',
meta.get('CONTENT_TYPE', ''))
try:
content_length = int(meta.get('HTTP_CONTENT_LENGTH',
meta.get('CONTENT_LENGTH', 0)))
except (ValueError, TypeError):
content_length = None
# See if the handler will want to take care of the parsing.
for handler in upload_handlers:
result = handler.handle_raw_input(stream,
meta,
content_length,
None,
encoding)
if result is not None:
return DataAndFiles({}, {'file': result[1]})
# This is the standard case.
possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size]
chunk_size = min([2 ** 31 - 4] + possible_sizes)
chunks = ChunkIter(stream, chunk_size)
counters = [0] * len(upload_handlers)
for index, handler in enumerate(upload_handlers):
try:
handler.new_file(None, filename, content_type,
content_length, encoding)
except StopFutureHandlers:
upload_handlers = upload_handlers[:index + 1]
break
for chunk in chunks:
for index, handler in enumerate(upload_handlers):
chunk_length = len(chunk)
chunk = handler.receive_data_chunk(chunk, counters[index])
counters[index] += chunk_length
if chunk is None:
break
for index, handler in enumerate(upload_handlers):
file_obj = handler.file_complete(counters[index])
if file_obj is not None:
return DataAndFiles({}, {'file': file_obj})
raise ParseError(self.errors['unhandled'])
def get_filename(self, stream, media_type, parser_context):
"""
Detects the uploaded file name. First searches a 'filename' url kwarg.
Then tries to parse Content-Disposition header.
"""
with contextlib.suppress(KeyError):
return parser_context['kwargs']['filename']
with contextlib.suppress(AttributeError, KeyError, ValueError):
meta = parser_context['request'].META
disposition, params = parse_header_parameters(meta['HTTP_CONTENT_DISPOSITION'])
if 'filename*' in params:
return params['filename*']
return params['filename']
| FileUploadParser |
python | eventlet__eventlet | tests/greenpool_test.py | {
"start": 237,
"end": 9715
} | class ____(tests.LimitedTestCase):
def test_spawn(self):
p = eventlet.GreenPool(4)
waiters = []
for i in range(10):
waiters.append(p.spawn(passthru, i))
results = [waiter.wait() for waiter in waiters]
self.assertEqual(results, list(range(10)))
def test_spawn_n(self):
p = eventlet.GreenPool(4)
results_closure = []
def do_something(a):
eventlet.sleep(0.01)
results_closure.append(a)
for i in range(10):
p.spawn(do_something, i)
p.waitall()
self.assertEqual(results_closure, list(range(10)))
def test_waiting(self):
pool = eventlet.GreenPool(1)
done = eventlet.Event()
def consume():
done.wait()
def waiter(pool):
gt = pool.spawn(consume)
gt.wait()
waiters = []
self.assertEqual(pool.running(), 0)
waiters.append(eventlet.spawn(waiter, pool))
eventlet.sleep(0)
self.assertEqual(pool.waiting(), 0)
waiters.append(eventlet.spawn(waiter, pool))
eventlet.sleep(0)
self.assertEqual(pool.waiting(), 1)
waiters.append(eventlet.spawn(waiter, pool))
eventlet.sleep(0)
self.assertEqual(pool.waiting(), 2)
self.assertEqual(pool.running(), 1)
done.send(None)
for w in waiters:
w.wait()
self.assertEqual(pool.waiting(), 0)
self.assertEqual(pool.running(), 0)
def test_multiple_coros(self):
evt = eventlet.Event()
results = []
def producer():
results.append('prod')
evt.send()
def consumer():
results.append('cons1')
evt.wait()
results.append('cons2')
pool = eventlet.GreenPool(2)
done = pool.spawn(consumer)
pool.spawn_n(producer)
done.wait()
self.assertEqual(['cons1', 'prod', 'cons2'], results)
def test_timer_cancel(self):
# this test verifies that local timers are not fired
# outside of the context of the spawn
timer_fired = []
def fire_timer():
timer_fired.append(True)
def some_work():
hubs.get_hub().schedule_call_local(0, fire_timer)
pool = eventlet.GreenPool(2)
worker = pool.spawn(some_work)
worker.wait()
eventlet.sleep(0)
eventlet.sleep(0)
self.assertEqual(timer_fired, [])
def test_reentrant(self):
pool = eventlet.GreenPool(1)
def reenter():
waiter = pool.spawn(lambda a: a, 'reenter')
self.assertEqual('reenter', waiter.wait())
outer_waiter = pool.spawn(reenter)
outer_waiter.wait()
evt = eventlet.Event()
def reenter_async():
pool.spawn_n(lambda a: a, 'reenter')
evt.send('done')
pool.spawn_n(reenter_async)
self.assertEqual('done', evt.wait())
def assert_pool_has_free(self, pool, num_free):
self.assertEqual(pool.free(), num_free)
def wait_long_time(e):
e.wait()
timer = eventlet.Timeout(1)
try:
evt = eventlet.Event()
for x in range(num_free):
pool.spawn(wait_long_time, evt)
# if the pool has fewer free than we expect,
# then we'll hit the timeout error
finally:
timer.cancel()
# if the runtime error is not raised it means the pool had
# some unexpected free items
timer = eventlet.Timeout(0, RuntimeError)
try:
self.assertRaises(RuntimeError, pool.spawn, wait_long_time, evt)
finally:
timer.cancel()
# clean up by causing all the wait_long_time functions to return
evt.send(None)
eventlet.sleep(0)
eventlet.sleep(0)
def test_resize(self):
pool = eventlet.GreenPool(2)
evt = eventlet.Event()
def wait_long_time(e):
e.wait()
pool.spawn(wait_long_time, evt)
pool.spawn(wait_long_time, evt)
self.assertEqual(pool.free(), 0)
self.assertEqual(pool.running(), 2)
self.assert_pool_has_free(pool, 0)
# verify that the pool discards excess items put into it
pool.resize(1)
# cause the wait_long_time functions to return, which will
# trigger puts to the pool
evt.send(None)
eventlet.sleep(0)
eventlet.sleep(0)
self.assertEqual(pool.free(), 1)
self.assertEqual(pool.running(), 0)
self.assert_pool_has_free(pool, 1)
# resize larger and assert that there are more free items
pool.resize(2)
self.assertEqual(pool.free(), 2)
self.assertEqual(pool.running(), 0)
self.assert_pool_has_free(pool, 2)
def test_pool_smash(self):
# The premise is that a coroutine in a Pool tries to get a token out
# of a token pool but times out before getting the token. We verify
# that neither pool is adversely affected by this situation.
pool = eventlet.GreenPool(1)
tp = pools.TokenPool(max_size=1)
tp.get() # empty out the pool
def do_receive(tp):
timer = eventlet.Timeout(0, RuntimeError())
try:
tp.get()
self.fail("Shouldn't have received anything from the pool")
except RuntimeError:
return 'timed out'
else:
timer.cancel()
# the spawn makes the token pool expect that coroutine, but then
# immediately cuts bait
e1 = pool.spawn(do_receive, tp)
self.assertEqual(e1.wait(), 'timed out')
# the pool can get some random item back
def send_wakeup(tp):
tp.put('wakeup')
gt = eventlet.spawn(send_wakeup, tp)
# now we ask the pool to run something else, which should not
# be affected by the previous send at all
def resume():
return 'resumed'
e2 = pool.spawn(resume)
self.assertEqual(e2.wait(), 'resumed')
# we should be able to get out the thing we put in there, too
self.assertEqual(tp.get(), 'wakeup')
gt.wait()
def test_spawn_n_2(self):
p = eventlet.GreenPool(2)
self.assertEqual(p.free(), 2)
r = []
def foo(a):
r.append(a)
gt = p.spawn(foo, 1)
self.assertEqual(p.free(), 1)
gt.wait()
self.assertEqual(r, [1])
eventlet.sleep(0)
self.assertEqual(p.free(), 2)
# Once the pool is exhausted, spawning forces a yield.
p.spawn_n(foo, 2)
self.assertEqual(1, p.free())
self.assertEqual(r, [1])
p.spawn_n(foo, 3)
self.assertEqual(0, p.free())
self.assertEqual(r, [1])
p.spawn_n(foo, 4)
self.assertEqual(set(r), {1, 2, 3})
eventlet.sleep(0)
self.assertEqual(set(r), {1, 2, 3, 4})
def test_exceptions(self):
p = eventlet.GreenPool(2)
for m in (p.spawn, p.spawn_n):
self.assert_pool_has_free(p, 2)
m(raiser, RuntimeError())
self.assert_pool_has_free(p, 1)
p.waitall()
self.assert_pool_has_free(p, 2)
m(raiser, greenlet.GreenletExit)
self.assert_pool_has_free(p, 1)
p.waitall()
self.assert_pool_has_free(p, 2)
def test_imap(self):
p = eventlet.GreenPool(4)
result_list = list(p.imap(passthru, range(10)))
self.assertEqual(result_list, list(range(10)))
def test_empty_imap(self):
p = eventlet.GreenPool(4)
result_iter = p.imap(passthru, [])
self.assertRaises(StopIteration, result_iter.next)
def test_imap_nonefunc(self):
p = eventlet.GreenPool(4)
result_list = list(p.imap(None, range(10)))
self.assertEqual(result_list, [(x,) for x in range(10)])
def test_imap_multi_args(self):
p = eventlet.GreenPool(4)
result_list = list(p.imap(passthru2, range(10), range(10, 20)))
self.assertEqual(result_list, list(zip(range(10), range(10, 20))))
def test_imap_raises(self):
# testing the case where the function raises an exception;
# both that the caller sees that exception, and that the iterator
# continues to be usable to get the rest of the items
p = eventlet.GreenPool(4)
def raiser(item):
if item == 1 or item == 7:
raise RuntimeError("intentional error")
else:
return item
it = p.imap(raiser, range(10))
results = []
while True:
try:
results.append(next(it))
except RuntimeError:
results.append('r')
except StopIteration:
break
self.assertEqual(results, [0, 'r', 2, 3, 4, 5, 6, 'r', 8, 9])
def test_starmap(self):
p = eventlet.GreenPool(4)
result_list = list(p.starmap(passthru, [(x,) for x in range(10)]))
self.assertEqual(result_list, list(range(10)))
def test_waitall_on_nothing(self):
p = eventlet.GreenPool()
p.waitall()
def test_recursive_waitall(self):
p = eventlet.GreenPool()
gt = p.spawn(p.waitall)
self.assertRaises(AssertionError, gt.wait)
| GreenPool |
python | pytorch__pytorch | test/cpp_extensions/open_registration_extension/torch_openreg/tests/test_memory.py | {
"start": 199,
"end": 7291
} | class ____(TestCase):
"""Test cases for OpenRegDeviceAllocator functionality."""
def setUp(self):
"""Reset memory state before each test."""
# Force garbage collection to ensure clean state
gc.collect()
# Note: We can't directly reset allocator stats without C++ API,
# but we can ensure tensors are properly released
def test_basic_allocation(self):
"""Test basic memory allocation with various sizes."""
# Small allocation
x = torch.empty(100, device="openreg")
self.assertEqual(x.device.type, "openreg")
self.assertEqual(x.numel(), 100)
# Large allocation
z = torch.empty(10000, device="openreg")
self.assertEqual(z.device.type, "openreg")
self.assertEqual(z.numel(), 10000)
# Multi-dimensional allocation
w = torch.empty(10, 20, 30, device="openreg")
self.assertEqual(w.device.type, "openreg")
self.assertEqual(w.shape, torch.Size([10, 20, 30]))
def test_memory_lifecycle(self):
"""Test complete memory allocation and deallocation lifecycle."""
# Allocate tensor
x = torch.empty(1000, device="openreg")
self.assertEqual(x.device.type, "openreg")
# Explicitly delete tensor
del x
gc.collect()
# Allocate again to ensure memory was freed
y = torch.empty(1000, device="openreg")
self.assertEqual(y.device.type, "openreg")
del y
gc.collect()
def test_tensor_copy_operations(self):
"""Test memory operations during tensor copies."""
# CPU to OpenReg
cpu_tensor = torch.randn(100)
openreg_tensor = cpu_tensor.to("openreg")
self.assertEqual(openreg_tensor.device.type, "openreg")
self.assertEqual(cpu_tensor.shape, openreg_tensor.shape)
# OpenReg to CPU
back_to_cpu = openreg_tensor.to("cpu")
self.assertEqual(back_to_cpu.device.type, "cpu")
self.assertTrue(torch.allclose(cpu_tensor, back_to_cpu))
# OpenReg to OpenReg (clone)
cloned = openreg_tensor.clone()
self.assertEqual(cloned.device.type, "openreg")
self.assertTrue(torch.allclose(openreg_tensor.cpu(), cloned.cpu()))
def test_inplace_operations(self):
"""Test memory stability during inplace operations."""
x = torch.ones(100, device="openreg")
original_data_ptr = x.data_ptr()
# Inplace addition
x.add_(1)
self.assertEqual(x.data_ptr(), original_data_ptr)
self.assertTrue(torch.all(x == 2))
# Inplace multiplication
x.mul_(2)
self.assertEqual(x.data_ptr(), original_data_ptr)
self.assertTrue(torch.all(x == 4))
def test_view_operations(self):
"""Test that views share memory correctly."""
x = torch.randn(100, device="openreg")
original_data_ptr = x.data_ptr()
# Reshape view
y = x.view(10, 10)
self.assertEqual(y.data_ptr(), original_data_ptr)
self.assertEqual(y.shape, torch.Size([10, 10]))
# Slice view
z = x[10:20]
# Slices may have different data_ptr but should share storage
self.assertEqual(z.numel(), 10)
def test_different_dtypes(self):
"""Test allocation with different data types."""
dtypes = [torch.float32, torch.float64, torch.int32, torch.int64]
for dtype in dtypes:
x = torch.empty(100, dtype=dtype, device="openreg")
self.assertEqual(x.device.type, "openreg")
self.assertEqual(x.dtype, dtype)
self.assertEqual(x.numel(), 100)
def test_tensor_resize(self):
"""Test tensor resizing operations."""
x = torch.empty(100, device="openreg")
_ = x.data_ptr()
# Resize to smaller size (should reuse storage)
x.resize_(50)
self.assertEqual(x.numel(), 50)
# Storage should still be available
# Resize to original size
x.resize_(100)
self.assertEqual(x.numel(), 100)
def test_empty_cache_operation(self):
"""Test empty cache functionality."""
# Allocate some tensors
x = torch.empty(1000, device="openreg")
y = torch.empty(2000, device="openreg")
# Delete tensors
del x, y
gc.collect()
# Note: OpenRegDeviceAllocator.emptyCache is currently a no-op
# This test ensures it doesn't crash
torch.cuda.empty_cache() if torch.cuda.is_available() else None
def test_memory_format_allocation(self):
"""Test allocation with different memory formats."""
# Channels last format
x = torch.empty(2, 3, 4, 4, device="openreg", memory_format=torch.channels_last)
self.assertEqual(x.device.type, "openreg")
self.assertTrue(x.is_contiguous(memory_format=torch.channels_last))
# Contiguous format (default)
y = torch.empty(
2, 3, 4, 4, device="openreg", memory_format=torch.contiguous_format
)
self.assertEqual(y.device.type, "openreg")
self.assertTrue(y.is_contiguous())
def test_large_allocation(self):
"""Test large memory allocation."""
# Allocate a large tensor (10MB approximately)
size = 10 * 1024 * 1024 // 4 # 10MB in float32
x = torch.empty(size, device="openreg")
self.assertEqual(x.device.type, "openreg")
self.assertEqual(x.numel(), size)
def test_sequential_allocations_and_deallocations(self):
"""Test sequential allocation and deallocation patterns."""
for i in range(10):
x = torch.empty(1000 + i * 100, device="openreg")
self.assertEqual(x.device.type, "openreg")
# Let tensor go out of scope
del x
gc.collect()
def test_allocation_with_requires_grad(self):
"""Test allocation of tensors with gradient tracking."""
x = torch.empty(100, device="openreg", requires_grad=True)
self.assertEqual(x.device.type, "openreg")
self.assertTrue(x.requires_grad)
y = torch.randn(100, device="openreg", requires_grad=True)
self.assertEqual(y.device.type, "openreg")
self.assertTrue(y.requires_grad)
def test_storage_operations(self):
"""Test storage-level operations."""
x = torch.randn(100, device="openreg")
storage = x.storage()
# Verify storage is on correct device
self.assertTrue(storage.device.type == "openreg")
# Verify storage size
self.assertGreaterEqual(storage.size(), x.numel())
def test_tensor_from_blob(self):
"""Test creating tensors that reference existing memory."""
x = torch.randn(100, device="openreg")
# Create a view that references the same data
y = x.view_as(x)
# They should share the same underlying storage
self.assertEqual(x.data_ptr(), y.data_ptr())
# Modifying one should affect the other
x.fill_(5.0)
self.assertTrue(torch.all(y == 5.0))
| TestDeviceAllocator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-zendesk-support/unit_tests/integrations/zs_requests/ticket_forms_request_bilder.py | {
"start": 274,
"end": 1070
} | class ____(ZendeskSupportBaseRequestBuilder):
@classmethod
def ticket_forms_endpoint(cls, authenticator: Authenticator) -> "TicketFormsRequestBuilder":
return cls("d3v-airbyte", "ticket_forms").with_authenticator(authenticator)
def __init__(self, subdomain: str, resource: str) -> None:
super().__init__(subdomain, resource)
self._start_time: int = None
@property
def query_params(self):
params = super().query_params or {}
if self._start_time:
params["start_time"] = self._start_time
return params
def with_start_time(self, start_time: int) -> "TicketFormsRequestBuilder":
self._start_time: int = calendar.timegm(ab_datetime_parse(start_time).utctimetuple())
return self
| TicketFormsRequestBuilder |
python | matplotlib__matplotlib | lib/matplotlib/image.py | {
"start": 53836,
"end": 72007
} | class ____(_ImageBase):
"""
The Image class whose size is determined by the given bbox.
Parameters
----------
bbox : BboxBase or Callable[RendererBase, BboxBase]
The bbox or a function to generate the bbox
.. warning ::
If using `matplotlib.artist.Artist.get_window_extent` as the
callable ensure that the other artist is drawn first (lower zorder)
or you may need to renderer the figure twice to ensure that the
computed bbox is accurate.
cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
The Colormap instance or registered colormap name used to map scalar
data to colors.
norm : str or `~matplotlib.colors.Normalize`
Maps luminance to 0-1.
interpolation : str, default: :rc:`image.interpolation`
Supported values are 'none', 'auto', 'nearest', 'bilinear',
'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite',
'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell',
'sinc', 'lanczos', 'blackman'.
origin : {'upper', 'lower'}, default: :rc:`image.origin`
Place the [0, 0] index of the array in the upper left or lower left
corner of the Axes. The convention 'upper' is typically used for
matrices and images.
filternorm : bool, default: True
A parameter for the antigrain image resize filter
(see the antigrain documentation).
If filternorm is set, the filter normalizes integer values and corrects
the rounding errors. It doesn't do anything with the source floating
point values, it corrects only integers according to the rule of 1.0
which means that any sum of pixel weights must be equal to 1.0. So,
the filter function must produce a graph of the proper shape.
filterrad : float > 0, default: 4
The filter radius for filters that have a radius parameter, i.e. when
interpolation is one of: 'sinc', 'lanczos' or 'blackman'.
resample : bool, default: False
When True, use a full resampling method. When False, only resample when
the output image is larger than the input image.
**kwargs : `~matplotlib.artist.Artist` properties
"""
def __init__(self, bbox,
*,
cmap=None,
norm=None,
colorizer=None,
interpolation=None,
origin=None,
filternorm=True,
filterrad=4.0,
resample=False,
**kwargs
):
super().__init__(
None,
cmap=cmap,
norm=norm,
colorizer=colorizer,
interpolation=interpolation,
origin=origin,
filternorm=filternorm,
filterrad=filterrad,
resample=resample,
**kwargs
)
self.bbox = bbox
def get_window_extent(self, renderer=None):
if isinstance(self.bbox, BboxBase):
return self.bbox
elif callable(self.bbox):
if renderer is None:
renderer = self.get_figure()._get_renderer()
return self.bbox(renderer)
else:
raise ValueError("Unknown type of bbox")
def contains(self, mouseevent):
"""Test whether the mouse event occurred within the image."""
if self._different_canvas(mouseevent) or not self.get_visible():
return False, {}
x, y = mouseevent.x, mouseevent.y
inside = self.get_window_extent().contains(x, y)
return inside, {}
def make_image(self, renderer, magnification=1.0, unsampled=False):
# docstring inherited
width, height = renderer.get_canvas_width_height()
bbox_in = self.get_window_extent(renderer).frozen()
bbox_in._points /= [width, height]
bbox_out = self.get_window_extent(renderer)
clip = Bbox([[0, 0], [width, height]])
self._transform = BboxTransformTo(clip)
return self._make_image(
self._A,
bbox_in, bbox_out, clip, magnification, unsampled=unsampled)
def imread(fname, format=None):
"""
Read an image from a file into an array.
.. note::
This function exists for historical reasons. It is recommended to
use `PIL.Image.open` instead for loading images.
Parameters
----------
fname : str or file-like
The image file to read: a filename, a URL or a file-like object opened
in read-binary mode.
Passing a URL is deprecated. Please open the URL
for reading and pass the result to Pillow, e.g. with
``np.array(PIL.Image.open(urllib.request.urlopen(url)))``.
format : str, optional
The image file format assumed for reading the data. The image is
loaded as a PNG file if *format* is set to "png", if *fname* is a path
or opened file with a ".png" extension, or if it is a URL. In all
other cases, *format* is ignored and the format is auto-detected by
`PIL.Image.open`.
Returns
-------
`numpy.array`
The image data. The returned array has shape
- (M, N) for grayscale images.
- (M, N, 3) for RGB images.
- (M, N, 4) for RGBA images.
PNG images are returned as float arrays (0-1). All other formats are
returned as int arrays, with a bit depth determined by the file's
contents.
"""
# hide imports to speed initial import on systems with slow linkers
from urllib import parse
if format is None:
if isinstance(fname, str):
parsed = parse.urlparse(fname)
# If the string is a URL (Windows paths appear as if they have a
# length-1 scheme), assume png.
if len(parsed.scheme) > 1:
ext = 'png'
else:
ext = Path(fname).suffix.lower()[1:]
elif hasattr(fname, 'geturl'): # Returned by urlopen().
# We could try to parse the url's path and use the extension, but
# returning png is consistent with the block above. Note that this
# if clause has to come before checking for fname.name as
# urlopen("file:///...") also has a name attribute (with the fixed
# value "<urllib response>").
ext = 'png'
elif hasattr(fname, 'name'):
ext = Path(fname.name).suffix.lower()[1:]
else:
ext = 'png'
else:
ext = format
img_open = (
PIL.PngImagePlugin.PngImageFile if ext == 'png' else PIL.Image.open)
if isinstance(fname, str) and len(parse.urlparse(fname).scheme) > 1:
# Pillow doesn't handle URLs directly.
raise ValueError(
"Please open the URL for reading and pass the "
"result to Pillow, e.g. with "
"``np.array(PIL.Image.open(urllib.request.urlopen(url)))``."
)
with img_open(fname) as image:
return (_pil_png_to_float_array(image)
if isinstance(image, PIL.PngImagePlugin.PngImageFile) else
pil_to_array(image))
def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
origin=None, dpi=100, *, metadata=None, pil_kwargs=None):
"""
Colormap and save an array as an image file.
RGB(A) images are passed through. Single channel images will be
colormapped according to *cmap* and *norm*.
.. note::
If you want to save a single channel image as gray scale please use an
image I/O library (such as pillow, tifffile, or imageio) directly.
Parameters
----------
fname : str or path-like or file-like
A path or a file-like object to store the image in.
If *format* is not set, then the output format is inferred from the
extension of *fname*, if any, and from :rc:`savefig.format` otherwise.
If *format* is set, it determines the output format.
arr : array-like
The image data. Accepts NumPy arrays or sequences
(e.g., lists or tuples). The shape can be one of
MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA).
vmin, vmax : float, optional
*vmin* and *vmax* set the color scaling for the image by fixing the
values that map to the colormap color limits. If either *vmin*
or *vmax* is None, that limit is determined from the *arr*
min/max value.
cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
A Colormap instance or registered colormap name. The colormap
maps scalar data to colors. It is ignored for RGB(A) data.
format : str, optional
The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this
is unset is documented under *fname*.
origin : {'upper', 'lower'}, default: :rc:`image.origin`
Indicates whether the ``(0, 0)`` index of the array is in the upper
left or lower left corner of the Axes.
dpi : float
The DPI to store in the metadata of the file. This does not affect the
resolution of the output image. Depending on file format, this may be
rounded to the nearest integer.
metadata : dict, optional
Metadata in the image file. The supported keys depend on the output
format, see the documentation of the respective backends for more
information.
Currently only supported for "png", "pdf", "ps", "eps", and "svg".
pil_kwargs : dict, optional
Keyword arguments passed to `PIL.Image.Image.save`. If the 'pnginfo'
key is present, it completely overrides *metadata*, including the
default 'Software' key.
"""
from matplotlib.figure import Figure
# Normalizing input (e.g., list or tuples) to NumPy array if needed
arr = np.asanyarray(arr)
if isinstance(fname, os.PathLike):
fname = os.fspath(fname)
if format is None:
format = (Path(fname).suffix[1:] if isinstance(fname, str)
else mpl.rcParams["savefig.format"]).lower()
if format in ["pdf", "ps", "eps", "svg"]:
# Vector formats that are not handled by PIL.
if pil_kwargs is not None:
raise ValueError(
f"Cannot use 'pil_kwargs' when saving to {format}")
fig = Figure(dpi=dpi, frameon=False)
fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin,
resize=True)
fig.savefig(fname, dpi=dpi, format=format, transparent=True,
metadata=metadata)
else:
# Don't bother creating an image; this avoids rounding errors on the
# size when dividing and then multiplying by dpi.
origin = mpl._val_or_rc(origin, "image.origin")
_api.check_in_list(('upper', 'lower'), origin=origin)
if origin == "lower":
arr = arr[::-1]
if (isinstance(arr, memoryview) and arr.format == "B"
and arr.ndim == 3 and arr.shape[-1] == 4):
# Such an ``arr`` would also be handled fine by sm.to_rgba below
# (after casting with asarray), but it is useful to special-case it
# because that's what backend_agg passes, and can be in fact used
# as is, saving a few operations.
rgba = arr
else:
sm = mcolorizer.Colorizer(cmap=cmap)
sm.set_clim(vmin, vmax)
rgba = sm.to_rgba(arr, bytes=True)
if pil_kwargs is None:
pil_kwargs = {}
else:
# we modify this below, so make a copy (don't modify caller's dict)
pil_kwargs = pil_kwargs.copy()
pil_shape = (rgba.shape[1], rgba.shape[0])
rgba = np.require(rgba, requirements='C')
image = PIL.Image.frombuffer(
"RGBA", pil_shape, rgba, "raw", "RGBA", 0, 1)
if format == "png":
# Only use the metadata kwarg if pnginfo is not set, because the
# semantics of duplicate keys in pnginfo is unclear.
if "pnginfo" in pil_kwargs:
if metadata:
_api.warn_external("'metadata' is overridden by the "
"'pnginfo' entry in 'pil_kwargs'.")
else:
metadata = {
"Software": (f"Matplotlib version{mpl.__version__}, "
f"https://matplotlib.org/"),
**(metadata if metadata is not None else {}),
}
pil_kwargs["pnginfo"] = pnginfo = PIL.PngImagePlugin.PngInfo()
for k, v in metadata.items():
if v is not None:
pnginfo.add_text(k, v)
elif metadata is not None:
raise ValueError(f"metadata not supported for format {format!r}")
if format in ["jpg", "jpeg"]:
format = "jpeg" # Pillow doesn't recognize "jpg".
facecolor = mpl.rcParams["savefig.facecolor"]
if cbook._str_equal(facecolor, "auto"):
facecolor = mpl.rcParams["figure.facecolor"]
color = tuple(int(x * 255) for x in mcolors.to_rgb(facecolor))
background = PIL.Image.new("RGB", pil_shape, color)
background.paste(image, image)
image = background
pil_kwargs.setdefault("format", format)
pil_kwargs.setdefault("dpi", (dpi, dpi))
image.save(fname, **pil_kwargs)
def pil_to_array(pilImage):
"""
Load a `PIL image`_ and return it as a numpy int array.
.. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html
Returns
-------
numpy.array
The array shape depends on the image type:
- (M, N) for grayscale images.
- (M, N, 3) for RGB images.
- (M, N, 4) for RGBA images.
"""
if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']:
# return MxNx4 RGBA, MxNx3 RBA, or MxN luminance array
return np.asarray(pilImage)
elif pilImage.mode.startswith('I;16'):
# return MxN luminance array of uint16
raw = pilImage.tobytes('raw', pilImage.mode)
if pilImage.mode.endswith('B'):
x = np.frombuffer(raw, '>u2')
else:
x = np.frombuffer(raw, '<u2')
return x.reshape(pilImage.size[::-1]).astype('=u2')
else: # try to convert to an rgba image
try:
pilImage = pilImage.convert('RGBA')
except ValueError as err:
raise RuntimeError('Unknown image mode') from err
return np.asarray(pilImage) # return MxNx4 RGBA array
def _pil_png_to_float_array(pil_png):
"""Convert a PIL `PNGImageFile` to a 0-1 float array."""
# Unlike pil_to_array this converts to 0-1 float32s for backcompat with the
# old libpng-based loader.
# The supported rawmodes are from PIL.PngImagePlugin._MODES. When
# mode == "RGB(A)", the 16-bit raw data has already been coarsened to 8-bit
# by Pillow.
mode = pil_png.mode
rawmode = pil_png.png.im_rawmode
if rawmode == "1": # Grayscale.
return np.asarray(pil_png, np.float32)
if rawmode == "L;2": # Grayscale.
return np.divide(pil_png, 2**2 - 1, dtype=np.float32)
if rawmode == "L;4": # Grayscale.
return np.divide(pil_png, 2**4 - 1, dtype=np.float32)
if rawmode == "L": # Grayscale.
return np.divide(pil_png, 2**8 - 1, dtype=np.float32)
if rawmode == "I;16B": # Grayscale.
return np.divide(pil_png, 2**16 - 1, dtype=np.float32)
if mode == "RGB": # RGB.
return np.divide(pil_png, 2**8 - 1, dtype=np.float32)
if mode == "P": # Palette.
return np.divide(pil_png.convert("RGBA"), 2**8 - 1, dtype=np.float32)
if mode == "LA": # Grayscale + alpha.
return np.divide(pil_png.convert("RGBA"), 2**8 - 1, dtype=np.float32)
if mode == "RGBA": # RGBA.
return np.divide(pil_png, 2**8 - 1, dtype=np.float32)
raise ValueError(f"Unknown PIL rawmode: {rawmode}")
def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear',
preview=False):
"""
Make a thumbnail of image in *infile* with output filename *thumbfile*.
See :doc:`/gallery/misc/image_thumbnail_sgskip`.
Parameters
----------
infile : str or file-like
The image file. Matplotlib relies on Pillow_ for image reading, and
thus supports a wide range of file formats, including PNG, JPG, TIFF
and others.
.. _Pillow: https://python-pillow.github.io
thumbfile : str or file-like
The thumbnail filename.
scale : float, default: 0.1
The scale factor for the thumbnail.
interpolation : str, default: 'bilinear'
The interpolation scheme used in the resampling. See the
*interpolation* parameter of `~.Axes.imshow` for possible values.
preview : bool, default: False
If True, the default backend (presumably a user interface
backend) will be used which will cause a figure to be raised if
`~matplotlib.pyplot.show` is called. If it is False, the figure is
created using `.FigureCanvasBase` and the drawing backend is selected
as `.Figure.savefig` would normally do.
Returns
-------
`.Figure`
The figure instance containing the thumbnail.
"""
im = imread(infile)
rows, cols, depth = im.shape
# This doesn't really matter (it cancels in the end) but the API needs it.
dpi = 100
height = rows / dpi * scale
width = cols / dpi * scale
if preview:
# Let the UI backend do everything.
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(width, height), dpi=dpi)
else:
from matplotlib.figure import Figure
fig = Figure(figsize=(width, height), dpi=dpi)
FigureCanvasBase(fig)
ax = fig.add_axes((0, 0, 1, 1), aspect='auto',
frameon=False, xticks=[], yticks=[])
ax.imshow(im, aspect='auto', resample=True, interpolation=interpolation)
fig.savefig(thumbfile, dpi=dpi)
return fig
| BboxImage |
python | tensorflow__tensorflow | tensorflow/python/training/session_run_hook.py | {
"start": 3593,
"end": 6932
} | class ____:
"""Hook to extend calls to MonitoredSession.run()."""
def begin(self):
"""Called once before using the session.
When called, the default graph is the one that will be launched in the
session. The hook can modify the graph by adding new operations to it.
After the `begin()` call the graph will be finalized and the other callbacks
can not modify the graph anymore. Second call of `begin()` on the same
graph, should not change the graph.
"""
pass
def after_create_session(self, session, coord): # pylint: disable=unused-argument
"""Called when new TensorFlow session is created.
This is called to signal the hooks that a new session has been created. This
has two essential differences with the situation in which `begin` is called:
* When this is called, the graph is finalized and ops can no longer be added
to the graph.
* This method will also be called as a result of recovering a wrapped
session, not only at the beginning of the overall session.
Args:
session: A TensorFlow Session that has been created.
coord: A Coordinator object which keeps track of all threads.
"""
pass
def before_run(self, run_context): # pylint: disable=unused-argument
"""Called before each call to run().
You can return from this call a `SessionRunArgs` object indicating ops or
tensors to add to the upcoming `run()` call. These ops/tensors will be run
together with the ops/tensors originally passed to the original run() call.
The run args you return can also contain feeds to be added to the run()
call.
The `run_context` argument is a `SessionRunContext` that provides
information about the upcoming `run()` call: the originally requested
op/tensors, the TensorFlow Session.
At this point graph is finalized and you can not add ops.
Args:
run_context: A `SessionRunContext` object.
Returns:
None or a `SessionRunArgs` object.
"""
return None
def after_run(self,
run_context, # pylint: disable=unused-argument
run_values): # pylint: disable=unused-argument
"""Called after each call to run().
The `run_values` argument contains results of requested ops/tensors by
`before_run()`.
The `run_context` argument is the same one send to `before_run` call.
`run_context.request_stop()` can be called to stop the iteration.
If `session.run()` raises any exceptions then `after_run()` is not called.
Args:
run_context: A `SessionRunContext` object.
run_values: A SessionRunValues object.
"""
pass
def end(self, session): # pylint: disable=unused-argument
"""Called at the end of session.
The `session` argument can be used in case the hook wants to run final ops,
such as saving a last checkpoint.
If `session.run()` raises exception other than OutOfRangeError or
StopIteration then `end()` is not called.
Note the difference between `end()` and `after_run()` behavior when
`session.run()` raises OutOfRangeError or StopIteration. In that case
`end()` is called but `after_run()` is not called.
Args:
session: A TensorFlow Session that will be soon closed.
"""
pass
@tf_export(v1=["train.SessionRunArgs"])
| SessionRunHook |
python | huggingface__transformers | src/transformers/models/bridgetower/modeling_bridgetower.py | {
"start": 32754,
"end": 35182
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList(
[BridgeTowerTextLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)]
)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
encoder_hidden_states: Optional[torch.FloatTensor] = None,
encoder_attention_mask: Optional[torch.FloatTensor] = None,
past_key_values: Optional[Cache] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = False,
output_hidden_states: Optional[bool] = False,
cache_position: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
all_hidden_states = () if output_hidden_states else None
all_self_attentions = () if output_attentions else None
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
for i, layer_module in enumerate(self.layer):
layer_outputs = layer_module(
hidden_states,
attention_mask,
encoder_hidden_states, # as a positional argument for gradient checkpointing
encoder_attention_mask=encoder_attention_mask,
past_key_values=past_key_values,
cache_position=cache_position,
**kwargs,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_self_attentions = all_self_attentions + (layer_outputs[1],)
if self.config.add_cross_attention:
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
return BaseModelOutputWithPastAndCrossAttentions(
last_hidden_state=hidden_states,
past_key_values=past_key_values if use_cache else None,
hidden_states=all_hidden_states,
attentions=all_self_attentions,
cross_attentions=all_cross_attentions,
)
# Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->BridgeTowerText
| BridgeTowerTextEncoder |
python | getsentry__sentry | tests/sentry/utils/test_sdk.py | {
"start": 10593,
"end": 15740
} | class ____(TestCase):
def test_passes_along_exception(self, mock_sdk_capture_exception: MagicMock) -> None:
err = Exception()
with patch("sentry.utils.sdk.check_current_scope_transaction", return_value=None):
capture_exception_with_scope_check(err)
assert mock_sdk_capture_exception.call_args.args[0] == err
@patch("sentry.utils.sdk.check_current_scope_transaction")
def test_doesnt_check_transaction_if_no_request(
self,
mock_check_transaction: MagicMock,
mock_sdk_capture_exception: MagicMock,
):
capture_exception_with_scope_check(Exception())
assert mock_check_transaction.call_count == 0
def test_no_transaction_mismatch(self, mock_sdk_capture_exception: MagicMock) -> None:
with patch("sentry.utils.sdk.check_current_scope_transaction", return_value=None):
capture_exception_with_scope_check(Exception(), request=Request(HttpRequest()))
passed_scope = mock_sdk_capture_exception.call_args.kwargs["scope"]
assert isinstance(passed_scope, Scope)
assert "scope_bleed.transaction" not in passed_scope._tags
assert "scope_bleed" not in passed_scope._contexts
def test_with_transaction_mismatch(self, mock_sdk_capture_exception: MagicMock) -> None:
scope_bleed_data = {
"scope_transaction": "/tricks/{trick_name}/",
"request_transaction": "/dogs/{name}/",
}
with patch(
"sentry.utils.sdk.check_current_scope_transaction", return_value=scope_bleed_data
):
capture_exception_with_scope_check(Exception(), request=Request(HttpRequest()))
passed_scope = mock_sdk_capture_exception.call_args.kwargs["scope"]
assert isinstance(passed_scope, Scope)
assert passed_scope._tags["scope_bleed.transaction"] is True
assert passed_scope._contexts["scope_bleed"] == scope_bleed_data
def test_no_scope_data_passed(self, mock_sdk_capture_exception: MagicMock) -> None:
capture_exception_with_scope_check(Exception())
passed_scope = mock_sdk_capture_exception.call_args.kwargs["scope"]
empty_scope = Scope(client=passed_scope.client)
for entry in empty_scope.__slots__:
# _propagation_context is generated on __init__ for tracing without performance
# so is different every time. Same with client in SDK >=2.0.
if entry in ("_propagation_context", "client"):
continue
# No new scope data should be passed
assert getattr(passed_scope, entry) == getattr(empty_scope, entry)
def test_passes_along_incoming_scope_object(
self, mock_sdk_capture_exception: MagicMock
) -> None:
incoming_scope_arg = Scope()
capture_exception_with_scope_check(Exception(), scope=incoming_scope_arg)
passed_scope = mock_sdk_capture_exception.call_args.kwargs["scope"]
assert passed_scope == incoming_scope_arg
def test_merges_incoming_scope_obj_and_args(
self, mock_sdk_capture_exception: MagicMock
) -> None:
incoming_scope_arg = Scope()
incoming_scope_arg.set_level("info")
capture_exception_with_scope_check(
Exception(), scope=incoming_scope_arg, fingerprint="pawprint"
)
passed_scope = mock_sdk_capture_exception.call_args.kwargs["scope"]
assert passed_scope._level == "info"
assert passed_scope._fingerprint == "pawprint"
def test_passes_along_incoming_scope_args(self, mock_sdk_capture_exception: MagicMock) -> None:
capture_exception_with_scope_check(Exception(), fingerprint="pawprint")
passed_scope = mock_sdk_capture_exception.call_args.kwargs["scope"]
assert passed_scope._fingerprint == "pawprint"
def test_doesnt_overwrite_incoming_scope_bleed_context(
self, mock_sdk_capture_exception: MagicMock
):
existing_scope_bleed_data = {
"previous_org.slug_tag": "good_dogs",
"new_org.slug_tag": "squirrel_chasers",
}
transaction_scope_bleed_data = {
"scope_transaction": "/tricks/{trick_name}/",
"request_transaction": "/dogs/{name}/",
}
incoming_scope_arg = Scope()
incoming_scope_arg.set_context("scope_bleed", existing_scope_bleed_data)
with patch(
"sentry.utils.sdk.check_current_scope_transaction",
return_value=transaction_scope_bleed_data,
):
capture_exception_with_scope_check(
Exception(), request=Request(HttpRequest()), scope=incoming_scope_arg
)
passed_scope = mock_sdk_capture_exception.call_args.kwargs["scope"]
# both old and new data should be included
assert "previous_org.slug_tag" in passed_scope._contexts["scope_bleed"]
assert "new_org.slug_tag" in passed_scope._contexts["scope_bleed"]
assert "scope_transaction" in passed_scope._contexts["scope_bleed"]
assert "request_transaction" in passed_scope._contexts["scope_bleed"]
| CaptureExceptionWithScopeCheckTest |
python | apache__airflow | providers/databricks/src/airflow/providers/databricks/operators/databricks_repos.py | {
"start": 6775,
"end": 10380
} | class ____(BaseOperator):
"""
Updates specified repository to a given branch or tag using the PATCH api/2.0/repos API endpoint.
See: https://docs.databricks.com/dev-tools/api/latest/repos.html#operation/update-repo
:param branch: optional name of branch to update to. Should be specified if ``tag`` is omitted
:param tag: optional name of tag to update to. Should be specified if ``branch`` is omitted
:param repo_id: optional ID of existing repository. Should be specified if ``repo_path`` is omitted
:param repo_path: optional path of existing repository. Should be specified if ``repo_id`` is omitted
:param databricks_conn_id: Reference to the :ref:`Databricks connection <howto/connection:databricks>`.
By default and in the common case this will be ``databricks_default``. To use
token based authentication, provide the key ``token`` in the extra field for the
connection and create the key ``host`` and leave the ``host`` field empty. (templated)
:param databricks_retry_limit: Amount of times retry if the Databricks backend is
unreachable. Its value must be greater than or equal to 1.
:param databricks_retry_delay: Number of seconds to wait between retries (it
might be a floating point number).
"""
# Used in airflow.models.BaseOperator
template_fields: Sequence[str] = ("repo_path", "tag", "branch", "databricks_conn_id")
def __init__(
self,
*,
branch: str | None = None,
tag: str | None = None,
repo_id: str | None = None,
repo_path: str | None = None,
databricks_conn_id: str = "databricks_default",
databricks_retry_limit: int = 3,
databricks_retry_delay: int = 1,
**kwargs,
) -> None:
"""Create a new ``DatabricksReposUpdateOperator``."""
super().__init__(**kwargs)
self.databricks_conn_id = databricks_conn_id
self.databricks_retry_limit = databricks_retry_limit
self.databricks_retry_delay = databricks_retry_delay
if branch is not None and tag is not None:
raise AirflowException("Only one of branch or tag should be provided, but not both")
if branch is None and tag is None:
raise AirflowException("One of branch or tag should be provided")
if repo_id is not None and repo_path is not None:
raise AirflowException("Only one of repo_id or repo_path should be provided, but not both")
if repo_id is None and repo_path is None:
raise AirflowException("One of repo_id or repo_path should be provided")
self.repo_path = repo_path
self.repo_id = repo_id
self.branch = branch
self.tag = tag
@cached_property
def _hook(self) -> DatabricksHook:
return DatabricksHook(
self.databricks_conn_id,
retry_limit=self.databricks_retry_limit,
retry_delay=self.databricks_retry_delay,
caller="DatabricksReposUpdateOperator",
)
def execute(self, context: Context):
if self.repo_path is not None:
self.repo_id = self._hook.get_repo_by_path(self.repo_path)
if self.repo_id is None:
raise AirflowException(f"Can't find Repo ID for path '{self.repo_path}'")
if self.branch is not None:
payload = {"branch": str(self.branch)}
else:
payload = {"tag": str(self.tag)}
result = self._hook.update_repo(str(self.repo_id), payload)
return result["head_commit_id"]
| DatabricksReposUpdateOperator |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 187267,
"end": 189927
} | class ____(Operation):
def __init__(self, indices_or_sections, axis=0, *, name=None):
super().__init__(name=name)
if not isinstance(indices_or_sections, int):
indices_or_sections = tuple(indices_or_sections)
self.indices_or_sections = indices_or_sections
self.axis = axis
def call(self, x):
return backend.numpy.split(x, self.indices_or_sections, axis=self.axis)
def compute_output_spec(self, x):
x_shape = list(x.shape)
x_size_on_axis = x_shape[self.axis]
if isinstance(self.indices_or_sections, int):
if x_size_on_axis is None:
x_shape[self.axis] = None
return [
KerasTensor(x_shape, dtype=x.dtype)
for _ in range(self.indices_or_sections)
]
if np.mod(x_size_on_axis, self.indices_or_sections) != 0:
raise ValueError(
"`x` size on given `axis` must be dividible by "
"`indices_or_sections` when `indices_or_sections` is an "
f"int. But received {x_size_on_axis} and "
f"{self.indices_or_sections}."
)
size = x_size_on_axis // self.indices_or_sections
x_shape[self.axis] = size
return [
KerasTensor(x_shape, dtype=x.dtype)
for _ in range(self.indices_or_sections)
]
indices_or_sections = (0, *self.indices_or_sections, x_size_on_axis)
output_size = np.diff(indices_or_sections)
outputs = []
for i in range(len(output_size)):
output_shape = list(x_shape)
output_shape[self.axis] = int(output_size[i])
outputs.append(KerasTensor(output_shape, dtype=x.dtype))
return outputs
@keras_export(["keras.ops.split", "keras.ops.numpy.split"])
def split(x, indices_or_sections, axis=0):
"""Split a tensor into chunks.
Args:
x: Input tensor.
indices_or_sections: If an integer, N, the tensor will be split into N
equal sections along `axis`. If a 1-D array of sorted integers,
the entries indicate indices at which the tensor will be split
along `axis`.
axis: Axis along which to split. Defaults to `0`.
Note:
A split does not have to result in equal division when using
Torch backend.
Returns:
A list of tensors.
"""
if any_symbolic_tensors((x,)):
return Split(indices_or_sections, axis=axis).symbolic_call(x)
return backend.numpy.split(x, indices_or_sections, axis=axis)
| Split |
python | doocs__leetcode | solution/0500-0599/0520.Detect Capital/Solution.py | {
"start": 0,
"end": 192
} | class ____:
def detectCapitalUse(self, word: str) -> bool:
cnt = sum(c.isupper() for c in word)
return cnt == 0 or cnt == len(word) or (cnt == 1 and word[0].isupper())
| Solution |
python | sympy__sympy | sympy/functions/elementary/complexes.py | {
"start": 28340,
"end": 30025
} | class ____(DefinedFunction):
"""
Conjugate transpose or Hermite conjugation.
Examples
========
>>> from sympy import adjoint, MatrixSymbol
>>> A = MatrixSymbol('A', 10, 5)
>>> adjoint(A)
Adjoint(A)
Parameters
==========
arg : Matrix
Matrix or matrix expression to take the adjoint of.
Returns
=======
value : Matrix
Represents the conjugate transpose or Hermite
conjugation of arg.
"""
@classmethod
def eval(cls, arg):
obj = arg._eval_adjoint()
if obj is not None:
return obj
obj = arg._eval_transpose()
if obj is not None:
return conjugate(obj)
def _eval_adjoint(self):
return self.args[0]
def _eval_conjugate(self):
return transpose(self.args[0])
def _eval_transpose(self):
return conjugate(self.args[0])
def _latex(self, printer, exp=None, *args):
arg = printer._print(self.args[0])
tex = r'%s^{\dagger}' % arg
if exp:
tex = r'\left(%s\right)^{%s}' % (tex, exp)
return tex
def _pretty(self, printer, *args):
from sympy.printing.pretty.stringpict import prettyForm
pform = printer._print(self.args[0], *args)
if printer._use_unicode:
pform = pform**prettyForm('\N{DAGGER}')
else:
pform = pform**prettyForm('+')
return pform
###############################################################################
############### HANDLING OF POLAR NUMBERS #####################################
###############################################################################
| adjoint |
python | mwaskom__seaborn | seaborn/_statistics.py | {
"start": 1697,
"end": 7169
} | class ____:
"""Univariate and bivariate kernel density estimator."""
def __init__(
self, *,
bw_method=None,
bw_adjust=1,
gridsize=200,
cut=3,
clip=None,
cumulative=False,
):
"""Initialize the estimator with its parameters.
Parameters
----------
bw_method : string, scalar, or callable, optional
Method for determining the smoothing bandwidth to use; passed to
:class:`scipy.stats.gaussian_kde`.
bw_adjust : number, optional
Factor that multiplicatively scales the value chosen using
``bw_method``. Increasing will make the curve smoother. See Notes.
gridsize : int, optional
Number of points on each dimension of the evaluation grid.
cut : number, optional
Factor, multiplied by the smoothing bandwidth, that determines how
far the evaluation grid extends past the extreme datapoints. When
set to 0, truncate the curve at the data limits.
clip : pair of numbers or None, or a pair of such pairs
Do not evaluate the density outside of these limits.
cumulative : bool, optional
If True, estimate a cumulative distribution function. Requires scipy.
"""
if clip is None:
clip = None, None
self.bw_method = bw_method
self.bw_adjust = bw_adjust
self.gridsize = gridsize
self.cut = cut
self.clip = clip
self.cumulative = cumulative
if cumulative and _no_scipy:
raise RuntimeError("Cumulative KDE evaluation requires scipy")
self.support = None
def _define_support_grid(self, x, bw, cut, clip, gridsize):
"""Create the grid of evaluation points depending for vector x."""
clip_lo = -np.inf if clip[0] is None else clip[0]
clip_hi = +np.inf if clip[1] is None else clip[1]
gridmin = max(x.min() - bw * cut, clip_lo)
gridmax = min(x.max() + bw * cut, clip_hi)
return np.linspace(gridmin, gridmax, gridsize)
def _define_support_univariate(self, x, weights):
"""Create a 1D grid of evaluation points."""
kde = self._fit(x, weights)
bw = np.sqrt(kde.covariance.squeeze())
grid = self._define_support_grid(
x, bw, self.cut, self.clip, self.gridsize
)
return grid
def _define_support_bivariate(self, x1, x2, weights):
"""Create a 2D grid of evaluation points."""
clip = self.clip
if clip[0] is None or np.isscalar(clip[0]):
clip = (clip, clip)
kde = self._fit([x1, x2], weights)
bw = np.sqrt(np.diag(kde.covariance).squeeze())
grid1 = self._define_support_grid(
x1, bw[0], self.cut, clip[0], self.gridsize
)
grid2 = self._define_support_grid(
x2, bw[1], self.cut, clip[1], self.gridsize
)
return grid1, grid2
def define_support(self, x1, x2=None, weights=None, cache=True):
"""Create the evaluation grid for a given data set."""
if x2 is None:
support = self._define_support_univariate(x1, weights)
else:
support = self._define_support_bivariate(x1, x2, weights)
if cache:
self.support = support
return support
def _fit(self, fit_data, weights=None):
"""Fit the scipy kde while adding bw_adjust logic and version check."""
fit_kws = {"bw_method": self.bw_method}
if weights is not None:
fit_kws["weights"] = weights
kde = gaussian_kde(fit_data, **fit_kws)
kde.set_bandwidth(kde.factor * self.bw_adjust)
return kde
def _eval_univariate(self, x, weights=None):
"""Fit and evaluate a univariate on univariate data."""
support = self.support
if support is None:
support = self.define_support(x, cache=False)
kde = self._fit(x, weights)
if self.cumulative:
s_0 = support[0]
density = np.array([
kde.integrate_box_1d(s_0, s_i) for s_i in support
])
else:
density = kde(support)
return density, support
def _eval_bivariate(self, x1, x2, weights=None):
"""Fit and evaluate a univariate on bivariate data."""
support = self.support
if support is None:
support = self.define_support(x1, x2, cache=False)
kde = self._fit([x1, x2], weights)
if self.cumulative:
grid1, grid2 = support
density = np.zeros((grid1.size, grid2.size))
p0 = grid1.min(), grid2.min()
for i, xi in enumerate(grid1):
for j, xj in enumerate(grid2):
density[i, j] = kde.integrate_box(p0, (xi, xj))
else:
xx1, xx2 = np.meshgrid(*support)
density = kde([xx1.ravel(), xx2.ravel()]).reshape(xx1.shape)
return density, support
def __call__(self, x1, x2=None, weights=None):
"""Fit and evaluate on univariate or bivariate data."""
if x2 is None:
return self._eval_univariate(x1, weights)
else:
return self._eval_bivariate(x1, x2, weights)
# Note: we no longer use this for univariate histograms in histplot,
# preferring _stats.Hist. We'll deprecate this once we have a bivariate Stat class.
| KDE |
python | pytorch__pytorch | test/quantization/pt2e/test_graph_utils.py | {
"start": 374,
"end": 4365
} | class ____(TestCase):
@unittest.skipIf(IS_WINDOWS, "torch.compile is not supported on Windows")
def test_conv_bn_conv_relu(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv1 = torch.nn.Conv2d(3, 3, 3)
self.bn1 = torch.nn.BatchNorm2d(3)
self.conv2 = torch.nn.Conv2d(3, 3, 3)
self.relu2 = torch.nn.ReLU()
def forward(self, x):
bn_out = self.bn1(self.conv1(x))
relu_out = torch.nn.functional.relu(bn_out)
return self.relu2(self.conv2(relu_out))
m = M().eval()
example_inputs = (torch.randn(1, 3, 5, 5),)
# program capture
m, guards = torchdynamo.export( # noqa: F841
m,
*copy.deepcopy(example_inputs),
aten_graph=True,
)
fused_partitions = find_sequential_partitions(
m, [torch.nn.Conv2d, torch.nn.BatchNorm2d]
)
self.assertEqual(len(fused_partitions), 1)
fused_partitions = find_sequential_partitions(
m, [torch.nn.Conv2d, torch.nn.BatchNorm2d, torch.nn.ReLU]
)
self.assertEqual(len(fused_partitions), 1)
def x():
find_sequential_partitions(
m,
[
torch.nn.Conv2d,
torch.nn.BatchNorm2d,
torch.nn.ReLU,
torch.nn.functional.conv2d,
],
)
self.assertRaises(ValueError, x)
@unittest.skipIf(IS_WINDOWS, "torch.compile is not supported on Windows")
def test_conv_bn_relu(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.bn1 = torch.nn.BatchNorm2d(3)
self.conv2 = torch.nn.Conv2d(3, 3, 3)
self.relu2 = torch.nn.ReLU()
def forward(self, x):
bn_out = self.bn1(x)
return self.relu2(self.conv2(bn_out))
m = M().eval()
example_inputs = (torch.randn(1, 3, 5, 5),)
# program capture
m, guards = torchdynamo.export( # noqa: F841
m,
*copy.deepcopy(example_inputs),
aten_graph=True,
)
fused_partitions = find_sequential_partitions(
m, [torch.nn.Conv2d, torch.nn.BatchNorm2d]
)
self.assertEqual(len(fused_partitions), 0)
fused_partitions = find_sequential_partitions(
m, [torch.nn.BatchNorm2d, torch.nn.Conv2d]
)
self.assertEqual(len(fused_partitions), 1)
fused_partitions = find_sequential_partitions(
m, [torch.nn.BatchNorm2d, torch.nn.ReLU]
)
self.assertEqual(len(fused_partitions), 0)
@unittest.skipIf(IS_WINDOWS, "torch.compile is not supported on Windows")
def test_customized_equivalet_types_dict(self):
class M(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.conv = torch.nn.Conv2d(3, 3, 3)
def forward(self, x):
return torch.nn.functional.relu6(self.conv(x))
m = M().eval()
example_inputs = (torch.randn(1, 3, 5, 5),)
# program capture
m, guards = torchdynamo.export( # noqa: F841
m,
*copy.deepcopy(example_inputs),
aten_graph=True,
)
customized_equivalent_types = get_equivalent_types()
customized_equivalent_types.append({torch.nn.ReLU6, torch.nn.functional.relu6})
update_equivalent_types_dict(customized_equivalent_types)
fused_partitions = find_sequential_partitions(
m,
[torch.nn.Conv2d, torch.nn.ReLU6],
)
self.assertEqual(len(fused_partitions), 1)
if __name__ == "__main__":
raise_on_run_directly("test/test_quantization.py")
| TestGraphUtils |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 109431,
"end": 109838
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(
sgqlc.types.non_null(IpAllowListEntryOrderField), graphql_name="field"
)
direction = sgqlc.types.Field(
sgqlc.types.non_null(OrderDirection), graphql_name="direction"
)
| IpAllowListEntryOrder |
python | getsentry__sentry | tests/sentry/api/serializers/test_event.py | {
"start": 14775,
"end": 17532
} | class ____(TestCase):
@mock.patch(
"sentry.sdk_updates.SdkIndexState",
return_value=SdkIndexState(sdk_versions={"example.sdk": "2.0.0"}),
)
def test_update_on_major(self, mock_index_state: mock.MagicMock) -> None:
min_ago = before_now(minutes=1).isoformat()
event = self.store_event(
data={
"event_id": "a" * 32,
"message": "oh no",
"timestamp": min_ago,
"fingerprint": ["group-1"],
"sdk": {"name": "example.sdk", "version": "1.0.0"},
},
project_id=self.project.id,
assert_no_errors=False,
)
result = serialize(event, None, IssueEventSerializer())
assert result["sdkUpdates"] == [
{
"enables": [],
"newSdkVersion": "2.0.0",
"sdkName": "example.sdk",
"sdkUrl": None,
"type": "updateSdk",
}
]
@mock.patch(
"sentry.sdk_updates.SdkIndexState",
return_value=SdkIndexState(sdk_versions={"example.sdk": "1.1.0"}),
)
def test_update_on_minor(self, mock_index_state: mock.MagicMock) -> None:
min_ago = before_now(minutes=1).isoformat()
event = self.store_event(
data={
"event_id": "a" * 32,
"message": "oh no",
"timestamp": min_ago,
"fingerprint": ["group-1"],
"sdk": {"name": "example.sdk", "version": "1.0.0"},
},
project_id=self.project.id,
assert_no_errors=False,
)
result = serialize(event, None, IssueEventSerializer())
assert result["sdkUpdates"] == [
{
"enables": [],
"newSdkVersion": "1.1.0",
"sdkName": "example.sdk",
"sdkUrl": None,
"type": "updateSdk",
}
]
@mock.patch(
"sentry.sdk_updates.SdkIndexState",
return_value=SdkIndexState(sdk_versions={"example.sdk": "1.0.1"}),
)
def test_ignores_patch(self, mock_index_state: mock.MagicMock) -> None:
min_ago = before_now(minutes=1).isoformat()
event = self.store_event(
data={
"event_id": "a" * 32,
"message": "oh no",
"timestamp": min_ago,
"fingerprint": ["group-1"],
"sdk": {"name": "example.sdk", "version": "1.0.0"},
},
project_id=self.project.id,
assert_no_errors=False,
)
result = serialize(event, None, IssueEventSerializer())
assert result["sdkUpdates"] == []
| IssueEventSerializerTest |
python | chroma-core__chroma | chromadb/execution/expression/operator.py | {
"start": 36198,
"end": 36390
} | class ____(Rank):
"""Summation of multiple ranks"""
ranks: List[Rank]
def to_dict(self) -> Dict[str, Any]:
return {"$sum": [r.to_dict() for r in self.ranks]}
@dataclass
| Sum |
python | gevent__gevent | src/gevent/exceptions.py | {
"start": 3360,
"end": 3823
} | class ____(GreenletExit):
"""
Internal exception, raised when we're trying to destroy the
hub and we want the loop to stop running callbacks now.
This must not be subclassed; the type is tested by identity.
Clients outside of gevent must not raise this exception.
.. versionadded:: 20.12.0
"""
def __init__(self, destroy_loop):
GreenletExit.__init__(self, destroy_loop)
self.destroy_loop = destroy_loop
| HubDestroyed |
python | zarr-developers__zarr-python | tests/test_dtype/test_npy/test_int.py | {
"start": 2013,
"end": 3215
} | class ____(BaseTestZDType):
test_cls = Int32
scalar_type = np.int32
# The behavior of some tests associated with this class variable are
# order-dependent -- np.dtype('i') correctly fails certain tests only if it's not
# in the last position of the tuple. I have no idea how this is possible!
valid_dtype = (np.dtype("i"), np.dtype(">i4"), np.dtype("<i4"))
invalid_dtype = (
np.dtype(np.int8),
np.dtype(np.uint16),
np.dtype(np.float64),
)
valid_json_v2 = (
{"name": ">i4", "object_codec_id": None},
{"name": "<i4", "object_codec_id": None},
)
valid_json_v3 = ("int32",)
invalid_json_v2 = (
"|i4",
"int32",
"|f8",
)
invalid_json_v3 = (
"|i4",
"|f8",
{"name": "int32", "configuration": {"endianness": "little"}},
)
scalar_v2_params = ((Int32(), 1), (Int32(), -1), (Int32(), 1.0))
scalar_v3_params = ((Int32(), 1), (Int32(), -1))
cast_value_params = (
(Int32(), 1, np.int32(1)),
(Int32(), -1, np.int32(-1)),
)
invalid_scalar_params = ((Int32(), {"set!"}), (Int32(), ("tuple",)))
item_size_params = (Int32(),)
| TestInt32 |
python | pdm-project__pdm | src/pdm/cli/commands/publish/__init__.py | {
"start": 581,
"end": 8265
} | class ____(BaseCommand):
"""Build and publish the project to PyPI"""
arguments = (verbose_option, project_option, skip_option)
def add_arguments(self, parser: argparse.ArgumentParser) -> None:
parser.add_argument(
"-r",
"--repository",
help="The repository name or url to publish the package to [env var: PDM_PUBLISH_REPO]",
)
parser.add_argument(
"-u",
"--username",
help="The username to access the repository [env var: PDM_PUBLISH_USERNAME]",
)
parser.add_argument(
"-P",
"--password",
help="The password to access the repository [env var: PDM_PUBLISH_PASSWORD]",
)
parser.add_argument(
"-S",
"--sign",
action="store_true",
help="Upload the package with PGP signature",
)
parser.add_argument(
"-i",
"--identity",
help="GPG identity used to sign files.",
)
parser.add_argument(
"-c",
"--comment",
help="The comment to include with the distribution file.",
)
parser.add_argument(
"--no-build",
action="store_false",
dest="build",
help="Don't build the package before publishing",
)
parser.add_argument(
"-d",
"--dest",
help="The directory to upload the package from",
default="dist",
)
parser.add_argument(
"--skip-existing",
action="store_true",
help="Skip uploading files that already exist. This may not work with some repository implementations.",
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"--no-very-ssl", action="store_false", dest="verify_ssl", help="Disable SSL verification", default=None
)
group.add_argument(
"--ca-certs",
dest="ca_certs",
help="The path to a PEM-encoded Certificate Authority bundle to use"
" for publish server validation [env var: PDM_PUBLISH_CA_CERTS]",
)
@staticmethod
def _make_package(filename: str, signatures: dict[str, str], options: argparse.Namespace) -> PackageFile:
p = PackageFile.from_filename(filename, options.comment)
if p.base_filename in signatures:
p.add_gpg_signature(signatures[p.base_filename], p.base_filename + ".asc")
elif options.sign:
p.sign(options.identity)
return p
@staticmethod
def _skip_upload(response: Response) -> bool:
status = response.status_code
reason = response.reason_phrase.lower()
text = response.text.lower()
# Borrowed from https://github.com/pypa/twine/blob/main/twine/commands/upload.py#L149
return (
# pypiserver (https://pypi.org/project/pypiserver)
status == 409
# PyPI / TestPyPI / GCP Artifact Registry
or (status == 400 and any("already exist" in x for x in [reason, text]))
# Nexus Repository OSS (https://www.sonatype.com/nexus-repository-oss)
or (
status == 400
and any(token in x for x in [reason, text] for token in ["updating asset", "cannot be updated"])
)
# Artifactory (https://jfrog.com/artifactory/)
or (status == 403 and "overwrite artifact" in text)
# Gitlab Enterprise Edition (https://about.gitlab.com)
or (status == 400 and "already been taken" in text)
)
@staticmethod
def _check_response(response: Response) -> None:
import httpx
message = ""
if response.status_code == 410 and "pypi.python.org" in str(response.url):
message = (
"Uploading to these sites is deprecated. "
"Try using https://upload.pypi.org/legacy/ "
"(or https://test.pypi.org/legacy/) instead."
)
elif response.status_code == 405 and "pypi.org" in str(response.url):
message = "It appears you're trying to upload to pypi.org but have an invalid URL."
else:
try:
response.raise_for_status()
except httpx.HTTPStatusError as err:
message = str(err)
if response.text:
logger.debug(response.text)
if message:
raise PublishError(message)
@staticmethod
def get_repository(project: Project, options: argparse.Namespace) -> Repository:
from pdm.cli.commands.publish.repository import Repository
repository = options.repository or os.getenv("PDM_PUBLISH_REPO", "pypi")
username = options.username or os.getenv("PDM_PUBLISH_USERNAME")
password = options.password or os.getenv("PDM_PUBLISH_PASSWORD")
ca_certs = options.ca_certs or os.getenv("PDM_PUBLISH_CA_CERTS")
config = project.project_config.get_repository_config(repository, "repository")
if config is None:
config = project.global_config.get_repository_config(repository, "repository")
if config is None:
raise PdmUsageError(f"Missing repository config of {repository}")
else:
global_config = project.global_config.get_repository_config(repository, "repository")
if global_config is not None:
config.passive_update(global_config)
assert config.url is not None
if username is not None:
config.username = username
if password is not None:
config.password = password
if ca_certs is not None:
config.ca_certs = ca_certs
if options.verify_ssl is False:
config.verify_ssl = options.verify_ssl
config.populate_keyring_auth()
return Repository(project, config)
def handle(self, project: Project, options: argparse.Namespace) -> None:
hooks = HookManager(project, options.skip)
hooks.try_emit("pre_publish")
if options.build:
build.Command.do_build(project, dest=options.dest, hooks=hooks)
upload_dir = project.root.joinpath(options.dest)
package_files = [str(p) for p in upload_dir.iterdir() if not p.name.endswith(".asc")]
signatures = {p.stem: str(p) for p in upload_dir.iterdir() if p.name.endswith(".asc")}
repository = self.get_repository(project, options)
uploaded: list[PackageFile] = []
with project.core.ui.logging("publish"):
packages = sorted(
(self._make_package(p, signatures, options) for p in package_files),
# Upload wheels first if they exist.
key=lambda p: not p.base_filename.endswith(".whl"),
)
for package in packages:
resp = repository.upload(package)
logger.debug("Response from %s:\n%s %s", resp.url, resp.status_code, resp.reason_phrase)
if options.skip_existing and self._skip_upload(resp):
project.core.ui.warn(f"Skipping {package.base_filename} because it appears to already exist")
continue
self._check_response(resp)
uploaded.append(package)
release_urls = repository.get_release_urls(uploaded)
if release_urls:
project.core.ui.echo("\n[success]View at:")
for url in release_urls:
project.core.ui.echo(url)
hooks.try_emit("post_publish")
| Command |
python | ApeWorX__ape | src/ape/pytest/coverage.py | {
"start": 712,
"end": 5037
} | class ____(ManagerAccessMixin):
def __init__(
self,
project: "ProjectManager",
sources: Union[Iterable["ContractSource"], Callable[[], Iterable["ContractSource"]]],
):
self.project = project
self._sources: Union[Iterable[ContractSource], Callable[[], Iterable[ContractSource]]] = (
sources
)
self._report: Optional[CoverageReport] = None
@property
def sources(self) -> list["ContractSource"]:
if isinstance(self._sources, list):
return self._sources
elif callable(self._sources):
# Lazily evaluated.
self._sources = self._sources()
self._sources = [src for src in self._sources]
return self._sources
@property
def report(self) -> "CoverageReport":
if self._report is None:
self._report = self._init_coverage_profile()
return self._report
def reset(self):
self._report = None
self._init_coverage_profile()
def _init_coverage_profile(
self,
) -> "CoverageReport":
from ape.types.coverage import CoverageProject, CoverageReport
# source_id -> pc(s) -> times hit
project_coverage = CoverageProject(name=self.project.name or "__local__")
for src in self.sources:
source_cov = project_coverage.include(src)
ext = get_full_extension(Path(src.source_id))
if ext not in self.compiler_manager.registered_compilers:
continue
compiler = self.compiler_manager.registered_compilers[ext]
try:
compiler.init_coverage_profile(source_cov, src)
except NotImplementedError:
continue
timestamp = get_current_timestamp_ms()
report = CoverageReport(
projects=[project_coverage],
source_folders=[self.project.contracts_folder],
timestamp=timestamp,
)
# Remove empties.
for project in report.projects:
project.sources = [x for x in project.sources if len(x.statements) > 0]
return report
def cover(
self, src_path: Path, pcs: Iterable[int], inc_fn_hits: bool = True
) -> tuple[set[int], list[str]]:
if hasattr(self.project, "path"):
source_id = f"{src_path.relative_to(self.project.path)}"
else:
source_id = str(src_path)
if source_id not in self.report.sources:
# The source is not tracked for coverage.
return set(), []
handled_pcs = set()
functions_incremented: list[str] = []
for pc in pcs:
if pc < 0:
continue
if not (source_coverage := self.report.get_source_coverage(source_id)):
continue
for contract in source_coverage.contracts:
for function in contract.functions:
statements_hit = []
for statement in function.statements:
if statement in statements_hit or pc not in statement.pcs:
# With 1 group of PCs, can only hit a statement once.
# This is because likely multiple PCs together have the same
# location and are really the same statement.
# To increase the hit count by more than one, submit multiple txns.
continue
statement.hit_count += 1
handled_pcs.add(pc)
statements_hit.append(statement)
# Increment this function's hit count if we haven't already.
if inc_fn_hits and (
not functions_incremented
or function.full_name != functions_incremented[-1]
):
function.hit_count += 1
functions_incremented.append(function.full_name)
unhandled_pcs = set(pcs) - handled_pcs
if unhandled_pcs:
# Maybe a bug in ape.
logger.debug(f"Unhandled PCs: '{','.join([f'{x}' for x in unhandled_pcs])}'")
return handled_pcs, functions_incremented
| CoverageData |
python | pytorch__pytorch | benchmarks/tensorexpr/normalization.py | {
"start": 1238,
"end": 1508
} | class ____(NormalizationBench):
def forward(self):
y = self.batch_norm(
self.data, self.running_mean, self.running_var, training=self.training
)
return y
@staticmethod
def module():
return "batchnorm"
| BatchNormBench |
python | sqlalchemy__sqlalchemy | test/orm/test_eager_relations.py | {
"start": 121187,
"end": 124725
} | class ____(
fixtures.MappedTest, testing.AssertsCompiledSQL
):
__dialect__ = "default"
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"a",
metadata,
Column("id", Integer, primary_key=True),
Column("bid", ForeignKey("b.id")),
)
Table(
"b",
metadata,
Column("id", Integer, primary_key=True),
Column("cid", ForeignKey("c.id")),
)
Table("c", metadata, Column("id", Integer, primary_key=True))
Table(
"ctod",
metadata,
Column("cid", ForeignKey("c.id"), primary_key=True),
Column("did", ForeignKey("d.id"), primary_key=True),
)
Table("d", metadata, Column("id", Integer, primary_key=True))
@classmethod
def setup_classes(cls):
class A(cls.Comparable):
pass
class B(cls.Comparable):
pass
class C(cls.Comparable):
pass
class D(cls.Comparable):
pass
@classmethod
def setup_mappers(cls):
A, B, C, D = (
cls.classes.A,
cls.classes.B,
cls.classes.C,
cls.classes.D,
)
cls.mapper_registry.map_imperatively(
A, cls.tables.a, properties={"b": relationship(B)}
)
cls.mapper_registry.map_imperatively(
B, cls.tables.b, properties=odict([("c", relationship(C))])
)
cls.mapper_registry.map_imperatively(
C,
cls.tables.c,
properties=odict(
[
(
"ds",
relationship(
D,
secondary=cls.tables.ctod,
order_by=cls.tables.d.c.id,
),
)
]
),
)
cls.mapper_registry.map_imperatively(D, cls.tables.d)
@classmethod
def _fixture_data(cls):
A, B, C, D = (
cls.classes.A,
cls.classes.B,
cls.classes.C,
cls.classes.D,
)
d1, d2, d3 = D(id=1), D(id=2), D(id=3)
return [
A(id=1, b=B(id=1, c=C(id=1, ds=[d1, d2]))),
A(id=2, b=B(id=2, c=C(id=2, ds=[d2, d3]))),
]
@classmethod
def insert_data(cls, connection):
s = Session(connection)
s.add_all(cls._fixture_data())
s.commit()
def _assert_result(self, query):
def go():
eq_(query.all(), self._fixture_data())
self.assert_sql_count(testing.db, go, 1)
def test_joined_across(self):
A, B, C = self.classes("A", "B", "C")
s = fixture_session()
q = s.query(A).options(
joinedload(A.b)
.joinedload(B.c, innerjoin=True)
.joinedload(C.ds, innerjoin=True)
)
self.assert_compile(
q,
"SELECT a.id AS a_id, a.bid AS a_bid, d_1.id AS d_1_id, "
"c_1.id AS c_1_id, b_1.id AS b_1_id, b_1.cid AS b_1_cid "
"FROM a LEFT OUTER JOIN "
"(b AS b_1 JOIN "
"(c AS c_1 JOIN ctod AS ctod_1 ON c_1.id = ctod_1.cid) "
"ON c_1.id = b_1.cid "
"JOIN d AS d_1 ON d_1.id = ctod_1.did) ON b_1.id = a.bid "
"ORDER BY d_1.id",
)
self._assert_result(q)
| InnerJoinSplicingWSecondaryTest |
python | openai__openai-python | src/openai/types/beta/threads/file_path_delta_annotation.py | {
"start": 353,
"end": 755
} | class ____(BaseModel):
index: int
"""The index of the annotation in the text content part."""
type: Literal["file_path"]
"""Always `file_path`."""
end_index: Optional[int] = None
file_path: Optional[FilePath] = None
start_index: Optional[int] = None
text: Optional[str] = None
"""The text in the message content that needs to be replaced."""
| FilePathDeltaAnnotation |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/integrations/dbt/pythonic/assets_translator.py | {
"start": 231,
"end": 906
} | class ____(DagsterDbtTranslator):
def get_asset_key(self, dbt_resource_props: Mapping[str, Any]) -> dg.AssetKey:
asset_key = super().get_asset_key(dbt_resource_props)
return asset_key.with_prefix("my_prefix_")
def get_group_name(self, dbt_resource_props: Mapping[str, Any]) -> str:
# Customize group names
return "my_dbt_group"
# end_custom_dagster_dbt_translator
@dbt_assets(
manifest=dbt_project.manifest_path,
dagster_dbt_translator=CustomDagsterDbtTranslator(),
)
def dbt_models(context: dg.AssetExecutionContext, dbt: DbtCliResource):
yield from dbt.cli(["build"], context=context).stream()
| CustomDagsterDbtTranslator |
python | getsentry__sentry | src/sentry/web/forms/fields.py | {
"start": 2658,
"end": 2778
} | class ____(EmailField):
default_validators = EmailField.default_validators + [email_address_validator]
| AllowedEmailField |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/dsl/expressions/unary.py | {
"start": 677,
"end": 1500
} | class ____(Expr):
"""Class representing a cast of an expression."""
__slots__ = ()
_non_child = ("dtype",)
def __init__(self, dtype: DataType, value: Expr) -> None:
self.dtype = dtype
self.children = (value,)
self.is_pointwise = True
if not dtypes.can_cast(value.dtype.plc_type, self.dtype.plc_type):
raise NotImplementedError(
f"Can't cast {value.dtype.id().name} to {self.dtype.id().name}"
)
def do_evaluate(
self, df: DataFrame, *, context: ExecutionContext = ExecutionContext.FRAME
) -> Column:
"""Evaluate this expression given a dataframe for context."""
(child,) = self.children
column = child.evaluate(df, context=context)
return column.astype(self.dtype, stream=df.stream)
| Cast |
python | pytorch__pytorch | test/dynamo/test_subclasses.py | {
"start": 83086,
"end": 84893
} | class ____(torch.nn.Module):
def forward(
self,
primals_1: "Sym(s47)", # PlainAOTInput(idx=0)
primals_2: "Sym(s16)", # PlainAOTInput(idx=1)
primals_3: "f32[s47, s16]", # SubclassGetAttrAOTInput(base=PlainAOTInput(idx=2), attr='a')
primals_4: "f32[s47, s16]", # SubclassGetAttrAOTInput(base=PlainAOTInput(idx=2), attr='b')
primals_5: "Sym(s47)", # SubclassSizeAOTInput(base=PlainAOTInput(idx=2), idx=0)
primals_6: "Sym(s16)", # SubclassSizeAOTInput(base=PlainAOTInput(idx=2), idx=1)
primals_7: "Sym(s16)", # SubclassStrideAOTInput(base=PlainAOTInput(idx=2), idx=0)
):
clone: "f32[s47, s16]" = torch.ops.aten.clone.default(primals_3); primals_3 = None
clone_1: "f32[s47, s16]" = torch.ops.aten.clone.default(primals_4); primals_4 = None
view: "f32[s16, s47]" = torch.ops.aten.view.default(clone, [primals_2, primals_1]); clone = None
view_1: "f32[s16, s47]" = torch.ops.aten.view.default(clone_1, [primals_2, primals_1]); clone_1 = primals_1 = None
return (
view, # SubclassGetAttrAOTOutput(base=PlainAOTOutput(idx=0), attr='a')
view_1, # SubclassGetAttrAOTOutput(base=PlainAOTOutput(idx=0), attr='b')
primals_2, # SubclassSizeAOTOutput(base=PlainAOTOutput(idx=0), idx=0)
primals_5, # SubclassSizeAOTOutput(base=PlainAOTOutput(idx=0), idx=1)
primals_5, # SubclassStrideAOTOutput(base=PlainAOTOutput(idx=0), idx=0)
primals_5, # SavedForBackwardsAOTOutput(idx=0)
primals_7, # SavedForBackwardsAOTOutput(idx=1)
)
""", # noqa: B950
)
self.assertExpectedInline(
normalize_gm(bw[0].print_readable(print_output=False, expanded_def=True)),
"""\
| GraphModule |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1127224,
"end": 1130974
} | class ____(sgqlc.types.Type, Node):
"""Represents triggered deployment instance."""
__schema__ = github_schema
__field_names__ = (
"commit",
"commit_oid",
"created_at",
"creator",
"database_id",
"description",
"environment",
"latest_environment",
"latest_status",
"original_environment",
"payload",
"ref",
"repository",
"state",
"statuses",
"task",
"updated_at",
)
commit = sgqlc.types.Field(Commit, graphql_name="commit")
"""Identifies the commit sha of the deployment."""
commit_oid = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="commitOid")
"""Identifies the oid of the deployment commit, even if the commit
has been deleted.
"""
created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="createdAt")
"""Identifies the date and time when the object was created."""
creator = sgqlc.types.Field(sgqlc.types.non_null(Actor), graphql_name="creator")
"""Identifies the actor who triggered the deployment."""
database_id = sgqlc.types.Field(Int, graphql_name="databaseId")
"""Identifies the primary key from the database."""
description = sgqlc.types.Field(String, graphql_name="description")
"""The deployment description."""
environment = sgqlc.types.Field(String, graphql_name="environment")
"""The latest environment to which this deployment was made."""
latest_environment = sgqlc.types.Field(String, graphql_name="latestEnvironment")
"""The latest environment to which this deployment was made."""
latest_status = sgqlc.types.Field("DeploymentStatus", graphql_name="latestStatus")
"""The latest status of this deployment."""
original_environment = sgqlc.types.Field(String, graphql_name="originalEnvironment")
"""The original environment to which this deployment was made."""
payload = sgqlc.types.Field(String, graphql_name="payload")
"""Extra information that a deployment system might need."""
ref = sgqlc.types.Field("Ref", graphql_name="ref")
"""Identifies the Ref of the deployment, if the deployment was
created by ref.
"""
repository = sgqlc.types.Field(sgqlc.types.non_null("Repository"), graphql_name="repository")
"""Identifies the repository associated with the deployment."""
state = sgqlc.types.Field(DeploymentState, graphql_name="state")
"""The current state of the deployment."""
statuses = sgqlc.types.Field(
DeploymentStatusConnection,
graphql_name="statuses",
args=sgqlc.types.ArgDict(
(
("after", sgqlc.types.Arg(String, graphql_name="after", default=None)),
("before", sgqlc.types.Arg(String, graphql_name="before", default=None)),
("first", sgqlc.types.Arg(Int, graphql_name="first", default=None)),
("last", sgqlc.types.Arg(Int, graphql_name="last", default=None)),
)
),
)
"""A list of statuses associated with the deployment.
Arguments:
* `after` (`String`): Returns the elements in the list that come
after the specified cursor.
* `before` (`String`): Returns the elements in the list that come
before the specified cursor.
* `first` (`Int`): Returns the first _n_ elements from the list.
* `last` (`Int`): Returns the last _n_ elements from the list.
"""
task = sgqlc.types.Field(String, graphql_name="task")
"""The deployment task."""
updated_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="updatedAt")
"""Identifies the date and time when the object was last updated."""
| Deployment |
python | getsentry__sentry | src/sentry/api/serializers/models/team.py | {
"start": 4471,
"end": 5568
} | class ____(TypedDict):
id: str
slug: str
name: str
dateCreated: datetime | None
isMember: bool
teamRole: str | None
flags: dict[str, Any]
access: frozenset[str] # scopes granted by teamRole
hasAccess: bool
isPending: bool
memberCount: int
avatar: SerializedAvatarFields
# We require a third Team Response TypedDict that inherits like so:
# TeamSerializerResponse
# * BaseTeamSerializerResponse
# * _TeamSerializerResponseOptional
# instead of having this inheritance:
# BaseTeamSerializerResponse
# * _TeamSerializerResponseOptional
# b/c of how drf-spectacular builds schema using @extend_schema. When specifying a DRF serializer
# as a response, the schema will include all optional fields even if the response body for that
# request never includes those fields. There is no way to have a single serializer that we can
# manipulate to exclude optional fields at will, so we need two separate serializers where one
# returns the base response fields, and the other returns the combined base+optional response fields
| BaseTeamSerializerResponse |
python | joke2k__faker | tests/providers/test_person.py | {
"start": 40159,
"end": 42061
} | class ____(unittest.TestCase):
"""Tests person in the is_IS locale"""
def setUp(self):
self.fake = Faker("is_IS")
Faker.seed(0)
def test_first_name(self):
name = self.fake.first_name()
self.assertIsInstance(name, str)
assert name in IsISProvider.first_names
def test_first_name_male(self):
name = self.fake.first_name_male()
self.assertIsInstance(name, str)
assert name in IsISProvider.first_names_male
def test_first_name_female(self):
name = self.fake.first_name_female()
self.assertIsInstance(name, str)
assert name in IsISProvider.first_names_female
def test_last_name(self):
last_name = self.fake.last_name()
self.assertIsInstance(last_name, str)
assert last_name.endswith("son") or last_name.endswith("dóttir")
suffix = "son" if last_name.endswith("son") else "dóttir"
last_name_wo_suffix = last_name.rsplit(suffix, maxsplit=1)[0]
assert last_name_wo_suffix in IsISProvider.last_names_without_suffix
def test_last_name_male(self):
last_name = self.fake.last_name_male()
self.assertIsInstance(last_name, str)
assert last_name.endswith("son")
last_name_wo_suffix = last_name.rsplit("son", maxsplit=1)[0]
assert last_name_wo_suffix in IsISProvider.last_names_without_suffix
def test_last_name_female(self):
last_name = self.fake.last_name_female()
self.assertIsInstance(last_name, str)
assert last_name.endswith("dóttir")
last_name_wo_suffix = last_name.rsplit("dóttir", maxsplit=1)[0]
assert last_name_wo_suffix in IsISProvider.last_names_without_suffix
def test_middle_name(self):
middle_name = self.fake.middle_name()
self.assertIsInstance(middle_name, str)
assert middle_name in IsISProvider.middle_names
| TestIsIS |
python | numba__numba | numba/core/caching.py | {
"start": 14885,
"end": 16087
} | class ____(CacheImpl):
"""
Implements the logic to cache CompileResult objects.
"""
def reduce(self, cres):
"""
Returns a serialized CompileResult
"""
return cres._reduce()
def rebuild(self, target_context, payload):
"""
Returns the unserialized CompileResult
"""
return compiler.CompileResult._rebuild(target_context, *payload)
def check_cachable(self, cres):
"""
Check cachability of the given compile result.
"""
cannot_cache = None
if any(not x.can_cache for x in cres.lifted):
cannot_cache = "as it uses lifted code"
elif cres.library.has_dynamic_globals:
cannot_cache = ("as it uses dynamic globals "
"(such as ctypes pointers and large global arrays)")
if cannot_cache:
msg = ('Cannot cache compiled function "%s" %s'
% (cres.fndesc.qualname.split('.')[-1], cannot_cache))
warnings.warn_explicit(msg, NumbaWarning,
self._locator._py_file, self._lineno)
return False
return True
| CompileResultCacheImpl |
python | jazzband__django-pipeline | pipeline/finders.py | {
"start": 2187,
"end": 2605
} | class ____(PatternFilterMixin, DjangoAppDirectoriesFinder):
"""
Like AppDirectoriesFinder, but doesn't return any additional ignored
patterns.
This allows us to concentrate/compress our components without dragging
the raw versions in via collectstatic.
"""
ignore_patterns = [
"*.js",
"*.css",
"*.less",
"*.scss",
"*.styl",
]
| AppDirectoriesFinder |
python | PyCQA__pylint | tests/functional/a/abstract/abstract_class_instantiated.py | {
"start": 1147,
"end": 1220
} | class ____(Structure):
def __contains__(self, _):
pass
| Container |
python | py-pdf__pypdf | pypdf/generic/_data_structures.py | {
"start": 54338,
"end": 57776
} | class ____(TreeObject):
"""
A class representing a field dictionary.
This class is accessed through
:meth:`get_fields()<pypdf.PdfReader.get_fields>`
"""
def __init__(self, data: DictionaryObject) -> None:
DictionaryObject.__init__(self)
field_attributes = (
FieldDictionaryAttributes.attributes()
+ CheckboxRadioButtonAttributes.attributes()
)
self.indirect_reference = data.indirect_reference
for attr in field_attributes:
try:
self[NameObject(attr)] = data[attr]
except KeyError:
pass
if isinstance(self.get("/V"), EncodedStreamObject):
d = cast(EncodedStreamObject, self[NameObject("/V")]).get_data()
if isinstance(d, bytes):
d_str = d.decode()
elif d is None:
d_str = ""
else:
raise Exception("Should never happen")
self[NameObject("/V")] = TextStringObject(d_str)
# TABLE 8.69 Entries common to all field dictionaries
@property
def field_type(self) -> Optional[NameObject]:
"""Read-only property accessing the type of this field."""
return self.get(FieldDictionaryAttributes.FT)
@property
def parent(self) -> Optional[DictionaryObject]:
"""Read-only property accessing the parent of this field."""
return self.get(FieldDictionaryAttributes.Parent)
@property
def kids(self) -> Optional["ArrayObject"]:
"""Read-only property accessing the kids of this field."""
return self.get(FieldDictionaryAttributes.Kids)
@property
def name(self) -> Optional[str]:
"""Read-only property accessing the name of this field."""
return self.get(FieldDictionaryAttributes.T)
@property
def alternate_name(self) -> Optional[str]:
"""Read-only property accessing the alternate name of this field."""
return self.get(FieldDictionaryAttributes.TU)
@property
def mapping_name(self) -> Optional[str]:
"""
Read-only property accessing the mapping name of this field.
This name is used by pypdf as a key in the dictionary returned by
:meth:`get_fields()<pypdf.PdfReader.get_fields>`
"""
return self.get(FieldDictionaryAttributes.TM)
@property
def flags(self) -> Optional[int]:
"""
Read-only property accessing the field flags, specifying various
characteristics of the field (see Table 8.70 of the PDF 1.7 reference).
"""
return self.get(FieldDictionaryAttributes.Ff)
@property
def value(self) -> Optional[Any]:
"""
Read-only property accessing the value of this field.
Format varies based on field type.
"""
return self.get(FieldDictionaryAttributes.V)
@property
def default_value(self) -> Optional[Any]:
"""Read-only property accessing the default value of this field."""
return self.get(FieldDictionaryAttributes.DV)
@property
def additional_actions(self) -> Optional[DictionaryObject]:
"""
Read-only property accessing the additional actions dictionary.
This dictionary defines the field's behavior in response to trigger
events. See Section 8.5.2 of the PDF 1.7 reference.
"""
return self.get(FieldDictionaryAttributes.AA)
| Field |
python | getsentry__sentry | src/sentry/api/authentication.py | {
"start": 7735,
"end": 9223
} | class ____(BasicAuthentication):
def authenticate(self, request: Request):
relay_id = get_header_relay_id(request)
relay_sig = get_header_relay_signature(request)
if not relay_id:
raise AuthenticationFailed("Invalid relay ID")
if not relay_sig:
raise AuthenticationFailed("Missing relay signature")
return self.authenticate_credentials(relay_id, relay_sig, request)
def authenticate_credentials(
self, relay_id: str, relay_sig: str, request=None
) -> tuple[AnonymousUser, None]:
sentry_sdk.get_isolation_scope().set_tag("relay_id", relay_id)
if request is None:
raise AuthenticationFailed("missing request")
relay, static = relay_from_id(request, relay_id)
if relay is None:
raise AuthenticationFailed("Unknown relay")
if not static:
relay.is_internal = is_internal_relay(request, relay.public_key)
try:
data = relay.public_key_object.unpack(request.body, relay_sig, max_age=60 * 5)
request.relay = relay
request.relay_request_data = data
except UnpackError:
raise AuthenticationFailed("Invalid relay signature")
# TODO(mitsuhiko): can we return the relay here? would be nice if we
# could find some common interface for it
return (AnonymousUser(), None)
@AuthenticationSiloLimit(SiloMode.CONTROL, SiloMode.REGION)
| RelayAuthentication |
python | mwaskom__seaborn | tests/test_axisgrid.py | {
"start": 56974,
"end": 63161
} | class ____:
rs = np.random.RandomState(sum(map(ord, "jointplot")))
x = rs.randn(100)
y = rs.randn(100)
data = pd.DataFrame(dict(x=x, y=y))
def test_scatter(self):
g = ag.jointplot(x="x", y="y", data=self.data)
assert len(g.ax_joint.collections) == 1
x, y = g.ax_joint.collections[0].get_offsets().T
assert_array_equal(self.x, x)
assert_array_equal(self.y, y)
assert_array_almost_equal(
[b.get_x() for b in g.ax_marg_x.patches],
np.histogram_bin_edges(self.x, "auto")[:-1],
)
assert_array_almost_equal(
[b.get_y() for b in g.ax_marg_y.patches],
np.histogram_bin_edges(self.y, "auto")[:-1],
)
def test_scatter_hue(self, long_df):
g1 = ag.jointplot(data=long_df, x="x", y="y", hue="a")
g2 = ag.JointGrid()
scatterplot(data=long_df, x="x", y="y", hue="a", ax=g2.ax_joint)
kdeplot(data=long_df, x="x", hue="a", ax=g2.ax_marg_x, fill=True)
kdeplot(data=long_df, y="y", hue="a", ax=g2.ax_marg_y, fill=True)
assert_plots_equal(g1.ax_joint, g2.ax_joint)
assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)
assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)
def test_reg(self):
g = ag.jointplot(x="x", y="y", data=self.data, kind="reg")
assert len(g.ax_joint.collections) == 2
x, y = g.ax_joint.collections[0].get_offsets().T
assert_array_equal(self.x, x)
assert_array_equal(self.y, y)
assert g.ax_marg_x.patches
assert g.ax_marg_y.patches
assert g.ax_marg_x.lines
assert g.ax_marg_y.lines
def test_resid(self):
g = ag.jointplot(x="x", y="y", data=self.data, kind="resid")
assert g.ax_joint.collections
assert g.ax_joint.lines
assert not g.ax_marg_x.lines
assert not g.ax_marg_y.lines
def test_hist(self, long_df):
bins = 3, 6
g1 = ag.jointplot(data=long_df, x="x", y="y", kind="hist", bins=bins)
g2 = ag.JointGrid()
histplot(data=long_df, x="x", y="y", ax=g2.ax_joint, bins=bins)
histplot(data=long_df, x="x", ax=g2.ax_marg_x, bins=bins[0])
histplot(data=long_df, y="y", ax=g2.ax_marg_y, bins=bins[1])
assert_plots_equal(g1.ax_joint, g2.ax_joint)
assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)
assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)
def test_hex(self):
g = ag.jointplot(x="x", y="y", data=self.data, kind="hex")
assert g.ax_joint.collections
assert g.ax_marg_x.patches
assert g.ax_marg_y.patches
def test_kde(self, long_df):
g1 = ag.jointplot(data=long_df, x="x", y="y", kind="kde")
g2 = ag.JointGrid()
kdeplot(data=long_df, x="x", y="y", ax=g2.ax_joint)
kdeplot(data=long_df, x="x", ax=g2.ax_marg_x)
kdeplot(data=long_df, y="y", ax=g2.ax_marg_y)
assert_plots_equal(g1.ax_joint, g2.ax_joint)
assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)
assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)
def test_kde_hue(self, long_df):
g1 = ag.jointplot(data=long_df, x="x", y="y", hue="a", kind="kde")
g2 = ag.JointGrid()
kdeplot(data=long_df, x="x", y="y", hue="a", ax=g2.ax_joint)
kdeplot(data=long_df, x="x", hue="a", ax=g2.ax_marg_x)
kdeplot(data=long_df, y="y", hue="a", ax=g2.ax_marg_y)
assert_plots_equal(g1.ax_joint, g2.ax_joint)
assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)
assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)
def test_color(self):
g = ag.jointplot(x="x", y="y", data=self.data, color="purple")
scatter_color = g.ax_joint.collections[0].get_facecolor()
assert_colors_equal(scatter_color, "purple")
hist_color = g.ax_marg_x.patches[0].get_facecolor()[:3]
assert_colors_equal(hist_color, "purple")
def test_palette(self, long_df):
kws = dict(data=long_df, hue="a", palette="Set2")
g1 = ag.jointplot(x="x", y="y", **kws)
g2 = ag.JointGrid()
scatterplot(x="x", y="y", ax=g2.ax_joint, **kws)
kdeplot(x="x", ax=g2.ax_marg_x, fill=True, **kws)
kdeplot(y="y", ax=g2.ax_marg_y, fill=True, **kws)
assert_plots_equal(g1.ax_joint, g2.ax_joint)
assert_plots_equal(g1.ax_marg_x, g2.ax_marg_x, labels=False)
assert_plots_equal(g1.ax_marg_y, g2.ax_marg_y, labels=False)
def test_hex_customise(self):
# test that default gridsize can be overridden
g = ag.jointplot(x="x", y="y", data=self.data, kind="hex",
joint_kws=dict(gridsize=5))
assert len(g.ax_joint.collections) == 1
a = g.ax_joint.collections[0].get_array()
assert a.shape[0] == 28 # 28 hexagons expected for gridsize 5
def test_bad_kind(self):
with pytest.raises(ValueError):
ag.jointplot(x="x", y="y", data=self.data, kind="not_a_kind")
def test_unsupported_hue_kind(self):
for kind in ["reg", "resid", "hex"]:
with pytest.raises(ValueError):
ag.jointplot(x="x", y="y", hue="a", data=self.data, kind=kind)
def test_leaky_dict(self):
# Validate input dicts are unchanged by jointplot plotting function
for kwarg in ("joint_kws", "marginal_kws"):
for kind in ("hex", "kde", "resid", "reg", "scatter"):
empty_dict = {}
ag.jointplot(x="x", y="y", data=self.data, kind=kind,
**{kwarg: empty_dict})
assert empty_dict == {}
def test_distplot_kwarg_warning(self, long_df):
with pytest.warns(UserWarning):
g = ag.jointplot(data=long_df, x="x", y="y", marginal_kws=dict(rug=True))
assert g.ax_marg_x.patches
def test_ax_warning(self, long_df):
ax = plt.gca()
with pytest.warns(UserWarning):
g = ag.jointplot(data=long_df, x="x", y="y", ax=ax)
assert g.ax_joint.collections
| TestJointPlot |
python | HIPS__autograd | autograd/tracer.py | {
"start": 535,
"end": 2715
} | class ____:
__slots__ = []
def __init__(self, value, fun, args, kwargs, parent_argnums, parents):
assert False
def initialize_root(self, *args, **kwargs):
assert False
@classmethod
def new_root(cls, *args, **kwargs):
root = cls.__new__(cls)
root.initialize_root(*args, **kwargs)
return root
def primitive(f_raw):
"""
Wraps a function so that its gradient can be specified and its invocation
can be recorded. For examples, see the docs."""
@wraps(f_raw)
def f_wrapped(*args, **kwargs):
boxed_args, trace, node_constructor = find_top_boxed_args(args)
if boxed_args:
argvals = subvals(args, [(argnum, box._value) for argnum, box in boxed_args])
if f_wrapped in notrace_primitives[node_constructor]:
return f_wrapped(*argvals, **kwargs)
parents = tuple(box._node for _, box in boxed_args)
argnums = tuple(argnum for argnum, _ in boxed_args)
ans = f_wrapped(*argvals, **kwargs)
node = node_constructor(ans, f_wrapped, argvals, kwargs, argnums, parents)
return new_box(ans, trace, node)
else:
return f_raw(*args, **kwargs)
f_wrapped.fun = f_raw
f_wrapped._is_autograd_primitive = True
return f_wrapped
notrace_primitives = defaultdict(set)
def register_notrace(trace_type, primitive_fun):
notrace_primitives[trace_type].add(primitive_fun)
def notrace_primitive(f_raw):
@wraps(f_raw)
def f_wrapped(*args, **kwargs):
argvals = map(getval, args)
return f_raw(*argvals, **kwargs)
f_wrapped._is_primitive = True
return f_wrapped
def find_top_boxed_args(args):
top_trace = -1
top_boxes = []
top_node_type = None
for argnum, arg in enumerate(args):
if isbox(arg):
trace = arg._trace
if trace > top_trace:
top_boxes = [(argnum, arg)]
top_trace = trace
top_node_type = type(arg._node)
elif trace == top_trace:
top_boxes.append((argnum, arg))
return top_boxes, top_trace, top_node_type
| Node |
python | TheAlgorithms__Python | graphs/bidirectional_breadth_first_search.py | {
"start": 455,
"end": 753
} | class ____:
def __init__(
self, pos_x: int, pos_y: int, goal_x: int, goal_y: int, parent: Node | None
):
self.pos_x = pos_x
self.pos_y = pos_y
self.pos = (pos_y, pos_x)
self.goal_x = goal_x
self.goal_y = goal_y
self.parent = parent
| Node |
python | python__mypy | mypy/types.py | {
"start": 100096,
"end": 106999
} | class ____(ProperType):
"""The tuple type Tuple[T1, ..., Tn] (at least one type argument).
Instance variables:
items: Tuple item types
partial_fallback: The (imprecise) underlying instance type that is used
for non-tuple methods. This is generally builtins.tuple[Any, ...] for
regular tuples, but it's different for named tuples and classes with
a tuple base class. Use mypy.typeops.tuple_fallback to calculate the
precise fallback type derived from item types.
implicit: If True, derived from a tuple expression (t,....) instead of Tuple[t, ...]
"""
__slots__ = ("items", "partial_fallback", "implicit")
items: list[Type]
partial_fallback: Instance
implicit: bool
def __init__(
self,
items: list[Type],
fallback: Instance,
line: int = -1,
column: int = -1,
implicit: bool = False,
) -> None:
super().__init__(line, column)
self.partial_fallback = fallback
self.items = items
self.implicit = implicit
def can_be_true_default(self) -> bool:
if self.can_be_any_bool():
# Corner case: it is a `NamedTuple` with `__bool__` method defined.
# It can be anything: both `True` and `False`.
return True
return self.length() > 0
def can_be_false_default(self) -> bool:
if self.can_be_any_bool():
# Corner case: it is a `NamedTuple` with `__bool__` method defined.
# It can be anything: both `True` and `False`.
return True
if self.length() == 0:
return True
if self.length() > 1:
return False
# Special case tuple[*Ts] may or may not be false.
item = self.items[0]
if not isinstance(item, UnpackType):
return False
if not isinstance(item.type, TypeVarTupleType):
# Non-normalized tuple[int, ...] can be false.
return True
return item.type.min_len == 0
def can_be_any_bool(self) -> bool:
return bool(
self.partial_fallback.type
and self.partial_fallback.type.fullname != "builtins.tuple"
and self.partial_fallback.type.names.get("__bool__")
)
def length(self) -> int:
return len(self.items)
def accept(self, visitor: TypeVisitor[T]) -> T:
return visitor.visit_tuple_type(self)
def __hash__(self) -> int:
return hash((tuple(self.items), self.partial_fallback))
def __eq__(self, other: object) -> bool:
if not isinstance(other, TupleType):
return NotImplemented
return self.items == other.items and self.partial_fallback == other.partial_fallback
def serialize(self) -> JsonDict:
return {
".class": "TupleType",
"items": [t.serialize() for t in self.items],
"partial_fallback": self.partial_fallback.serialize(),
"implicit": self.implicit,
}
@classmethod
def deserialize(cls, data: JsonDict) -> TupleType:
assert data[".class"] == "TupleType"
return TupleType(
[deserialize_type(t) for t in data["items"]],
Instance.deserialize(data["partial_fallback"]),
implicit=data["implicit"],
)
def write(self, data: WriteBuffer) -> None:
write_tag(data, TUPLE_TYPE)
self.partial_fallback.write(data)
write_type_list(data, self.items)
write_bool(data, self.implicit)
write_tag(data, END_TAG)
@classmethod
def read(cls, data: ReadBuffer) -> TupleType:
assert read_tag(data) == INSTANCE
fallback = Instance.read(data)
ret = TupleType(read_type_list(data), fallback, implicit=read_bool(data))
assert read_tag(data) == END_TAG
return ret
def copy_modified(
self, *, fallback: Instance | None = None, items: list[Type] | None = None
) -> TupleType:
if fallback is None:
fallback = self.partial_fallback
if items is None:
items = self.items
return TupleType(items, fallback, self.line, self.column)
def slice(
self, begin: int | None, end: int | None, stride: int | None, *, fallback: Instance | None
) -> TupleType | None:
if fallback is None:
fallback = self.partial_fallback
if stride == 0:
return None
if any(isinstance(t, UnpackType) for t in self.items):
total = len(self.items)
unpack_index = find_unpack_in_list(self.items)
assert unpack_index is not None
if begin is None and end is None:
# We special-case this to support reversing variadic tuples.
# General support for slicing is tricky, so we handle only simple cases.
if stride == -1:
slice_items = self.items[::-1]
elif stride is None or stride == 1:
slice_items = self.items
else:
return None
elif (begin is None or unpack_index >= begin >= 0) and (
end is not None and unpack_index >= end >= 0
):
# Start and end are in the prefix, everything works in this case.
slice_items = self.items[begin:end:stride]
elif (begin is not None and unpack_index - total < begin < 0) and (
end is None or unpack_index - total < end < 0
):
# Start and end are in the suffix, everything works in this case.
slice_items = self.items[begin:end:stride]
elif (begin is None or unpack_index >= begin >= 0) and (
end is None or unpack_index - total < end < 0
):
# Start in the prefix, end in the suffix, we can support only trivial strides.
if stride is None or stride == 1:
slice_items = self.items[begin:end:stride]
else:
return None
elif (begin is not None and unpack_index - total < begin < 0) and (
end is not None and unpack_index >= end >= 0
):
# Start in the suffix, end in the prefix, we can support only trivial strides.
if stride is None or stride == -1:
slice_items = self.items[begin:end:stride]
else:
return None
else:
# TODO: there some additional cases we can support for homogeneous variadic
# items, we can "eat away" finite number of items.
return None
else:
slice_items = self.items[begin:end:stride]
return TupleType(slice_items, fallback, self.line, self.column, self.implicit)
| TupleType |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/suite/test_select.py | {
"start": 59371,
"end": 64104
} | class ____(fixtures.TablesTest):
__requires__ = ("window_functions",)
__sparse_driver_backend__ = True
@classmethod
def define_tables(cls, metadata):
Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("col1", Integer),
Column("col2", Integer),
Column("col3", Float),
)
@classmethod
def insert_data(cls, connection):
def row_factory(i):
return {
"id": i,
"col1": i,
"col2": i * 5,
"col3": i + 0.5,
}
connection.execute(
cls.tables.some_table.insert(),
[row_factory(i) for i in range(1, 50)],
)
def test_window(self, connection):
some_table = self.tables.some_table
rows = connection.execute(
select(
func.max(some_table.c.col2).over(
order_by=[some_table.c.col1.desc()]
)
).where(some_table.c.col1 < 20)
).all()
eq_(rows, [(95,) for i in range(19)])
@testing.requires.window_range
def test_window_range(self, connection):
some_table = self.tables.some_table
rows = connection.execute(
select(
func.max(some_table.c.col1).over(
partition_by=[some_table.c.col2],
order_by=[some_table.c.col2.asc()],
range_=(0, 1),
)
).where(some_table.c.col1 < 20)
).all()
eq_(rows, [(i,) for i in range(1, 20)])
@testing.requires.window_range_numeric
def test_window_range_numeric(self, connection):
some_table = self.tables.some_table
rows = connection.execute(
select(
func.max(some_table.c.col3).over(
partition_by=[some_table.c.col3],
order_by=[some_table.c.col3.asc()],
range_=FrameClause(
1.25,
1.25,
FrameClauseType.PRECEDING,
FrameClauseType.FOLLOWING,
),
)
).where(some_table.c.col1 < 20)
).all()
eq_(rows, [(i + 0.5,) for i in range(1, 20)])
@testing.requires.window_range_non_numeric
def test_window_range_dates(self, connection, metadata):
t = Table(
"range_string",
metadata,
Column("value", Integer),
Column("oder", Date),
)
t.create(connection)
connection.execute(
t.insert(),
[
{"value": 1, "oder": date(2025, 10, 1)},
{"value": 2, "oder": date(2025, 10, 2)},
{"value": 3, "oder": date(2025, 10, 10)},
{"value": 4, "oder": date(2025, 10, 13)},
{"value": 5, "oder": date(2025, 10, 16)},
],
)
rows = connection.execute(
select(
func.sum(t.c.value).over(
order_by=t.c.oder,
range_=FrameClause(
timedelta(days=7),
None,
FrameClauseType.PRECEDING,
FrameClauseType.CURRENT,
),
)
).order_by(t.c.oder)
).all()
eq_(rows, [(1,), (3,), (3,), (7,), (12,)])
def test_window_rows_between_w_caching(self, connection):
some_table = self.tables.some_table
# this tests that dialects such as SQL Server which require literal
# rendering of ROWS BETWEEN and RANGE BETWEEN numerical values make
# use of literal_execute, for post-cache rendering of integer values,
# and not literal_binds which would include the integer values in the
# cached string (caching overall fixed in #11515)
for i in range(3):
for rows, expected in [
(
(5, 20),
list(range(105, 245, 5)) + ([245] * 16) + [None] * 5,
),
(
(20, 30),
list(range(155, 245, 5)) + ([245] * 11) + [None] * 20,
),
]:
result_rows = connection.execute(
select(
func.max(some_table.c.col2).over(
order_by=[some_table.c.col1],
rows=rows,
)
)
).all()
eq_(result_rows, [(i,) for i in expected])
| WindowFunctionTest |
python | eventlet__eventlet | eventlet/support/stacklesss.py | {
"start": 1357,
"end": 1851
} | class ____(Exception):
pass
def emulate():
module = types.ModuleType('greenlet')
sys.modules['greenlet'] = module
module.greenlet = greenlet
module.getcurrent = getcurrent
module.GreenletExit = GreenletExit
caller = stackless.getcurrent()
tasklet_to_greenlet[caller] = None
main_coro = greenlet()
tasklet_to_greenlet[caller] = main_coro
main_coro.t = caller
del main_coro.switch # It's already running
coro_args[main_coro] = None
| GreenletExit |
python | doocs__leetcode | solution/0400-0499/0491.Non-decreasing Subsequences/Solution.py | {
"start": 0,
"end": 495
} | class ____:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
def dfs(u, last, t):
if u == len(nums):
if len(t) > 1:
ans.append(t[:])
return
if nums[u] >= last:
t.append(nums[u])
dfs(u + 1, nums[u], t)
t.pop()
if nums[u] != last:
dfs(u + 1, last, t)
ans = []
dfs(0, -1000, [])
return ans
| Solution |
python | apache__avro | lang/py/avro/schema.py | {
"start": 30380,
"end": 30974
} | class ____(UnionSchema):
def __init__(self, schemas, names=None, validate_names: bool = True):
# Prepend "string" to handle system errors
UnionSchema.__init__(self, ["string"] + schemas, names, validate_names)
def to_json(self, names=None):
names = names or Names(validate_names=self.validate_names)
to_dump = []
for schema in self.schemas:
# Don't print the system error schema
if schema.type == "string":
continue
to_dump.append(schema.to_json(names))
return to_dump
| ErrorUnionSchema |
python | gevent__gevent | src/gevent/tests/test__threading_before_monkey.py | {
"start": 274,
"end": 714
} | class ____(greentest.TestCase):
def test_main_thread(self):
current = threading.current_thread()
self.assertFalse(isinstance(current, threading._DummyThread))
self.assertTrue(isinstance(current, monkey.get_original('threading', 'Thread')))
# in 3.4, if the patch is incorrectly done, getting the repr
# of the thread fails
repr(current)
if __name__ == '__main__':
greentest.main()
| Test |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 182859,
"end": 188456
} | class ____(ThreadedTCPSocketTest):
def __init__(self, methodName='runTest'):
self.event = threading.Event()
ThreadedTCPSocketTest.__init__(self, methodName=methodName)
def assert_sock_timeout(self, sock, timeout):
self.assertEqual(self.serv.gettimeout(), timeout)
blocking = (timeout != 0.0)
self.assertEqual(sock.getblocking(), blocking)
if fcntl is not None:
# When a Python socket has a non-zero timeout, it's switched
# internally to a non-blocking mode. Later, sock.sendall(),
# sock.recv(), and other socket operations use a select() call and
# handle EWOULDBLOCK/EGAIN on all socket operations. That's how
# timeouts are enforced.
fd_blocking = (timeout is None)
flag = fcntl.fcntl(sock, fcntl.F_GETFL, os.O_NONBLOCK)
self.assertEqual(not bool(flag & os.O_NONBLOCK), fd_blocking)
def testSetBlocking(self):
# Test setblocking() and settimeout() methods
self.serv.setblocking(True)
self.assert_sock_timeout(self.serv, None)
self.serv.setblocking(False)
self.assert_sock_timeout(self.serv, 0.0)
self.serv.settimeout(None)
self.assert_sock_timeout(self.serv, None)
self.serv.settimeout(0)
self.assert_sock_timeout(self.serv, 0)
self.serv.settimeout(10)
self.assert_sock_timeout(self.serv, 10)
self.serv.settimeout(0)
self.assert_sock_timeout(self.serv, 0)
def _testSetBlocking(self):
pass
@support.cpython_only
def testSetBlocking_overflow(self):
# Issue 15989
import _testcapi
if _testcapi.UINT_MAX >= _testcapi.ULONG_MAX:
self.skipTest('needs UINT_MAX < ULONG_MAX')
self.serv.setblocking(False)
self.assertEqual(self.serv.gettimeout(), 0.0)
self.serv.setblocking(_testcapi.UINT_MAX + 1)
self.assertIsNone(self.serv.gettimeout())
_testSetBlocking_overflow = support.cpython_only(_testSetBlocking)
@unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'),
'test needs socket.SOCK_NONBLOCK')
@support.requires_linux_version(2, 6, 28)
def testInitNonBlocking(self):
# create a socket with SOCK_NONBLOCK
self.serv.close()
self.serv = socket.socket(socket.AF_INET,
socket.SOCK_STREAM | socket.SOCK_NONBLOCK)
self.assert_sock_timeout(self.serv, 0)
def _testInitNonBlocking(self):
pass
def testInheritFlagsBlocking(self):
# bpo-7995: accept() on a listening socket with a timeout and the
# default timeout is None, the resulting socket must be blocking.
with socket_setdefaulttimeout(None):
self.serv.settimeout(10)
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
self.assertIsNone(conn.gettimeout())
def _testInheritFlagsBlocking(self):
self.cli.connect((HOST, self.port))
def testInheritFlagsTimeout(self):
# bpo-7995: accept() on a listening socket with a timeout and the
# default timeout is None, the resulting socket must inherit
# the default timeout.
default_timeout = 20.0
with socket_setdefaulttimeout(default_timeout):
self.serv.settimeout(10)
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
self.assertEqual(conn.gettimeout(), default_timeout)
def _testInheritFlagsTimeout(self):
self.cli.connect((HOST, self.port))
def testAccept(self):
# Testing non-blocking accept
self.serv.setblocking(False)
# connect() didn't start: non-blocking accept() fails
start_time = time.monotonic()
with self.assertRaises(BlockingIOError):
conn, addr = self.serv.accept()
dt = time.monotonic() - start_time
self.assertLess(dt, 1.0)
self.event.set()
read, write, err = select.select([self.serv], [], [], support.LONG_TIMEOUT)
if self.serv not in read:
self.fail("Error trying to do accept after select.")
# connect() completed: non-blocking accept() doesn't block
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
self.assertIsNone(conn.gettimeout())
def _testAccept(self):
# don't connect before event is set to check
# that non-blocking accept() raises BlockingIOError
self.event.wait()
self.cli.connect((HOST, self.port))
def testRecv(self):
# Testing non-blocking recv
conn, addr = self.serv.accept()
self.addCleanup(conn.close)
conn.setblocking(False)
# the server didn't send data yet: non-blocking recv() fails
with self.assertRaises(BlockingIOError):
msg = conn.recv(len(MSG))
self.event.set()
read, write, err = select.select([conn], [], [], support.LONG_TIMEOUT)
if conn not in read:
self.fail("Error during select call to non-blocking socket.")
# the server sent data yet: non-blocking recv() doesn't block
msg = conn.recv(len(MSG))
self.assertEqual(msg, MSG)
def _testRecv(self):
self.cli.connect((HOST, self.port))
# don't send anything before event is set to check
# that non-blocking recv() raises BlockingIOError
self.event.wait()
# send data: recv() will no longer block
self.cli.sendall(MSG)
| NonBlockingTCPTests |
python | graphql-python__graphene | graphene/tests/issues/test_425.py | {
"start": 2362,
"end": 3101
} | class ____(Enum):
@classmethod
def __init_subclass_with_meta__(cls, other_attr="default", **options):
_meta = SpecialEnumOptions(cls)
_meta.other_attr = other_attr
super(SpecialEnum, cls).__init_subclass_with_meta__(_meta=_meta, **options)
def test_special_enum_could_be_subclassed():
class MyEnum(SpecialEnum):
class Meta:
other_attr = "yeah!"
assert MyEnum._meta.other_attr == "yeah!"
def test_special_enum_could_be_subclassed_default():
class MyEnum(SpecialEnum):
pass
assert MyEnum._meta.other_attr == "default"
def test_special_enum_inherit_meta_options():
class MyEnum(SpecialEnum):
pass
assert MyEnum._meta.name == "MyEnum"
| SpecialEnum |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/values.py | {
"start": 6978,
"end": 7752
} | class ____(type_spec_lib.TypeSpec):
"""TypeSpec for PerWorkerValues.
It only support tracing a function using a PerWorkerValues.
"""
def __init__(self, value_spec, descendant_type):
assert value_spec
self._value_spec = value_spec
self._descendant_type = descendant_type
def _serialize(self):
return (self._value_spec,)
@property
def value_type(self):
return self._descendant_type
def most_specific_common_supertype(self, others):
raise NotImplementedError(
"most_specific_common_supertype is not implemented")
@property
def _component_specs(self):
return self._value_spec
def _to_components(self, value):
return self._value_spec
def _from_components(self, value):
return value
| PerWorkerValuesTypeSpec |
python | wandb__wandb | wandb/sdk/lib/config_util.py | {
"start": 219,
"end": 2914
} | class ____(Error):
pass
def dict_from_proto_list(obj_list):
d = dict()
for item in obj_list:
d[item.key] = dict(desc=None, value=json.loads(item.value_json))
return d
def dict_strip_value_dict(config_dict):
d = dict()
for k, v in config_dict.items():
d[k] = v["value"]
return d
def dict_no_value_from_proto_list(obj_list):
d = dict()
for item in obj_list:
possible_dict = json.loads(item.value_json)
if not isinstance(possible_dict, dict) or "value" not in possible_dict:
continue
d[item.key] = possible_dict["value"]
return d
# TODO(jhr): these functions should go away once we merge jobspec PR
def save_config_file_from_dict(config_filename, config_dict):
import yaml
s = b"wandb_version: 1"
if config_dict: # adding an empty dictionary here causes a parse error
s += b"\n\n" + yaml.dump(
config_dict,
Dumper=yaml.SafeDumper,
default_flow_style=False,
allow_unicode=True,
encoding="utf-8",
sort_keys=False,
)
data = s.decode("utf-8")
filesystem.mkdir_exists_ok(os.path.dirname(config_filename))
with open(config_filename, "w") as conf_file:
conf_file.write(data)
def dict_from_config_file(
filename: str, must_exist: bool = False
) -> Optional[Dict[str, Any]]:
import yaml
if not os.path.exists(filename):
if must_exist:
raise ConfigError(f"config file {filename} doesn't exist")
logger.debug(f"no default config file found in {filename}")
return None
try:
conf_file = open(filename)
except OSError:
raise ConfigError(f"Couldn't read config file: {filename}")
try:
loaded = load_yaml(conf_file)
except yaml.parser.ParserError:
raise ConfigError("Invalid YAML in config yaml")
if loaded is None:
wandb.termwarn(
"Found an empty default config file (config-defaults.yaml). Proceeding with no defaults."
)
return None
config_version = loaded.pop("wandb_version", None)
if config_version is not None and config_version != 1:
raise ConfigError("Unknown config version")
data = dict()
for k, v in loaded.items():
data[k] = v["value"]
return data
def merge_dicts(dest: dict, src: dict) -> dict:
"""Recursively merge two dictionaries. Similar to Lodash's _.merge()."""
for key, value in src.items():
if isinstance(value, dict) and key in dest and isinstance(dest[key], dict):
merge_dicts(dest[key], value)
else:
dest[key] = value
return dest
| ConfigError |
python | anthropics__anthropic-sdk-python | tests/api_resources/beta/skills/test_versions.py | {
"start": 562,
"end": 9234
} | class ____:
parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
@pytest.mark.skip(reason="prism binary unsupported")
@parametrize
def test_method_create(self, client: Anthropic) -> None:
version = client.beta.skills.versions.create(
skill_id="skill_id",
)
assert_matches_type(VersionCreateResponse, version, path=["response"])
@pytest.mark.skip(reason="prism binary unsupported")
@parametrize
def test_method_create_with_all_params(self, client: Anthropic) -> None:
version = client.beta.skills.versions.create(
skill_id="skill_id",
files=[b"raw file contents"],
betas=["string"],
)
assert_matches_type(VersionCreateResponse, version, path=["response"])
@pytest.mark.skip(reason="prism binary unsupported")
@parametrize
def test_raw_response_create(self, client: Anthropic) -> None:
response = client.beta.skills.versions.with_raw_response.create(
skill_id="skill_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
version = response.parse()
assert_matches_type(VersionCreateResponse, version, path=["response"])
@pytest.mark.skip(reason="prism binary unsupported")
@parametrize
def test_streaming_response_create(self, client: Anthropic) -> None:
with client.beta.skills.versions.with_streaming_response.create(
skill_id="skill_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
version = response.parse()
assert_matches_type(VersionCreateResponse, version, path=["response"])
assert cast(Any, response.is_closed) is True
@pytest.mark.skip(reason="prism binary unsupported")
@parametrize
def test_path_params_create(self, client: Anthropic) -> None:
with pytest.raises(ValueError, match=r"Expected a non-empty value for `skill_id` but received ''"):
client.beta.skills.versions.with_raw_response.create(
skill_id="",
)
@parametrize
def test_method_retrieve(self, client: Anthropic) -> None:
version = client.beta.skills.versions.retrieve(
version="version",
skill_id="skill_id",
)
assert_matches_type(VersionRetrieveResponse, version, path=["response"])
@parametrize
def test_method_retrieve_with_all_params(self, client: Anthropic) -> None:
version = client.beta.skills.versions.retrieve(
version="version",
skill_id="skill_id",
betas=["string"],
)
assert_matches_type(VersionRetrieveResponse, version, path=["response"])
@parametrize
def test_raw_response_retrieve(self, client: Anthropic) -> None:
response = client.beta.skills.versions.with_raw_response.retrieve(
version="version",
skill_id="skill_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
version = response.parse()
assert_matches_type(VersionRetrieveResponse, version, path=["response"])
@parametrize
def test_streaming_response_retrieve(self, client: Anthropic) -> None:
with client.beta.skills.versions.with_streaming_response.retrieve(
version="version",
skill_id="skill_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
version = response.parse()
assert_matches_type(VersionRetrieveResponse, version, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_retrieve(self, client: Anthropic) -> None:
with pytest.raises(ValueError, match=r"Expected a non-empty value for `skill_id` but received ''"):
client.beta.skills.versions.with_raw_response.retrieve(
version="version",
skill_id="",
)
with pytest.raises(ValueError, match=r"Expected a non-empty value for `version` but received ''"):
client.beta.skills.versions.with_raw_response.retrieve(
version="",
skill_id="skill_id",
)
@parametrize
def test_method_list(self, client: Anthropic) -> None:
version = client.beta.skills.versions.list(
skill_id="skill_id",
)
assert_matches_type(SyncPageCursor[VersionListResponse], version, path=["response"])
@parametrize
def test_method_list_with_all_params(self, client: Anthropic) -> None:
version = client.beta.skills.versions.list(
skill_id="skill_id",
limit=0,
page="page",
betas=["string"],
)
assert_matches_type(SyncPageCursor[VersionListResponse], version, path=["response"])
@parametrize
def test_raw_response_list(self, client: Anthropic) -> None:
response = client.beta.skills.versions.with_raw_response.list(
skill_id="skill_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
version = response.parse()
assert_matches_type(SyncPageCursor[VersionListResponse], version, path=["response"])
@parametrize
def test_streaming_response_list(self, client: Anthropic) -> None:
with client.beta.skills.versions.with_streaming_response.list(
skill_id="skill_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
version = response.parse()
assert_matches_type(SyncPageCursor[VersionListResponse], version, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_list(self, client: Anthropic) -> None:
with pytest.raises(ValueError, match=r"Expected a non-empty value for `skill_id` but received ''"):
client.beta.skills.versions.with_raw_response.list(
skill_id="",
)
@parametrize
def test_method_delete(self, client: Anthropic) -> None:
version = client.beta.skills.versions.delete(
version="version",
skill_id="skill_id",
)
assert_matches_type(VersionDeleteResponse, version, path=["response"])
@parametrize
def test_method_delete_with_all_params(self, client: Anthropic) -> None:
version = client.beta.skills.versions.delete(
version="version",
skill_id="skill_id",
betas=["string"],
)
assert_matches_type(VersionDeleteResponse, version, path=["response"])
@parametrize
def test_raw_response_delete(self, client: Anthropic) -> None:
response = client.beta.skills.versions.with_raw_response.delete(
version="version",
skill_id="skill_id",
)
assert response.is_closed is True
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
version = response.parse()
assert_matches_type(VersionDeleteResponse, version, path=["response"])
@parametrize
def test_streaming_response_delete(self, client: Anthropic) -> None:
with client.beta.skills.versions.with_streaming_response.delete(
version="version",
skill_id="skill_id",
) as response:
assert not response.is_closed
assert response.http_request.headers.get("X-Stainless-Lang") == "python"
version = response.parse()
assert_matches_type(VersionDeleteResponse, version, path=["response"])
assert cast(Any, response.is_closed) is True
@parametrize
def test_path_params_delete(self, client: Anthropic) -> None:
with pytest.raises(ValueError, match=r"Expected a non-empty value for `skill_id` but received ''"):
client.beta.skills.versions.with_raw_response.delete(
version="version",
skill_id="",
)
with pytest.raises(ValueError, match=r"Expected a non-empty value for `version` but received ''"):
client.beta.skills.versions.with_raw_response.delete(
version="",
skill_id="skill_id",
)
| TestVersions |
python | pytorch__pytorch | torch/distributed/_shard/sharding_plan/api.py | {
"start": 3024,
"end": 3649
} | class ____(abc.ABC):
"""
Default ShardingPlanner interface, can be extended and
implement advanced sharding strategies.
"""
@abc.abstractmethod
def build_plan(self, module: nn.Module) -> ShardingPlan:
"""
Given a nn.Module, define how to shard the module across
ranks, return a ShardingPlan
Args:
module (:class:`torch.nn.Module`):
The module to apply sharding to.
Returns:
A :class:`torch.distributed._shard.sharding_plan.ShardingPlan` object that
represents how to shard the module.
"""
| ShardingPlanner |
python | networkx__networkx | networkx/algorithms/tests/test_euler.py | {
"start": 281,
"end": 1334
} | class ____:
def test_is_eulerian(self):
assert nx.is_eulerian(nx.complete_graph(5))
assert nx.is_eulerian(nx.complete_graph(7))
assert nx.is_eulerian(nx.hypercube_graph(4))
assert nx.is_eulerian(nx.hypercube_graph(6))
assert not nx.is_eulerian(nx.complete_graph(4))
assert not nx.is_eulerian(nx.complete_graph(6))
assert not nx.is_eulerian(nx.hypercube_graph(3))
assert not nx.is_eulerian(nx.hypercube_graph(5))
assert not nx.is_eulerian(nx.petersen_graph())
assert not nx.is_eulerian(nx.path_graph(4))
def test_is_eulerian2(self):
# not connected
G = nx.Graph()
G.add_nodes_from([1, 2, 3])
assert not nx.is_eulerian(G)
# not strongly connected
G = nx.DiGraph()
G.add_nodes_from([1, 2, 3])
assert not nx.is_eulerian(G)
G = nx.MultiDiGraph()
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(2, 3)
G.add_edge(3, 1)
assert not nx.is_eulerian(G)
| TestIsEulerian |
python | python__mypy | mypyc/test-data/fixtures/testutil.py | {
"start": 2583,
"end": 3045
} | class ____(Awaitable[V], Generic[T, V]):
def __init__(self, val: T) -> None:
self.val = val
def __await__(self) -> Generator[T, V, V]:
z = yield self.val
return z
# Wrap a mypyc-generated function in a real python function, to allow it to be
# stuck into classes and the like.
def make_python_function(f: F) -> F:
def g(*args: Any, **kwargs: Any) -> Any:
return f(*args, **kwargs)
return g # type: ignore
| async_val |
python | sympy__sympy | sympy/physics/biomechanics/musculotendon.py | {
"start": 3494,
"end": 42867
} | class ____(ForceActuator, _NamedMixin):
r"""Abstract base class for all musculotendon classes to inherit from.
Explanation
===========
A musculotendon generates a contractile force based on its activation,
length, and shortening velocity. This abstract base class is to be inherited
by all musculotendon subclasses that implement different characteristic
musculotendon curves. Characteristic musculotendon curves are required for
the tendon force-length, passive fiber force-length, active fiber force-
length, and fiber force-velocity relationships.
Parameters
==========
name : str
The name identifier associated with the musculotendon. This name is used
as a suffix when automatically generated symbols are instantiated. It
must be a string of nonzero length.
pathway : PathwayBase
The pathway that the actuator follows. This must be an instance of a
concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
activation_dynamics : ActivationBase
The activation dynamics that will be modeled within the musculotendon.
This must be an instance of a concrete subclass of ``ActivationBase``,
e.g. ``FirstOrderActivationDeGroote2016``.
musculotendon_dynamics : MusculotendonFormulation | int
The formulation of musculotendon dynamics that should be used
internally, i.e. rigid or elastic tendon model, the choice of
musculotendon state etc. This must be a member of the integer
enumeration ``MusculotendonFormulation`` or an integer that can be cast
to a member. To use a rigid tendon formulation, set this to
``MusculotendonFormulation.RIGID_TENDON`` (or the integer value ``0``,
which will be cast to the enumeration member). There are four possible
formulations for an elastic tendon model. To use an explicit formulation
with the fiber length as the state, set this to
``MusculotendonFormulation.FIBER_LENGTH_EXPLICIT`` (or the integer value
``1``). To use an explicit formulation with the tendon force as the
state, set this to ``MusculotendonFormulation.TENDON_FORCE_EXPLICIT``
(or the integer value ``2``). To use an implicit formulation with the
fiber length as the state, set this to
``MusculotendonFormulation.FIBER_LENGTH_IMPLICIT`` (or the integer value
``3``). To use an implicit formulation with the tendon force as the
state, set this to ``MusculotendonFormulation.TENDON_FORCE_IMPLICIT``
(or the integer value ``4``). The default is
``MusculotendonFormulation.RIGID_TENDON``, which corresponds to a rigid
tendon formulation.
tendon_slack_length : Expr | None
The length of the tendon when the musculotendon is in its unloaded
state. In a rigid tendon model the tendon length is the tendon slack
length. In all musculotendon models, tendon slack length is used to
normalize tendon length to give
:math:`\tilde{l}^T = \frac{l^T}{l^T_{slack}}`.
peak_isometric_force : Expr | None
The maximum force that the muscle fiber can produce when it is
undergoing an isometric contraction (no lengthening velocity). In all
musculotendon models, peak isometric force is used to normalized tendon
and muscle fiber force to give
:math:`\tilde{F}^T = \frac{F^T}{F^M_{max}}`.
optimal_fiber_length : Expr | None
The muscle fiber length at which the muscle fibers produce no passive
force and their maximum active force. In all musculotendon models,
optimal fiber length is used to normalize muscle fiber length to give
:math:`\tilde{l}^M = \frac{l^M}{l^M_{opt}}`.
maximal_fiber_velocity : Expr | None
The fiber velocity at which, during muscle fiber shortening, the muscle
fibers are unable to produce any active force. In all musculotendon
models, maximal fiber velocity is used to normalize muscle fiber
extension velocity to give :math:`\tilde{v}^M = \frac{v^M}{v^M_{max}}`.
optimal_pennation_angle : Expr | None
The pennation angle when muscle fiber length equals the optimal fiber
length.
fiber_damping_coefficient : Expr | None
The coefficient of damping to be used in the damping element in the
muscle fiber model.
with_defaults : bool
Whether ``with_defaults`` alternate constructors should be used when
automatically constructing child classes. Default is ``False``.
"""
def __init__(
self,
name,
pathway,
activation_dynamics,
*,
musculotendon_dynamics=_DEFAULT_MUSCULOTENDON_FORMULATION,
tendon_slack_length=None,
peak_isometric_force=None,
optimal_fiber_length=None,
maximal_fiber_velocity=None,
optimal_pennation_angle=None,
fiber_damping_coefficient=None,
with_defaults=False,
):
self.name = name
# Supply a placeholder force to the super initializer, this will be
# replaced later
super().__init__(Symbol('F'), pathway)
# Activation dynamics
if not isinstance(activation_dynamics, ActivationBase):
msg = (
f'Can\'t set attribute `activation_dynamics` to '
f'{activation_dynamics} as it must be of type '
f'`ActivationBase`, not {type(activation_dynamics)}.'
)
raise TypeError(msg)
self._activation_dynamics = activation_dynamics
self._child_objects = (self._activation_dynamics, )
# Constants
if tendon_slack_length is not None:
self._l_T_slack = tendon_slack_length
else:
self._l_T_slack = Symbol(f'l_T_slack_{self.name}')
if peak_isometric_force is not None:
self._F_M_max = peak_isometric_force
else:
self._F_M_max = Symbol(f'F_M_max_{self.name}')
if optimal_fiber_length is not None:
self._l_M_opt = optimal_fiber_length
else:
self._l_M_opt = Symbol(f'l_M_opt_{self.name}')
if maximal_fiber_velocity is not None:
self._v_M_max = maximal_fiber_velocity
else:
self._v_M_max = Symbol(f'v_M_max_{self.name}')
if optimal_pennation_angle is not None:
self._alpha_opt = optimal_pennation_angle
else:
self._alpha_opt = Symbol(f'alpha_opt_{self.name}')
if fiber_damping_coefficient is not None:
self._beta = fiber_damping_coefficient
else:
self._beta = Symbol(f'beta_{self.name}')
# Musculotendon dynamics
self._with_defaults = with_defaults
if musculotendon_dynamics == MusculotendonFormulation.RIGID_TENDON:
self._rigid_tendon_musculotendon_dynamics()
elif musculotendon_dynamics == MusculotendonFormulation.FIBER_LENGTH_EXPLICIT:
self._fiber_length_explicit_musculotendon_dynamics()
elif musculotendon_dynamics == MusculotendonFormulation.TENDON_FORCE_EXPLICIT:
self._tendon_force_explicit_musculotendon_dynamics()
elif musculotendon_dynamics == MusculotendonFormulation.FIBER_LENGTH_IMPLICIT:
self._fiber_length_implicit_musculotendon_dynamics()
elif musculotendon_dynamics == MusculotendonFormulation.TENDON_FORCE_IMPLICIT:
self._tendon_force_implicit_musculotendon_dynamics()
else:
msg = (
f'Musculotendon dynamics {repr(musculotendon_dynamics)} '
f'passed to `musculotendon_dynamics` was of type '
f'{type(musculotendon_dynamics)}, must be '
f'{MusculotendonFormulation}.'
)
raise TypeError(msg)
self._musculotendon_dynamics = musculotendon_dynamics
# Must override the placeholder value in `self._force` now that the
# actual force has been calculated by
# `self._<MUSCULOTENDON FORMULATION>_musculotendon_dynamics`.
# Note that `self._force` assumes forces are expansile, musculotendon
# forces are contractile hence the minus sign preceding `self._F_T`
# (the tendon force).
self._force = -self._F_T
@classmethod
def with_defaults(
cls,
name,
pathway,
activation_dynamics,
*,
musculotendon_dynamics=_DEFAULT_MUSCULOTENDON_FORMULATION,
tendon_slack_length=None,
peak_isometric_force=None,
optimal_fiber_length=None,
maximal_fiber_velocity=Float('10.0'),
optimal_pennation_angle=Float('0.0'),
fiber_damping_coefficient=Float('0.1'),
):
r"""Recommended constructor that will use the published constants.
Explanation
===========
Returns a new instance of the musculotendon class using recommended
values for ``v_M_max``, ``alpha_opt``, and ``beta``. The values are:
:math:`v^M_{max} = 10`
:math:`\alpha_{opt} = 0`
:math:`\beta = \frac{1}{10}`
The musculotendon curves are also instantiated using the constants from
the original publication.
Parameters
==========
name : str
The name identifier associated with the musculotendon. This name is
used as a suffix when automatically generated symbols are
instantiated. It must be a string of nonzero length.
pathway : PathwayBase
The pathway that the actuator follows. This must be an instance of a
concrete subclass of ``PathwayBase``, e.g. ``LinearPathway``.
activation_dynamics : ActivationBase
The activation dynamics that will be modeled within the
musculotendon. This must be an instance of a concrete subclass of
``ActivationBase``, e.g. ``FirstOrderActivationDeGroote2016``.
musculotendon_dynamics : MusculotendonFormulation | int
The formulation of musculotendon dynamics that should be used
internally, i.e. rigid or elastic tendon model, the choice of
musculotendon state etc. This must be a member of the integer
enumeration ``MusculotendonFormulation`` or an integer that can be
cast to a member. To use a rigid tendon formulation, set this to
``MusculotendonFormulation.RIGID_TENDON`` (or the integer value
``0``, which will be cast to the enumeration member). There are four
possible formulations for an elastic tendon model. To use an
explicit formulation with the fiber length as the state, set this to
``MusculotendonFormulation.FIBER_LENGTH_EXPLICIT`` (or the integer
value ``1``). To use an explicit formulation with the tendon force
as the state, set this to
``MusculotendonFormulation.TENDON_FORCE_EXPLICIT`` (or the integer
value ``2``). To use an implicit formulation with the fiber length
as the state, set this to
``MusculotendonFormulation.FIBER_LENGTH_IMPLICIT`` (or the integer
value ``3``). To use an implicit formulation with the tendon force
as the state, set this to
``MusculotendonFormulation.TENDON_FORCE_IMPLICIT`` (or the integer
value ``4``). The default is
``MusculotendonFormulation.RIGID_TENDON``, which corresponds to a
rigid tendon formulation.
tendon_slack_length : Expr | None
The length of the tendon when the musculotendon is in its unloaded
state. In a rigid tendon model the tendon length is the tendon slack
length. In all musculotendon models, tendon slack length is used to
normalize tendon length to give
:math:`\tilde{l}^T = \frac{l^T}{l^T_{slack}}`.
peak_isometric_force : Expr | None
The maximum force that the muscle fiber can produce when it is
undergoing an isometric contraction (no lengthening velocity). In
all musculotendon models, peak isometric force is used to normalized
tendon and muscle fiber force to give
:math:`\tilde{F}^T = \frac{F^T}{F^M_{max}}`.
optimal_fiber_length : Expr | None
The muscle fiber length at which the muscle fibers produce no
passive force and their maximum active force. In all musculotendon
models, optimal fiber length is used to normalize muscle fiber
length to give :math:`\tilde{l}^M = \frac{l^M}{l^M_{opt}}`.
maximal_fiber_velocity : Expr | None
The fiber velocity at which, during muscle fiber shortening, the
muscle fibers are unable to produce any active force. In all
musculotendon models, maximal fiber velocity is used to normalize
muscle fiber extension velocity to give
:math:`\tilde{v}^M = \frac{v^M}{v^M_{max}}`.
optimal_pennation_angle : Expr | None
The pennation angle when muscle fiber length equals the optimal
fiber length.
fiber_damping_coefficient : Expr | None
The coefficient of damping to be used in the damping element in the
muscle fiber model.
"""
return cls(
name,
pathway,
activation_dynamics=activation_dynamics,
musculotendon_dynamics=musculotendon_dynamics,
tendon_slack_length=tendon_slack_length,
peak_isometric_force=peak_isometric_force,
optimal_fiber_length=optimal_fiber_length,
maximal_fiber_velocity=maximal_fiber_velocity,
optimal_pennation_angle=optimal_pennation_angle,
fiber_damping_coefficient=fiber_damping_coefficient,
with_defaults=True,
)
@abstractmethod
def curves(cls):
"""Return a ``CharacteristicCurveCollection`` of the curves related to
the specific model."""
pass
@property
def tendon_slack_length(self):
r"""Symbol or value corresponding to the tendon slack length constant.
Explanation
===========
The length of the tendon when the musculotendon is in its unloaded
state. In a rigid tendon model the tendon length is the tendon slack
length. In all musculotendon models, tendon slack length is used to
normalize tendon length to give
:math:`\tilde{l}^T = \frac{l^T}{l^T_{slack}}`.
The alias ``l_T_slack`` can also be used to access the same attribute.
"""
return self._l_T_slack
@property
def l_T_slack(self):
r"""Symbol or value corresponding to the tendon slack length constant.
Explanation
===========
The length of the tendon when the musculotendon is in its unloaded
state. In a rigid tendon model the tendon length is the tendon slack
length. In all musculotendon models, tendon slack length is used to
normalize tendon length to give
:math:`\tilde{l}^T = \frac{l^T}{l^T_{slack}}`.
The alias ``tendon_slack_length`` can also be used to access the same
attribute.
"""
return self._l_T_slack
@property
def peak_isometric_force(self):
r"""Symbol or value corresponding to the peak isometric force constant.
Explanation
===========
The maximum force that the muscle fiber can produce when it is
undergoing an isometric contraction (no lengthening velocity). In all
musculotendon models, peak isometric force is used to normalized tendon
and muscle fiber force to give
:math:`\tilde{F}^T = \frac{F^T}{F^M_{max}}`.
The alias ``F_M_max`` can also be used to access the same attribute.
"""
return self._F_M_max
@property
def F_M_max(self):
r"""Symbol or value corresponding to the peak isometric force constant.
Explanation
===========
The maximum force that the muscle fiber can produce when it is
undergoing an isometric contraction (no lengthening velocity). In all
musculotendon models, peak isometric force is used to normalized tendon
and muscle fiber force to give
:math:`\tilde{F}^T = \frac{F^T}{F^M_{max}}`.
The alias ``peak_isometric_force`` can also be used to access the same
attribute.
"""
return self._F_M_max
@property
def optimal_fiber_length(self):
r"""Symbol or value corresponding to the optimal fiber length constant.
Explanation
===========
The muscle fiber length at which the muscle fibers produce no passive
force and their maximum active force. In all musculotendon models,
optimal fiber length is used to normalize muscle fiber length to give
:math:`\tilde{l}^M = \frac{l^M}{l^M_{opt}}`.
The alias ``l_M_opt`` can also be used to access the same attribute.
"""
return self._l_M_opt
@property
def l_M_opt(self):
r"""Symbol or value corresponding to the optimal fiber length constant.
Explanation
===========
The muscle fiber length at which the muscle fibers produce no passive
force and their maximum active force. In all musculotendon models,
optimal fiber length is used to normalize muscle fiber length to give
:math:`\tilde{l}^M = \frac{l^M}{l^M_{opt}}`.
The alias ``optimal_fiber_length`` can also be used to access the same
attribute.
"""
return self._l_M_opt
@property
def maximal_fiber_velocity(self):
r"""Symbol or value corresponding to the maximal fiber velocity constant.
Explanation
===========
The fiber velocity at which, during muscle fiber shortening, the muscle
fibers are unable to produce any active force. In all musculotendon
models, maximal fiber velocity is used to normalize muscle fiber
extension velocity to give :math:`\tilde{v}^M = \frac{v^M}{v^M_{max}}`.
The alias ``v_M_max`` can also be used to access the same attribute.
"""
return self._v_M_max
@property
def v_M_max(self):
r"""Symbol or value corresponding to the maximal fiber velocity constant.
Explanation
===========
The fiber velocity at which, during muscle fiber shortening, the muscle
fibers are unable to produce any active force. In all musculotendon
models, maximal fiber velocity is used to normalize muscle fiber
extension velocity to give :math:`\tilde{v}^M = \frac{v^M}{v^M_{max}}`.
The alias ``maximal_fiber_velocity`` can also be used to access the same
attribute.
"""
return self._v_M_max
@property
def optimal_pennation_angle(self):
"""Symbol or value corresponding to the optimal pennation angle
constant.
Explanation
===========
The pennation angle when muscle fiber length equals the optimal fiber
length.
The alias ``alpha_opt`` can also be used to access the same attribute.
"""
return self._alpha_opt
@property
def alpha_opt(self):
"""Symbol or value corresponding to the optimal pennation angle
constant.
Explanation
===========
The pennation angle when muscle fiber length equals the optimal fiber
length.
The alias ``optimal_pennation_angle`` can also be used to access the
same attribute.
"""
return self._alpha_opt
@property
def fiber_damping_coefficient(self):
"""Symbol or value corresponding to the fiber damping coefficient
constant.
Explanation
===========
The coefficient of damping to be used in the damping element in the
muscle fiber model.
The alias ``beta`` can also be used to access the same attribute.
"""
return self._beta
@property
def beta(self):
"""Symbol or value corresponding to the fiber damping coefficient
constant.
Explanation
===========
The coefficient of damping to be used in the damping element in the
muscle fiber model.
The alias ``fiber_damping_coefficient`` can also be used to access the
same attribute.
"""
return self._beta
@property
def activation_dynamics(self):
"""Activation dynamics model governing this musculotendon's activation.
Explanation
===========
Returns the instance of a subclass of ``ActivationBase`` that governs
the relationship between excitation and activation that is used to
represent the activation dynamics of this musculotendon.
"""
return self._activation_dynamics
@property
def excitation(self):
"""Dynamic symbol representing excitation.
Explanation
===========
The alias ``e`` can also be used to access the same attribute.
"""
return self._activation_dynamics._e
@property
def e(self):
"""Dynamic symbol representing excitation.
Explanation
===========
The alias ``excitation`` can also be used to access the same attribute.
"""
return self._activation_dynamics._e
@property
def activation(self):
"""Dynamic symbol representing activation.
Explanation
===========
The alias ``a`` can also be used to access the same attribute.
"""
return self._activation_dynamics._a
@property
def a(self):
"""Dynamic symbol representing activation.
Explanation
===========
The alias ``activation`` can also be used to access the same attribute.
"""
return self._activation_dynamics._a
@property
def musculotendon_dynamics(self):
"""The choice of rigid or type of elastic tendon musculotendon dynamics.
Explanation
===========
The formulation of musculotendon dynamics that should be used
internally, i.e. rigid or elastic tendon model, the choice of
musculotendon state etc. This must be a member of the integer
enumeration ``MusculotendonFormulation`` or an integer that can be cast
to a member. To use a rigid tendon formulation, set this to
``MusculotendonFormulation.RIGID_TENDON`` (or the integer value ``0``,
which will be cast to the enumeration member). There are four possible
formulations for an elastic tendon model. To use an explicit formulation
with the fiber length as the state, set this to
``MusculotendonFormulation.FIBER_LENGTH_EXPLICIT`` (or the integer value
``1``). To use an explicit formulation with the tendon force as the
state, set this to ``MusculotendonFormulation.TENDON_FORCE_EXPLICIT``
(or the integer value ``2``). To use an implicit formulation with the
fiber length as the state, set this to
``MusculotendonFormulation.FIBER_LENGTH_IMPLICIT`` (or the integer value
``3``). To use an implicit formulation with the tendon force as the
state, set this to ``MusculotendonFormulation.TENDON_FORCE_IMPLICIT``
(or the integer value ``4``). The default is
``MusculotendonFormulation.RIGID_TENDON``, which corresponds to a rigid
tendon formulation.
"""
return self._musculotendon_dynamics
def _rigid_tendon_musculotendon_dynamics(self):
"""Rigid tendon musculotendon."""
self._l_MT = self.pathway.length
self._v_MT = self.pathway.extension_velocity
self._l_T = self._l_T_slack
self._l_T_tilde = Integer(1)
self._l_M = sqrt((self._l_MT - self._l_T)**2 + (self._l_M_opt*sin(self._alpha_opt))**2)
self._l_M_tilde = self._l_M/self._l_M_opt
self._v_M = self._v_MT*(self._l_MT - self._l_T_slack)/self._l_M
self._v_M_tilde = self._v_M/self._v_M_max
if self._with_defaults:
self._fl_T = self.curves.tendon_force_length.with_defaults(self._l_T_tilde)
self._fl_M_pas = self.curves.fiber_force_length_passive.with_defaults(self._l_M_tilde)
self._fl_M_act = self.curves.fiber_force_length_active.with_defaults(self._l_M_tilde)
self._fv_M = self.curves.fiber_force_velocity.with_defaults(self._v_M_tilde)
else:
fl_T_constants = symbols(f'c_0:4_fl_T_{self.name}')
self._fl_T = self.curves.tendon_force_length(self._l_T_tilde, *fl_T_constants)
fl_M_pas_constants = symbols(f'c_0:2_fl_M_pas_{self.name}')
self._fl_M_pas = self.curves.fiber_force_length_passive(self._l_M_tilde, *fl_M_pas_constants)
fl_M_act_constants = symbols(f'c_0:12_fl_M_act_{self.name}')
self._fl_M_act = self.curves.fiber_force_length_active(self._l_M_tilde, *fl_M_act_constants)
fv_M_constants = symbols(f'c_0:4_fv_M_{self.name}')
self._fv_M = self.curves.fiber_force_velocity(self._v_M_tilde, *fv_M_constants)
self._F_M_tilde = self.a*self._fl_M_act*self._fv_M + self._fl_M_pas + self._beta*self._v_M_tilde
self._F_T_tilde = self._F_M_tilde
self._F_M = self._F_M_tilde*self._F_M_max
self._cos_alpha = cos(self._alpha_opt)
self._F_T = self._F_M*self._cos_alpha
# Containers
self._state_vars = zeros(0, 1)
self._input_vars = zeros(0, 1)
self._state_eqns = zeros(0, 1)
self._curve_constants = Matrix(
fl_T_constants
+ fl_M_pas_constants
+ fl_M_act_constants
+ fv_M_constants
) if not self._with_defaults else zeros(0, 1)
def _fiber_length_explicit_musculotendon_dynamics(self):
"""Elastic tendon musculotendon using `l_M_tilde` as a state."""
self._l_M_tilde = dynamicsymbols(f'l_M_tilde_{self.name}')
self._l_MT = self.pathway.length
self._v_MT = self.pathway.extension_velocity
self._l_M = self._l_M_tilde*self._l_M_opt
self._l_T = self._l_MT - sqrt(self._l_M**2 - (self._l_M_opt*sin(self._alpha_opt))**2)
self._l_T_tilde = self._l_T/self._l_T_slack
self._cos_alpha = (self._l_MT - self._l_T)/self._l_M
if self._with_defaults:
self._fl_T = self.curves.tendon_force_length.with_defaults(self._l_T_tilde)
self._fl_M_pas = self.curves.fiber_force_length_passive.with_defaults(self._l_M_tilde)
self._fl_M_act = self.curves.fiber_force_length_active.with_defaults(self._l_M_tilde)
else:
fl_T_constants = symbols(f'c_0:4_fl_T_{self.name}')
self._fl_T = self.curves.tendon_force_length(self._l_T_tilde, *fl_T_constants)
fl_M_pas_constants = symbols(f'c_0:2_fl_M_pas_{self.name}')
self._fl_M_pas = self.curves.fiber_force_length_passive(self._l_M_tilde, *fl_M_pas_constants)
fl_M_act_constants = symbols(f'c_0:12_fl_M_act_{self.name}')
self._fl_M_act = self.curves.fiber_force_length_active(self._l_M_tilde, *fl_M_act_constants)
self._F_T_tilde = self._fl_T
self._F_T = self._F_T_tilde*self._F_M_max
self._F_M = self._F_T/self._cos_alpha
self._F_M_tilde = self._F_M/self._F_M_max
self._fv_M = (self._F_M_tilde - self._fl_M_pas)/(self.a*self._fl_M_act)
if self._with_defaults:
self._v_M_tilde = self.curves.fiber_force_velocity_inverse.with_defaults(self._fv_M)
else:
fv_M_constants = symbols(f'c_0:4_fv_M_{self.name}')
self._v_M_tilde = self.curves.fiber_force_velocity_inverse(self._fv_M, *fv_M_constants)
self._dl_M_tilde_dt = (self._v_M_max/self._l_M_opt)*self._v_M_tilde
self._state_vars = Matrix([self._l_M_tilde])
self._input_vars = zeros(0, 1)
self._state_eqns = Matrix([self._dl_M_tilde_dt])
self._curve_constants = Matrix(
fl_T_constants
+ fl_M_pas_constants
+ fl_M_act_constants
+ fv_M_constants
) if not self._with_defaults else zeros(0, 1)
def _tendon_force_explicit_musculotendon_dynamics(self):
"""Elastic tendon musculotendon using `F_T_tilde` as a state."""
self._F_T_tilde = dynamicsymbols(f'F_T_tilde_{self.name}')
self._l_MT = self.pathway.length
self._v_MT = self.pathway.extension_velocity
self._fl_T = self._F_T_tilde
if self._with_defaults:
self._fl_T_inv = self.curves.tendon_force_length_inverse.with_defaults(self._fl_T)
else:
fl_T_constants = symbols(f'c_0:4_fl_T_{self.name}')
self._fl_T_inv = self.curves.tendon_force_length_inverse(self._fl_T, *fl_T_constants)
self._l_T_tilde = self._fl_T_inv
self._l_T = self._l_T_tilde*self._l_T_slack
self._l_M = sqrt((self._l_MT - self._l_T)**2 + (self._l_M_opt*sin(self._alpha_opt))**2)
self._l_M_tilde = self._l_M/self._l_M_opt
if self._with_defaults:
self._fl_M_pas = self.curves.fiber_force_length_passive.with_defaults(self._l_M_tilde)
self._fl_M_act = self.curves.fiber_force_length_active.with_defaults(self._l_M_tilde)
else:
fl_M_pas_constants = symbols(f'c_0:2_fl_M_pas_{self.name}')
self._fl_M_pas = self.curves.fiber_force_length_passive(self._l_M_tilde, *fl_M_pas_constants)
fl_M_act_constants = symbols(f'c_0:12_fl_M_act_{self.name}')
self._fl_M_act = self.curves.fiber_force_length_active(self._l_M_tilde, *fl_M_act_constants)
self._cos_alpha = (self._l_MT - self._l_T)/self._l_M
self._F_T = self._F_T_tilde*self._F_M_max
self._F_M = self._F_T/self._cos_alpha
self._F_M_tilde = self._F_M/self._F_M_max
self._fv_M = (self._F_M_tilde - self._fl_M_pas)/(self.a*self._fl_M_act)
if self._with_defaults:
self._fv_M_inv = self.curves.fiber_force_velocity_inverse.with_defaults(self._fv_M)
else:
fv_M_constants = symbols(f'c_0:4_fv_M_{self.name}')
self._fv_M_inv = self.curves.fiber_force_velocity_inverse(self._fv_M, *fv_M_constants)
self._v_M_tilde = self._fv_M_inv
self._v_M = self._v_M_tilde*self._v_M_max
self._v_T = self._v_MT - (self._v_M/self._cos_alpha)
self._v_T_tilde = self._v_T/self._l_T_slack
if self._with_defaults:
self._fl_T = self.curves.tendon_force_length.with_defaults(self._l_T_tilde)
else:
self._fl_T = self.curves.tendon_force_length(self._l_T_tilde, *fl_T_constants)
self._dF_T_tilde_dt = self._fl_T.diff(dynamicsymbols._t).subs({self._l_T_tilde.diff(dynamicsymbols._t): self._v_T_tilde})
self._state_vars = Matrix([self._F_T_tilde])
self._input_vars = zeros(0, 1)
self._state_eqns = Matrix([self._dF_T_tilde_dt])
self._curve_constants = Matrix(
fl_T_constants
+ fl_M_pas_constants
+ fl_M_act_constants
+ fv_M_constants
) if not self._with_defaults else zeros(0, 1)
def _fiber_length_implicit_musculotendon_dynamics(self):
raise NotImplementedError
def _tendon_force_implicit_musculotendon_dynamics(self):
raise NotImplementedError
@property
def state_vars(self):
"""Ordered column matrix of functions of time that represent the state
variables.
Explanation
===========
The alias ``x`` can also be used to access the same attribute.
"""
state_vars = [self._state_vars]
for child in self._child_objects:
state_vars.append(child.state_vars)
return Matrix.vstack(*state_vars)
@property
def x(self):
"""Ordered column matrix of functions of time that represent the state
variables.
Explanation
===========
The alias ``state_vars`` can also be used to access the same attribute.
"""
state_vars = [self._state_vars]
for child in self._child_objects:
state_vars.append(child.state_vars)
return Matrix.vstack(*state_vars)
@property
def input_vars(self):
"""Ordered column matrix of functions of time that represent the input
variables.
Explanation
===========
The alias ``r`` can also be used to access the same attribute.
"""
input_vars = [self._input_vars]
for child in self._child_objects:
input_vars.append(child.input_vars)
return Matrix.vstack(*input_vars)
@property
def r(self):
"""Ordered column matrix of functions of time that represent the input
variables.
Explanation
===========
The alias ``input_vars`` can also be used to access the same attribute.
"""
input_vars = [self._input_vars]
for child in self._child_objects:
input_vars.append(child.input_vars)
return Matrix.vstack(*input_vars)
@property
def constants(self):
"""Ordered column matrix of non-time varying symbols present in ``M``
and ``F``.
Explanation
===========
Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
has been used instead of ``Symbol`` for a constant then that attribute
will not be included in the matrix returned by this property. This is
because the primary use of this property attribute is to provide an
ordered sequence of the still-free symbols that require numeric values
during code generation.
The alias ``p`` can also be used to access the same attribute.
"""
musculotendon_constants = [
self._l_T_slack,
self._F_M_max,
self._l_M_opt,
self._v_M_max,
self._alpha_opt,
self._beta,
]
musculotendon_constants = [
c for c in musculotendon_constants if not c.is_number
]
constants = [
Matrix(musculotendon_constants)
if musculotendon_constants
else zeros(0, 1)
]
for child in self._child_objects:
constants.append(child.constants)
constants.append(self._curve_constants)
return Matrix.vstack(*constants)
@property
def p(self):
"""Ordered column matrix of non-time varying symbols present in ``M``
and ``F``.
Explanation
===========
Only symbolic constants are returned. If a numeric type (e.g. ``Float``)
has been used instead of ``Symbol`` for a constant then that attribute
will not be included in the matrix returned by this property. This is
because the primary use of this property attribute is to provide an
ordered sequence of the still-free symbols that require numeric values
during code generation.
The alias ``constants`` can also be used to access the same attribute.
"""
musculotendon_constants = [
self._l_T_slack,
self._F_M_max,
self._l_M_opt,
self._v_M_max,
self._alpha_opt,
self._beta,
]
musculotendon_constants = [
c for c in musculotendon_constants if not c.is_number
]
constants = [
Matrix(musculotendon_constants)
if musculotendon_constants
else zeros(0, 1)
]
for child in self._child_objects:
constants.append(child.constants)
constants.append(self._curve_constants)
return Matrix.vstack(*constants)
@property
def M(self):
"""Ordered square matrix of coefficients on the LHS of ``M x' = F``.
Explanation
===========
The square matrix that forms part of the LHS of the linear system of
ordinary differential equations governing the activation dynamics:
``M(x, r, t, p) x' = F(x, r, t, p)``.
As zeroth-order activation dynamics have no state variables, this
linear system has dimension 0 and therefore ``M`` is an empty square
``Matrix`` with shape (0, 0).
"""
M = [eye(len(self._state_vars))]
for child in self._child_objects:
M.append(child.M)
return diag(*M)
@property
def F(self):
"""Ordered column matrix of equations on the RHS of ``M x' = F``.
Explanation
===========
The column matrix that forms the RHS of the linear system of ordinary
differential equations governing the activation dynamics:
``M(x, r, t, p) x' = F(x, r, t, p)``.
As zeroth-order activation dynamics have no state variables, this
linear system has dimension 0 and therefore ``F`` is an empty column
``Matrix`` with shape (0, 1).
"""
F = [self._state_eqns]
for child in self._child_objects:
F.append(child.F)
return Matrix.vstack(*F)
def rhs(self):
"""Ordered column matrix of equations for the solution of ``M x' = F``.
Explanation
===========
The solution to the linear system of ordinary differential equations
governing the activation dynamics:
``M(x, r, t, p) x' = F(x, r, t, p)``.
As zeroth-order activation dynamics have no state variables, this
linear has dimension 0 and therefore this method returns an empty
column ``Matrix`` with shape (0, 1).
"""
is_explicit = (
MusculotendonFormulation.FIBER_LENGTH_EXPLICIT,
MusculotendonFormulation.TENDON_FORCE_EXPLICIT,
)
if self.musculotendon_dynamics is MusculotendonFormulation.RIGID_TENDON:
child_rhs = [child.rhs() for child in self._child_objects]
return Matrix.vstack(*child_rhs)
elif self.musculotendon_dynamics in is_explicit:
rhs = self._state_eqns
child_rhs = [child.rhs() for child in self._child_objects]
return Matrix.vstack(rhs, *child_rhs)
return self.M.solve(self.F)
def __repr__(self):
"""Returns a string representation to reinstantiate the model."""
return (
f'{self.__class__.__name__}({self.name!r}, '
f'pathway={self.pathway!r}, '
f'activation_dynamics={self.activation_dynamics!r}, '
f'musculotendon_dynamics={self.musculotendon_dynamics}, '
f'tendon_slack_length={self._l_T_slack!r}, '
f'peak_isometric_force={self._F_M_max!r}, '
f'optimal_fiber_length={self._l_M_opt!r}, '
f'maximal_fiber_velocity={self._v_M_max!r}, '
f'optimal_pennation_angle={self._alpha_opt!r}, '
f'fiber_damping_coefficient={self._beta!r})'
)
def __str__(self):
"""Returns a string representation of the expression for musculotendon
force."""
return str(self.force)
| MusculotendonBase |
python | pypa__setuptools | setuptools/_distutils/errors.py | {
"start": 1175,
"end": 1297
} | class ____(DistutilsError):
"""The option table provided to 'fancy_getopt()' is bogus."""
pass
| DistutilsGetoptError |
python | huggingface__transformers | src/transformers/models/modernbert/modeling_modernbert.py | {
"start": 41703,
"end": 42376
} | class ____(nn.Module):
def __init__(self, config: ModernBertConfig):
super().__init__()
self.config = config
self.dense = nn.Linear(config.hidden_size, config.hidden_size, config.classifier_bias)
self.act = ACT2FN[config.classifier_activation]
self.norm = nn.LayerNorm(config.hidden_size, eps=config.norm_eps, bias=config.norm_bias)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
return self.norm(self.act(self.dense(hidden_states)))
@auto_docstring(
custom_intro="""
The ModernBert Model with a decoder head on top that is used for masked language modeling.
"""
)
| ModernBertPredictionHead |
python | openai__openai-python | src/openai/types/responses/response_computer_tool_call.py | {
"start": 1478,
"end": 1888
} | class ____(BaseModel):
path: List[ActionDragPath]
"""An array of coordinates representing the path of the drag action.
Coordinates will appear as an array of objects, eg
```
[
{ x: 100, y: 200 },
{ x: 200, y: 300 }
]
```
"""
type: Literal["drag"]
"""Specifies the event type.
For a drag action, this property is always set to `drag`.
"""
| ActionDrag |
python | conda__conda | conda/common/configuration.py | {
"start": 2749,
"end": 3011
} | class ____(ConfigurationError):
def __init__(self, path, message_addition="", **kwargs):
message = "Unable to load configuration file.\n path: %(path)s\n"
super().__init__(message + message_addition, path=path, **kwargs)
| ConfigurationLoadError |
python | numpy__numpy | numpy/fft/tests/test_helper.py | {
"start": 5562,
"end": 5929
} | class ____:
def test_definition(self):
x = [0, 1, 2, 3, 4]
assert_array_almost_equal(9 * fft.rfftfreq(9), x)
assert_array_almost_equal(9 * pi * fft.rfftfreq(9, pi), x)
x = [0, 1, 2, 3, 4, 5]
assert_array_almost_equal(10 * fft.rfftfreq(10), x)
assert_array_almost_equal(10 * pi * fft.rfftfreq(10, pi), x)
| TestRFFTFreq |
python | doocs__leetcode | solution/0800-0899/0898.Bitwise ORs of Subarrays/Solution.py | {
"start": 0,
"end": 219
} | class ____:
def subarrayBitwiseORs(self, arr: List[int]) -> int:
ans = set()
s = set()
for x in arr:
s = {x | y for y in s} | {x}
ans |= s
return len(ans)
| Solution |
python | sphinx-doc__sphinx | sphinx/builders/latex/nodes.py | {
"start": 367,
"end": 526
} | class ____(
nodes.General, nodes.BackLinkable, nodes.Element, nodes.Labeled, nodes.Targetable
):
r"""A node represents ``\footnotetext``."""
| footnotetext |
python | getsentry__sentry | tests/sentry/middleware/test_superuser.py | {
"start": 310,
"end": 3269
} | class ____(TestCase):
middleware = cached_property(SuperuserMiddleware)
def _create_request(self, is_superuser: bool):
request = RequestFactory().get("/")
request.user = self.user
request.session = self.session
setattr(request, "organization", self.organization)
if is_superuser:
request.superuser = mock_su = MagicMock()
mock_su.is_active = True
mock_su.token = "test_token"
return request
@patch("sentry.middleware.superuser.logger")
def test_su_response_not_authorized(self, mock_logger: MagicMock) -> None:
request = self._create_request(is_superuser=False)
response = MagicMock()
self.middleware.process_response(request, response)
mock_logger.info.assert_not_called()
@patch("sentry.middleware.superuser.logger")
def test_su_response_logged_when_authorized(self, mock_logger: MagicMock) -> None:
request = self._create_request(is_superuser=True)
request.user.email = "admin@sentry.io"
response = MagicMock()
self.middleware.process_response(request, response)
mock_logger.info.assert_called_once_with(
"superuser.superuser_access",
extra={
"superuser_token_id": "test_token",
"user_id": self.user.id,
"user_email": None,
"su_org_accessed": self.organization.slug,
},
)
@override_settings(SUPERUSER_STAFF_EMAIL_SUFFIX="@sentry.io")
@patch("sentry.middleware.superuser.logger")
def test_su_response_logged_with_email(self, mock_logger: MagicMock) -> None:
request = self._create_request(is_superuser=True)
request.user.email = "admin@sentry.io"
response = MagicMock()
self.middleware.process_response(request, response)
mock_logger.info.assert_called_once_with(
"superuser.superuser_access",
extra={
"superuser_token_id": "test_token",
"user_id": self.user.id,
"user_email": "admin@sentry.io",
"su_org_accessed": self.organization.slug,
},
)
@override_settings(SUPERUSER_STAFF_EMAIL_SUFFIX="@sentry.io")
@patch("sentry.middleware.superuser.logger")
def test_su_response_email_not_logged_if_not_staff(self, mock_logger: MagicMock) -> None:
request = self._create_request(is_superuser=True)
request.user.email = "personal@example.com"
response = MagicMock()
self.middleware.process_response(request, response)
mock_logger.info.assert_called_once_with(
"superuser.superuser_access",
extra={
"superuser_token_id": "test_token",
"user_id": self.user.id,
"user_email": None,
"su_org_accessed": self.organization.slug,
},
)
| SuperuserMiddlewareTestCase |
python | huggingface__transformers | src/transformers/models/encoder_decoder/configuration_encoder_decoder.py | {
"start": 824,
"end": 4596
} | class ____(PreTrainedConfig):
r"""
[`EncoderDecoderConfig`] is the configuration class to store the configuration of a [`EncoderDecoderModel`]. It is
used to instantiate an Encoder Decoder model according to the specified arguments, defining the encoder and decoder
configs.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
kwargs (*optional*):
Dictionary of keyword arguments. Notably:
- **encoder** ([`PreTrainedConfig`], *optional*) -- An instance of a configuration object that defines
the encoder config.
- **decoder** ([`PreTrainedConfig`], *optional*) -- An instance of a configuration object that defines
the decoder config.
Examples:
```python
>>> from transformers import BertConfig, EncoderDecoderConfig, EncoderDecoderModel
>>> # Initializing a BERT google-bert/bert-base-uncased style configuration
>>> config_encoder = BertConfig()
>>> config_decoder = BertConfig()
>>> config = EncoderDecoderConfig.from_encoder_decoder_configs(config_encoder, config_decoder)
>>> # Initializing a Bert2Bert model (with random weights) from the google-bert/bert-base-uncased style configurations
>>> model = EncoderDecoderModel(config=config)
>>> # Accessing the model configuration
>>> config_encoder = model.config.encoder
>>> config_decoder = model.config.decoder
>>> # set decoder config to causal lm
>>> config_decoder.is_decoder = True
>>> config_decoder.add_cross_attention = True
>>> # Saving the model, including its configuration
>>> model.save_pretrained("my-model")
>>> # loading model and config from pretrained folder
>>> encoder_decoder_config = EncoderDecoderConfig.from_pretrained("my-model")
>>> model = EncoderDecoderModel.from_pretrained("my-model", config=encoder_decoder_config)
```"""
model_type = "encoder-decoder"
sub_configs = {"encoder": AutoConfig, "decoder": AutoConfig}
has_no_defaults_at_init = True
def __init__(self, **kwargs):
super().__init__(**kwargs)
if "encoder" not in kwargs or "decoder" not in kwargs:
raise ValueError(
f"A configuration of type {self.model_type} cannot be instantiated because "
f"both `encoder` and `decoder` sub-configurations were not passed, only {kwargs}"
)
encoder_config = kwargs.pop("encoder")
encoder_model_type = encoder_config.pop("model_type")
decoder_config = kwargs.pop("decoder")
decoder_model_type = decoder_config.pop("model_type")
self.encoder = AutoConfig.for_model(encoder_model_type, **encoder_config)
self.decoder = AutoConfig.for_model(decoder_model_type, **decoder_config)
self.is_encoder_decoder = True
@classmethod
def from_encoder_decoder_configs(
cls, encoder_config: PreTrainedConfig, decoder_config: PreTrainedConfig, **kwargs
) -> PreTrainedConfig:
r"""
Instantiate a [`EncoderDecoderConfig`] (or a derived class) from a pre-trained encoder model configuration and
decoder model configuration.
Returns:
[`EncoderDecoderConfig`]: An instance of a configuration object
"""
logger.info("Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config")
decoder_config.is_decoder = True
decoder_config.add_cross_attention = True
return cls(encoder=encoder_config.to_dict(), decoder=decoder_config.to_dict(), **kwargs)
__all__ = ["EncoderDecoderConfig"]
| EncoderDecoderConfig |
python | getsentry__sentry | tests/sentry/integrations/gitlab/test_integration.py | {
"start": 21420,
"end": 26848
} | class ____(IntegrationTestCase):
provider = GitlabIntegrationProvider
config = {
# Trailing slash is intentional to ensure that valid
# URLs are generated even if the user inputs a trailing /
"url": "https://gitlab.example.com/",
"name": "Test App",
"group": "",
"verify_ssl": True,
"client_id": "client_id",
"client_secret": "client_secret",
"include_subgroups": True,
}
def setUp(self) -> None:
super().setUp()
self.init_path_without_guide = f"{self.init_path}?completed_installation_guide"
def assert_setup_flow(self, user_id="user_id_1"):
resp = self.client.get(self.init_path)
assert resp.status_code == 200
self.assertContains(resp, "you will need to create a Sentry app in your GitLab instance")
resp = self.client.get(self.init_path_without_guide)
assert resp.status_code == 200
resp = self.client.post(self.init_path_without_guide, data=self.config)
assert resp.status_code == 302
redirect = urlparse(resp["Location"])
assert redirect.scheme == "https"
assert redirect.netloc == "gitlab.example.com"
assert redirect.path == "/oauth/authorize"
params = parse_qs(redirect.query)
assert params["state"]
assert params["redirect_uri"] == ["http://testserver/extensions/gitlab/setup/"]
assert params["response_type"] == ["code"]
assert params["client_id"] == ["client_id"]
# once we've asserted on it, switch to a singular values to make life easier
authorize_params = {k: v[0] for k, v in params.items()}
access_token = "xxxxx-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx"
responses.add(
responses.POST,
"https://gitlab.example.com/oauth/token",
json={"access_token": access_token},
)
responses.add(responses.GET, "https://gitlab.example.com/api/v4/user", json={"id": user_id})
responses.add(
responses.POST, "https://gitlab.example.com/api/v4/hooks", json={"id": "webhook-id-1"}
)
resp = self.client.get(
"{}?{}".format(
self.setup_path,
urlencode({"code": "oauth-code", "state": authorize_params["state"]}),
)
)
mock_access_token_request = responses.calls[0].request
req_params = parse_qs(mock_access_token_request.body)
assert req_params["grant_type"] == ["authorization_code"]
assert req_params["code"] == ["oauth-code"]
assert req_params["redirect_uri"] == ["http://testserver/extensions/gitlab/setup/"]
assert req_params["client_id"] == ["client_id"]
assert req_params["client_secret"] == ["client_secret"]
assert resp.status_code == 302
assert (
resp["Location"]
== f"http://testserver/settings/{self.organization.slug}/integrations/gitlab/"
)
@responses.activate
@patch("sentry.integrations.gitlab.integration.sha1_text")
def test_basic_flow(self, mock_sha: MagicMock) -> None:
sha = Mock()
sha.hexdigest.return_value = "secret-token"
mock_sha.return_value = sha
self.assert_setup_flow()
integration = Integration.objects.get(provider=self.provider.key)
assert integration.external_id == "gitlab.example.com:_instance_"
assert integration.name == "gitlab.example.com"
assert integration.metadata == {
"instance": "gitlab.example.com",
"scopes": ["api"],
"icon": None,
"domain_name": "gitlab.example.com",
"verify_ssl": True,
"base_url": "https://gitlab.example.com",
"webhook_secret": "secret-token",
"group_id": None,
"include_subgroups": False,
}
oi = OrganizationIntegration.objects.get(
integration=integration, organization_id=self.organization.id
)
assert oi.config == {}
idp = IdentityProvider.objects.get(type="gitlab")
identity = Identity.objects.get(
idp=idp, user=self.user, external_id="gitlab.example.com:user_id_1"
)
assert identity.status == IdentityStatus.VALID
assert identity.data == {
"access_token": "xxxxx-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx",
"client_id": "client_id",
"client_secret": "client_secret",
}
@responses.activate
def test_get_group_id(self) -> None:
self.assert_setup_flow()
integration = Integration.objects.get(provider=self.provider.key)
installation = get_installation_of_type(
GitlabIntegration, integration, self.organization.id
)
assert installation.get_group_id() is None
def assert_proxy_request(request, is_proxy=True):
assert (PROXY_BASE_PATH in request.url) == is_proxy
assert (PROXY_OI_HEADER in request.headers) == is_proxy
assert (PROXY_SIGNATURE_HEADER in request.headers) == is_proxy
# The following Gitlab headers don't appear in proxied requests
assert ("Authorization" in request.headers) != is_proxy
if is_proxy:
assert request.headers[PROXY_OI_HEADER] is not None
@override_settings(
SENTRY_SUBNET_SECRET="hush-hush-im-invisible",
SENTRY_CONTROL_ADDRESS="http://controlserver",
)
| GitlabIntegrationInstanceTest |
python | walkccc__LeetCode | solutions/691. Stickers to Spell Word/691.py | {
"start": 0,
"end": 783
} | class ____:
def minStickers(self, stickers: list[str], target: str) -> int:
maxMask = 1 << len(target)
# dp[i] := the minimum number of stickers to spell out i, where i is the
# bit mask of target
dp = [math.inf] * maxMask
dp[0] = 0
for mask in range(maxMask):
if dp[mask] == math.inf:
continue
# Try to expand from `mask` by using each sticker.
for sticker in stickers:
superMask = mask
for c in sticker:
for i, t in enumerate(target):
# Try to apply it on a missing letter.
if c == t and not (superMask >> i & 1):
superMask |= 1 << i
break
dp[superMask] = min(dp[superMask], dp[mask] + 1)
return -1 if dp[-1] == math.inf else dp[-1]
| Solution |
python | getsentry__sentry | src/sentry/core/endpoints/project_details.py | {
"start": 4113,
"end": 5567
} | class ____(serializers.Serializer):
isBookmarked = serializers.BooleanField(
help_text="Enables starring the project within the projects tab. Can be updated with **`project:read`** permission.",
required=False,
)
autofixAutomationTuning = serializers.ChoiceField(
choices=[item.value for item in AutofixAutomationTuningSettings],
required=False,
)
seerScannerAutomation = serializers.BooleanField(required=False)
@extend_schema_serializer(
exclude_fields=[
"options",
"team",
"digestsMinDelay",
"digestsMaxDelay",
"securityToken",
"securityTokenHeader",
"verifySSL",
"defaultEnvironment",
"dataScrubber",
"dataScrubberDefaults",
"sensitiveFields",
"safeFields",
"storeCrashReports",
"relayPiiConfig",
"builtinSymbolSources",
"symbolSources",
"scrubIPAddresses",
"groupingConfig",
"groupingEnhancements",
"derivedGroupingEnhancements",
"fingerprintingRules",
"secondaryGroupingConfig",
"secondaryGroupingExpiry",
"scrapeJavaScript",
"allowedDomains",
"copy_from_project",
"targetSampleRate",
"dynamicSamplingBiases",
"tempestFetchScreenshots",
"autofixAutomationTuning",
"seerScannerAutomation",
"debugFilesRole",
]
)
| ProjectMemberSerializer |
python | huggingface__transformers | tests/models/wav2vec2/test_tokenization_wav2vec2.py | {
"start": 14834,
"end": 41298
} | class ____(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "facebook/wav2vec2-base-960h"
tokenizer_class = Wav2Vec2CTCTokenizer
test_rust_tokenizer = False
def test_pretokenized_inputs(self):
# Skip this test for Wav2Vec2 - it's a character-level tokenizer where spaces
# become word delimiters, so pretokenized inputs can't match string tokenization
self.skipTest("Wav2Vec2 is a character-level tokenizer with word delimiters")
@classmethod
def setUpClass(cls):
super().setUpClass()
vocab = "<pad> <s> </s> <unk> | E T A O N I H S R D L U M W C F G Y P B V K ' X J Q Z".split(" ")
vocab_tokens = dict(zip(vocab, range(len(vocab))))
cls.special_tokens_map = {"pad_token": "<pad>", "unk_token": "<unk>", "bos_token": "<s>", "eos_token": "</s>"}
cls.tmpdirname = tempfile.mkdtemp()
cls.vocab_file = os.path.join(cls.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
with open(cls.vocab_file, "w", encoding="utf-8") as fp:
fp.write(json.dumps(vocab_tokens) + "\n")
@classmethod
def get_tokenizer(cls, pretrained_name=None, **kwargs):
# Update with special_tokens_map first, then user kwargs take precedence
merged_kwargs = cls.special_tokens_map.copy()
merged_kwargs.update(kwargs)
pretrained_name = pretrained_name or cls.tmpdirname
return Wav2Vec2CTCTokenizer.from_pretrained(pretrained_name, **merged_kwargs)
def test_word_delimiter_round_trip_without_config(self):
vocab_path = get_tests_dir("fixtures/vocab.json")
tokenizer = self.tokenizer_class(
vocab_path,
bos_token="<s>",
eos_token="</s>",
pad_token="<pad>",
unk_token="<unk>",
word_delimiter_token="|",
)
before_vocab = tokenizer.get_vocab()
self.assertIn("|", before_vocab)
with tempfile.TemporaryDirectory() as tmp_dir:
tokenizer.save_pretrained(tmp_dir)
reloaded = self.tokenizer_class.from_pretrained(tmp_dir)
self.assertDictEqual(before_vocab, reloaded.get_vocab())
def test_tokenizer_add_token_chars(self):
tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-base-960h")
# check adding a single token
tokenizer.add_tokens("x")
token_ids = tokenizer("C x A").input_ids
self.assertEqual(token_ids, [19, 4, 32, 4, 7])
tokenizer.add_tokens(["a", "b", "c"])
token_ids = tokenizer("C a A c").input_ids
self.assertEqual(token_ids, [19, 4, 33, 4, 7, 4, 35])
tokenizer.add_tokens(["a", "b", "c"])
token_ids = tokenizer("CaA c").input_ids
self.assertEqual(token_ids, [19, 33, 7, 4, 35])
def test_tokenizer_add_token_words(self):
tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-base-960h")
# check adding a single token
tokenizer.add_tokens("xxx")
token_ids = tokenizer("C xxx A B").input_ids
self.assertEqual(token_ids, [19, 4, 32, 4, 7, 4, 24])
tokenizer.add_tokens(["aaa", "bbb", "ccc"])
token_ids = tokenizer("C aaa A ccc B B").input_ids
self.assertEqual(token_ids, [19, 4, 33, 4, 7, 4, 35, 4, 24, 4, 24])
tokenizer.add_tokens(["aaa", "bbb", "ccc"])
token_ids = tokenizer("CaaaA ccc B B").input_ids
self.assertEqual(token_ids, [19, 33, 7, 4, 35, 4, 24, 4, 24])
def test_tokenizer_decode(self):
tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-base-960h")
sample_ids = [
[11, 5, 15, tokenizer.pad_token_id, 15, 8, 98],
[24, 22, 5, tokenizer.word_delimiter_token_id, 24, 22, 5, 77],
]
tokens = tokenizer.decode(sample_ids[0])
batch_tokens = tokenizer.batch_decode(sample_ids)
self.assertEqual(tokens, batch_tokens[0])
self.assertEqual(batch_tokens, ["HELLO<unk>", "BYE BYE<unk>"])
def test_tokenizer_decode_special(self):
tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-base-960h")
# fmt: off
sample_ids = [
[11, 5, 15, tokenizer.pad_token_id, 15, 8, 98],
[24, 22, 5, tokenizer.word_delimiter_token_id, 24, 22, 5, 77],
]
sample_ids_2 = [
[11, 5, 5, 5, 5, 5, 15, 15, 15, tokenizer.pad_token_id, 15, 8, 98],
[24, 22, 5, tokenizer.pad_token_id, tokenizer.pad_token_id, tokenizer.pad_token_id, tokenizer.word_delimiter_token_id, 24, 22, 5, 77, tokenizer.word_delimiter_token_id],
]
# fmt: on
batch_tokens = tokenizer.batch_decode(sample_ids)
batch_tokens_2 = tokenizer.batch_decode(sample_ids_2)
self.assertEqual(batch_tokens, batch_tokens_2)
self.assertEqual(batch_tokens, ["HELLO<unk>", "BYE BYE<unk>"])
def test_tokenizer_decode_added_tokens(self):
tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-base-960h")
tokenizer.add_tokens(["!", "?", "<new_tokens>"])
tokenizer.add_special_tokens({"cls_token": "$$$"})
# fmt: off
sample_ids = [
[11, 5, 15, tokenizer.pad_token_id, 15, 8, 98, 32, 32, 33, tokenizer.word_delimiter_token_id, 32, 32, 33, 34, 34, 35, 35],
[24, 22, 5, tokenizer.word_delimiter_token_id, 24, 22, 5, 77, tokenizer.pad_token_id, 34, 34, 35, 35],
]
# fmt: on
batch_tokens = tokenizer.batch_decode(sample_ids)
batch_tokens_2 = tokenizer.batch_decode(sample_ids, skip_special_tokens=True)
self.assertEqual(batch_tokens, ["HELLO<unk>!? !?<new_tokens>$$$", "BYE BYE<unk><new_tokens>$$$"])
self.assertEqual(batch_tokens_2, ["HELO!? !?<new_tokens>", "BYE BYE<new_tokens>"])
def test_special_characters_in_vocab(self):
sent = "ʈʰ æ æ̃ ˧ kʰ"
vocab_dict = {k: v for v, k in enumerate(set(sent.split()))}
vocab_file = os.path.join(self.tmpdirname, "vocab_special.json")
with open(vocab_file, "w") as f:
json.dump(vocab_dict, f)
tokenizer = Wav2Vec2CTCTokenizer(vocab_file) # , unk_token="<unk>")
expected_sent = tokenizer.decode(tokenizer(sent).input_ids, spaces_between_special_tokens=True)
self.assertEqual(sent, expected_sent)
tokenizer.save_pretrained(os.path.join(self.tmpdirname, "special_tokenizer"))
tokenizer = Wav2Vec2CTCTokenizer.from_pretrained(os.path.join(self.tmpdirname, "special_tokenizer"))
expected_sent = tokenizer.decode(tokenizer(sent).input_ids, spaces_between_special_tokens=True)
self.assertEqual(sent, expected_sent)
@staticmethod
def get_from_offsets(offsets, key):
retrieved_list = [d[key] for d in offsets]
return retrieved_list
def test_offsets(self):
tokenizer = self.get_tokenizer()
# fmt: off
# HEEEEE||LLL<pad>LO<unk> => HE LLO<unk>
# 1H + 5E + 2| + 3L + 1<pad> + 1L + 1O + 1<unk>
sample_ids = [11, 5, 5, 5, 5, 5, 4, 4, 15, 15, 15, tokenizer.pad_token_id, 15, 8, 98]
# fmt: on
outputs_char = tokenizer.decode(sample_ids, output_char_offsets=True)
# check Wav2Vec2CTCTokenizerOutput keys for char
self.assertEqual(len(outputs_char.keys()), 2)
self.assertTrue("text" in outputs_char)
self.assertTrue("char_offsets" in outputs_char)
self.assertTrue(isinstance(outputs_char, Wav2Vec2CTCTokenizerOutput))
outputs_word = tokenizer.decode(sample_ids, output_word_offsets=True)
# check Wav2Vec2CTCTokenizerOutput keys for word
self.assertEqual(len(outputs_word.keys()), 2)
self.assertTrue("text" in outputs_word)
self.assertTrue("word_offsets" in outputs_word)
self.assertTrue(isinstance(outputs_word, Wav2Vec2CTCTokenizerOutput))
outputs = tokenizer.decode(sample_ids, output_char_offsets=True, output_word_offsets=True)
# check Wav2Vec2CTCTokenizerOutput keys for both
self.assertEqual(len(outputs.keys()), 3)
self.assertTrue("text" in outputs)
self.assertTrue("char_offsets" in outputs)
self.assertTrue("word_offsets" in outputs)
self.assertTrue(isinstance(outputs, Wav2Vec2CTCTokenizerOutput))
# check that order of chars is correct and identical for both outputs
self.assertEqual("".join(self.get_from_offsets(outputs["char_offsets"], "char")), outputs.text)
self.assertEqual(
self.get_from_offsets(outputs["char_offsets"], "char"), ["H", "E", " ", "L", "L", "O", "<unk>"]
)
self.assertListEqual(
self.get_from_offsets(outputs["char_offsets"], "char"),
self.get_from_offsets(outputs_char["char_offsets"], "char"),
)
# check that order of words is correct and identical to both outputs
self.assertEqual(" ".join(self.get_from_offsets(outputs["word_offsets"], "word")), outputs.text)
self.assertListEqual(self.get_from_offsets(outputs["word_offsets"], "word"), ["HE", "LLO<unk>"])
self.assertListEqual(
self.get_from_offsets(outputs["word_offsets"], "word"),
self.get_from_offsets(outputs_word["word_offsets"], "word"),
)
# check that offsets are actually correct for char
# 0 is H, 1 is E, 6 is | (" "), 8 is 1st L, 12 is 2nd L, 13 is O, 14 is <unk>
self.assertListEqual(self.get_from_offsets(outputs["char_offsets"], "start_offset"), [0, 1, 6, 8, 12, 13, 14])
# 1 is H, 6 is E, 8 is | (" "), 11 is 1st L (note due to <pad>
# different begin of 2nd L), 13 is 2nd L, 14 is O, 15 is <unk>
self.assertListEqual(self.get_from_offsets(outputs["char_offsets"], "end_offset"), [1, 6, 8, 11, 13, 14, 15])
# check that offsets are actually correct for word
# H is at 1st position of first word, first L is at 8th position of second word
self.assertListEqual(self.get_from_offsets(outputs["word_offsets"], "start_offset"), [0, 8])
# last E is at 6th position of first word, first L is at last (15th) position of second word
self.assertListEqual(self.get_from_offsets(outputs["word_offsets"], "end_offset"), [6, 15])
def test_word_offsets_from_char_offsets(self):
tokenizer = self.get_tokenizer()
char_offsets = [
{"char": "H", "start_offset": 0, "end_offset": 1},
{"char": "I", "start_offset": 1, "end_offset": 2},
{"char": " ", "start_offset": 2, "end_offset": 3},
{"char": "L", "start_offset": 3, "end_offset": 4},
{"char": "I", "start_offset": 4, "end_offset": 5},
]
word_offsets = tokenizer._get_word_offsets(char_offsets, tokenizer.replace_word_delimiter_char)
self.assertEqual(
word_offsets,
[{"word": "HI", "start_offset": 0, "end_offset": 2}, {"word": "LI", "start_offset": 3, "end_offset": 5}],
)
# Double spaces don't get counted
char_offsets = [
{"char": " ", "start_offset": 0, "end_offset": 1},
{"char": "H", "start_offset": 1, "end_offset": 2},
{"char": "I", "start_offset": 2, "end_offset": 3},
{"char": " ", "start_offset": 3, "end_offset": 4},
{"char": " ", "start_offset": 4, "end_offset": 5},
{"char": "L", "start_offset": 5, "end_offset": 6},
{"char": "I", "start_offset": 6, "end_offset": 7},
{"char": "I", "start_offset": 7, "end_offset": 8},
{"char": " ", "start_offset": 8, "end_offset": 9},
{"char": " ", "start_offset": 9, "end_offset": 10},
]
word_offsets = tokenizer._get_word_offsets(char_offsets, tokenizer.replace_word_delimiter_char)
self.assertEqual(
word_offsets,
[{"word": "HI", "start_offset": 1, "end_offset": 3}, {"word": "LII", "start_offset": 5, "end_offset": 8}],
)
def test_offsets_batch(self):
tokenizer = self.get_tokenizer()
def check_list_tuples_equal(outputs_batch, outputs_list):
self.assertTrue(isinstance(outputs_batch, Wav2Vec2CTCTokenizerOutput))
self.assertTrue(isinstance(outputs_list[0], Wav2Vec2CTCTokenizerOutput))
# transform list to ModelOutput
outputs_batch_2 = Wav2Vec2CTCTokenizerOutput({k: [d[k] for d in outputs_list] for k in outputs_list[0]})
self.assertListEqual(outputs_batch["text"], outputs_batch_2["text"])
def recursive_check(list_or_dict_1, list_or_dict_2):
if isinstance(list_or_dict_1, list):
[recursive_check(l1, l2) for l1, l2 in zip(list_or_dict_1, list_or_dict_2)]
self.assertEqual(list_or_dict_1, list_or_dict_2)
if "char_offsets" in outputs_batch:
recursive_check(outputs_batch["char_offsets"], outputs_batch_2["char_offsets"])
if "word_offsets" in outputs_batch:
recursive_check(outputs_batch["word_offsets"], outputs_batch_2["word_offsets"])
# fmt: off
sample_ids = [
[11, 5, 15, tokenizer.pad_token_id, 15, 4, 8, 98, 32, 32, 32, 32, 4, 33, tokenizer.word_delimiter_token_id, 32, 32, 33, 34, 34],
[24, 22, 5, tokenizer.word_delimiter_token_id, tokenizer.word_delimiter_token_id, 24, 22, 22, 22, 4, 5, 77, tokenizer.pad_token_id, 22, 22, 4, 34, 34, 34, 34],
]
# fmt: on
# We assume that `decode` works as expected. All we will check now is
# the output type is correct and the output is identical to `decode`
# char
outputs_char_batch = tokenizer.batch_decode(sample_ids, output_char_offsets=True)
outputs_char = [tokenizer.decode(ids, output_char_offsets=True) for ids in sample_ids]
check_list_tuples_equal(outputs_char_batch, outputs_char)
# word
outputs_word_batch = tokenizer.batch_decode(sample_ids, output_word_offsets=True)
outputs_word = [tokenizer.decode(ids, output_word_offsets=True) for ids in sample_ids]
check_list_tuples_equal(outputs_word_batch, outputs_word)
# both
outputs_batch = tokenizer.batch_decode(sample_ids, output_char_offsets=True, output_word_offsets=True)
outputs = [tokenizer.decode(ids, output_word_offsets=True, output_char_offsets=True) for ids in sample_ids]
check_list_tuples_equal(outputs_batch, outputs)
def test_offsets_integration(self):
tokenizer = self.tokenizer_class.from_pretrained("facebook/wav2vec2-base-960h")
# pred_ids correspond to the following code
# ```
# from transformers import AutoTokenizer, AutoFeatureExtractor, AutoModelForCTC
# from datasets import load_dataset
# import datasets
# import torch
# model = AutoModelForCTC.from_pretrained("facebook/wav2vec2-base-960h")
# feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base-960h")
#
# ds = load_dataset("common_voice", "en", split="train", streaming=True)
# ds = ds.cast_column("audio", datasets.Audio(sampling_rate=16_000))
# ds_iter = iter(ds)
# sample = next(ds_iter)
#
# input_values = feature_extractor(sample["audio"]["array"], return_tensors="pt").input_values
# logits = model(input_values).logits
# pred_ids = torch.argmax(logits, axis=-1).tolist()
# ```
# fmt: off
pred_ids = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 11, 0, 0, 0, 22, 0, 0, 4, 4, 4, 14, 0, 0, 0, 0, 0, 8, 8, 0, 5, 5, 0, 12, 0, 4, 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 0, 0, 10, 0, 0, 0, 15, 0, 0, 10, 0, 0, 0, 12, 0, 0, 0, 0, 0, 7, 0, 9, 0, 0, 14, 0, 0, 0, 13, 0, 7, 0, 0, 4, 4, 0, 15, 8, 8, 0, 0, 8, 0, 26, 0, 0, 4, 4, 0, 0, 15, 0, 0, 0, 0, 0, 0, 10, 0, 26, 5, 5, 0, 4, 4, 0, 0, 12, 11, 0, 0, 5, 4, 4, 4, 0, 18, 0, 0, 0, 7, 9, 9, 0, 6, 0, 12, 12, 4, 4, 0, 6, 0, 0, 8, 0, 4, 4, 4, 0, 19, 0, 0, 8, 9, 9, 0, 0, 0, 0, 12, 12, 0, 0, 0, 0, 0, 0, 0, 16, 16, 0, 0, 17, 5, 5, 5, 0, 4, 4, 4, 0, 0, 29, 29, 0, 0, 0, 0, 8, 11, 0, 9, 9, 0, 0, 0, 4, 4, 0, 12, 12, 0, 0, 0, 9, 0, 0, 0, 0, 0, 8, 18, 0, 0, 0, 4, 4, 0, 0, 8, 9, 0, 4, 4, 0, 6, 11, 5, 0, 4, 4, 0, 13, 13, 0, 0, 0, 10, 0, 0, 25, 0, 0, 6, 0, 4, 4, 0, 0, 0, 0, 7, 0, 0, 23, 0, 0, 4, 4, 0, 0, 0, 6, 11, 0, 5, 4, 4, 18, 0, 0, 0, 0, 0, 0, 7, 15, 0, 0, 0, 15, 15, 0, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
# wav2vec2-base downsamples input audio by a factor of 320
# sampling rate for wav2vec2-base is 16_000
time_offset_wav2vec2_base = 320 / 16_000
expected_char_time_stamps_text = ['W', 'H', 'Y', ' ', 'D', 'O', 'E', 'S', ' ', 'M', 'I', 'L', 'I', 'S', 'A', 'N', 'D', 'R', 'A', ' ', 'L', 'O', 'O', 'K', ' ', 'L', 'I', 'K', 'E', ' ', 'S', 'H', 'E', ' ', 'W', 'A', 'N', 'T', 'S', ' ', 'T', 'O', ' ', 'C', 'O', 'N', 'S', 'U', 'M', 'E', ' ', 'J', 'O', 'H', 'N', ' ', 'S', 'N', 'O', 'W', ' ', 'O', 'N', ' ', 'T', 'H', 'E', ' ', 'R', 'I', 'V', 'T', ' ', 'A', 'P', ' ', 'T', 'H', 'E', ' ', 'W', 'A', 'L', 'L', ' ']
expected_char_time_stamps_start = [1.42, 1.44, 1.52, 1.58, 1.64, 1.76, 1.82, 1.88, 1.92, 2.26, 2.32, 2.4, 2.46, 2.54, 2.66, 2.7, 2.76, 2.84, 2.88, 2.94, 3.0, 3.02, 3.1, 3.14, 3.2, 3.28, 3.42, 3.46, 3.48, 3.54, 3.62, 3.64, 3.7, 3.72, 3.8, 3.88, 3.9, 3.96, 4.0, 4.04, 4.1, 4.16, 4.2, 4.28, 4.34, 4.36, 4.48, 4.66, 4.74, 4.76, 4.84, 4.94, 5.06, 5.08, 5.12, 5.22, 5.28, 5.38, 5.5, 5.52, 5.6, 5.68, 5.7, 5.74, 5.8, 5.82, 5.84, 5.88, 5.94, 6.04, 6.1, 6.16, 6.2, 6.32, 6.38, 6.44, 6.54, 6.56, 6.6, 6.62, 6.66, 6.8, 6.82, 6.9, 6.96]
expected_char_time_stamps_end = [1.44, 1.46, 1.54, 1.64, 1.66, 1.8, 1.86, 1.9, 2.06, 2.28, 2.34, 2.42, 2.48, 2.56, 2.68, 2.72, 2.78, 2.86, 2.9, 2.98, 3.02, 3.06, 3.12, 3.16, 3.24, 3.3, 3.44, 3.48, 3.52, 3.58, 3.64, 3.66, 3.72, 3.78, 3.82, 3.9, 3.94, 3.98, 4.04, 4.08, 4.12, 4.18, 4.26, 4.3, 4.36, 4.4, 4.52, 4.7, 4.76, 4.82, 4.9, 4.98, 5.08, 5.1, 5.16, 5.26, 5.32, 5.4, 5.52, 5.54, 5.64, 5.7, 5.72, 5.78, 5.82, 5.84, 5.86, 5.92, 5.98, 6.06, 6.12, 6.18, 6.24, 6.34, 6.4, 6.48, 6.56, 6.58, 6.62, 6.66, 6.68, 6.82, 6.84, 6.94, 7.02]
expected_word_time_stamps_text = ['WHY', 'DOES', 'MILISANDRA', 'LOOK', 'LIKE', 'SHE', 'WANTS', 'TO', 'CONSUME', 'JOHN', 'SNOW', 'ON', 'THE', 'RIVT', 'AP', 'THE', 'WALL']
expected_word_time_stamps_start = [1.42, 1.64, 2.26, 3.0, 3.28, 3.62, 3.8, 4.1, 4.28, 4.94, 5.28, 5.68, 5.8, 5.94, 6.32, 6.54, 6.66]
expected_word_time_stamps_end = [1.54, 1.9, 2.9, 3.16, 3.52, 3.72, 4.04, 4.18, 4.82, 5.16, 5.54, 5.72, 5.86, 6.18, 6.4, 6.62, 6.94]
# fmt: on
output = tokenizer.batch_decode(pred_ids, output_char_offsets=True, output_word_offsets=True)
char_offsets_text = self.get_from_offsets(output["char_offsets"][0], "char")
char_offsets_start = self.get_from_offsets(output["char_offsets"][0], "start_offset")
char_offsets_end = self.get_from_offsets(output["char_offsets"][0], "end_offset")
word_offsets_text = self.get_from_offsets(output["word_offsets"][0], "word")
word_offsets_start = self.get_from_offsets(output["word_offsets"][0], "start_offset")
word_offsets_end = self.get_from_offsets(output["word_offsets"][0], "end_offset")
# let's transform offsets to time stamps in seconds
char_time_stamps_start = [round(c * time_offset_wav2vec2_base, 2) for c in char_offsets_start]
char_time_stamps_end = [round(c * time_offset_wav2vec2_base, 2) for c in char_offsets_end]
word_time_stamps_start = [round(w * time_offset_wav2vec2_base, 2) for w in word_offsets_start]
word_time_stamps_end = [round(w * time_offset_wav2vec2_base, 2) for w in word_offsets_end]
# NOTE: you can verify the above results by checking out the dataset viewer
# on https://huggingface.co/datasets/common_voice/viewer/en/train and
# downloading / playing the sample `common_voice_en_100038.mp3`. As
# you can hear the time-stamps match more or less
self.assertListEqual(expected_char_time_stamps_text, char_offsets_text)
self.assertListEqual(expected_char_time_stamps_start, char_time_stamps_start)
self.assertListEqual(expected_char_time_stamps_end, char_time_stamps_end)
self.assertListEqual(expected_word_time_stamps_text, word_offsets_text)
self.assertListEqual(expected_word_time_stamps_start, word_time_stamps_start)
self.assertListEqual(expected_word_time_stamps_end, word_time_stamps_end)
# overwrite from test_tokenization_common
def test_add_tokens_tokenizer(self):
tokenizers = self.get_tokenizers(do_lower_case=False)
for tokenizer in tokenizers:
with self.subTest(f"{tokenizer.__class__.__name__}"):
vocab_size = tokenizer.vocab_size
all_size = len(tokenizer)
self.assertNotEqual(vocab_size, 0)
# We usually have added tokens from the start in tests because our vocab fixtures are
# smaller than the original vocabs - let's not assert this
# self.assertEqual(vocab_size, all_size)
new_toks = ["aaaaa bbbbbb", "cccccccccdddddddd"]
added_toks = tokenizer.add_tokens(new_toks)
vocab_size_2 = tokenizer.vocab_size
all_size_2 = len(tokenizer)
self.assertNotEqual(vocab_size_2, 0)
self.assertEqual(vocab_size, vocab_size_2)
self.assertEqual(added_toks, len(new_toks))
self.assertEqual(all_size_2, all_size + len(new_toks))
tokens = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l", add_special_tokens=False)
self.assertGreaterEqual(len(tokens), 4)
self.assertGreater(tokens[0], tokenizer.vocab_size - 1)
self.assertGreater(tokens[-3], tokenizer.vocab_size - 1)
new_toks_2 = {
"eos_token": AddedToken(">>>>|||<||<<|<<", lstrip=False, rstrip=False),
"pad_token": AddedToken("<<<<<|||>|>>>>|>", rstrip=False, lstrip=False),
}
added_toks_2 = tokenizer.add_special_tokens(new_toks_2)
vocab_size_3 = tokenizer.vocab_size
all_size_3 = len(tokenizer)
self.assertNotEqual(vocab_size_3, 0)
self.assertEqual(vocab_size, vocab_size_3)
self.assertEqual(added_toks_2, len(new_toks_2))
self.assertEqual(all_size_3, all_size_2 + len(new_toks_2))
tokens = tokenizer.encode(
">>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l", add_special_tokens=False
)
self.assertGreaterEqual(len(tokens), 6)
self.assertGreater(tokens[0], tokenizer.vocab_size - 1)
self.assertGreater(tokens[0], tokens[1])
self.assertGreater(tokens[-3], tokenizer.vocab_size - 1)
self.assertGreater(tokens[-3], tokens[-4])
self.assertEqual(tokens[0], tokenizer.eos_token_id)
self.assertEqual(tokens[-3], tokenizer.pad_token_id)
@unittest.skip(reason="The tokenizer shouldn't be used to encode input IDs (except for labels), only to decode.")
def test_tf_encode_plus_sent_to_model(self):
pass
@unittest.skip(reason="The tokenizer shouldn't be used to encode input IDs (except for labels), only to decode.")
def test_torch_encode_plus_sent_to_model(self):
pass
def test_convert_tokens_to_string_format(self):
# The default common tokenizer tests assumes that the output of `convert_tokens_to_string` is a string which
# is not the case for Wav2vec2.
tokenizers = self.get_tokenizers(fast=True, do_lower_case=True)
for tokenizer in tokenizers:
with self.subTest(f"{tokenizer.__class__.__name__}"):
tokens = ["T", "H", "I", "S", "|", "I", "S", "|", "A", "|", "T", "E", "X", "T"]
output = tokenizer.convert_tokens_to_string(tokens)
self.assertIsInstance(output["text"], str)
def test_nested_vocab(self):
eng_vocab = {"a": 7, "b": 8}
spa_vocab = {"a": 23, "c": 88}
ita_vocab = {"a": 6, "d": 9}
nested_vocab = {"eng": eng_vocab, "spa": spa_vocab, "ita": ita_vocab}
def check_tokenizer(tokenizer, check_ita_first=False):
if check_ita_first:
self.assertEqual(tokenizer.decode([6, 9, 9]), "ad")
self.assertEqual(tokenizer.encoder, ita_vocab)
tokenizer.set_target_lang("eng")
self.assertEqual(tokenizer.encoder, eng_vocab)
self.assertEqual(tokenizer.decode([7, 8, 7]), "aba")
tokenizer.set_target_lang("spa")
self.assertEqual(tokenizer.decode([23, 88, 23]), "aca")
self.assertEqual(tokenizer.encoder, spa_vocab)
tokenizer.set_target_lang("eng")
self.assertEqual(tokenizer.encoder, eng_vocab)
self.assertEqual(tokenizer.decode([7, 7, 8]), "ab")
tokenizer.set_target_lang("ita")
self.assertEqual(tokenizer.decode([6, 9, 9]), "ad")
self.assertEqual(tokenizer.encoder, ita_vocab)
with tempfile.TemporaryDirectory() as tempdir:
tempfile_path = os.path.join(tempdir, "vocab.json")
with open(tempfile_path, "w") as temp_file:
json.dump(nested_vocab, temp_file)
tokenizer = Wav2Vec2CTCTokenizer.from_pretrained(tempdir, target_lang="eng")
check_tokenizer(tokenizer)
with tempfile.TemporaryDirectory() as tempdir:
# should have saved target lang as "ita" since it was last one
tokenizer.save_pretrained(tempdir)
tokenizer = Wav2Vec2CTCTokenizer.from_pretrained(tempdir)
self.assertEqual(tokenizer.target_lang, "ita")
check_tokenizer(tokenizer, check_ita_first=True)
| Wav2Vec2CTCTokenizerTest |
python | astropy__astropy | astropy/utils/iers/iers.py | {
"start": 39279,
"end": 51880
} | class ____(QTable):
"""Leap seconds class, holding TAI-UTC differences.
The table should hold columns 'year', 'month', 'tai_utc'.
Methods are provided to initialize the table from IERS ``Leap_Second.dat``,
IETF/ntp ``leap-seconds.list``, or built-in ERFA/SOFA, and to update the
list used by ERFA.
Notes
-----
Astropy has a built-in ``iers.IERS_LEAP_SECONDS_FILE``. Up to date versions
can be downloaded from ``iers.IERS_LEAP_SECONDS_URL`` or
``iers.LEAP_SECONDS_LIST_URL``. Many systems also store a version
of ``leap-seconds.list`` for use with ``ntp`` (e.g., on Debian/Ubuntu
systems, ``/usr/share/zoneinfo/leap-seconds.list``).
To prevent querying internet resources if the available local leap second
file(s) are out of date, set ``iers.conf.auto_download = False``. This
must be done prior to performing any ``Time`` scale transformations related
to UTC (e.g. converting from UTC to TAI).
"""
# Note: Time instances in this class should use scale='tai' to avoid
# needing leap seconds in their creation or interpretation.
_re_expires = re.compile(r"^#.*File expires on[:\s]+(\d+\s\w+\s\d+)\s*$")
_expires = None
_auto_open_files = [
"erfa",
IERS_LEAP_SECOND_FILE,
"system_leap_second_file",
"iers_leap_second_auto_url",
"ietf_leap_second_auto_url",
]
"""Files or conf attributes to try in auto_open."""
@classmethod
def open(cls, file=None, cache=False):
"""Open a leap-second list.
Parameters
----------
file : path-like or None
Full local or network path to the file holding leap-second data,
for passing on to the various ``from_`` class methods.
If 'erfa', return the data used by the ERFA library.
If `None`, use default locations from file and configuration to
find a table that is not expired.
cache : bool
Whether to use cache. Defaults to False, since leap-second files
are regularly updated.
Returns
-------
leap_seconds : `~astropy.utils.iers.LeapSeconds`
Table with 'year', 'month', and 'tai_utc' columns, plus possibly
others.
Notes
-----
Bulletin C is released about 10 days after a possible leap second is
introduced, i.e., mid-January or mid-July. Expiration days are thus
generally at least 150 days after the present. For the auto-loading,
a list comprised of the table shipped with astropy, and files and
URLs in `~astropy.utils.iers.Conf` are tried, returning the first
that is sufficiently new, or the newest among them all.
"""
if file is None:
return cls.auto_open()
if file.lower() == "erfa":
return cls.from_erfa()
if urlparse(file).netloc:
file = download_file(file, cache=cache)
# Just try both reading methods.
try:
return cls.from_iers_leap_seconds(file)
except Exception:
return cls.from_leap_seconds_list(file)
@staticmethod
def _today():
# Get current day in scale='tai' without going through a scale change
# (so we do not need leap seconds).
s = "{0.year:04d}-{0.month:02d}-{0.day:02d}".format(datetime.now(tz=UTC))
return Time(s, scale="tai", format="iso", out_subfmt="date")
@classmethod
def auto_open(cls, files=None):
"""Attempt to get an up-to-date leap-second list.
The routine will try the files in sequence until it finds one
whose expiration date is "good enough" (see below). If none
are good enough, it returns the one with the most recent expiration
date, warning if that file is expired.
For remote files that are cached already, the cached file is tried
first before attempting to retrieve it again.
Parameters
----------
files : list of path-like, optional
List of files/URLs to attempt to open. By default, uses
``cls._auto_open_files``.
Returns
-------
leap_seconds : `~astropy.utils.iers.LeapSeconds`
Up to date leap-second table
Notes
-----
Bulletin C is released about 10 days after a possible leap second is
introduced, i.e., mid-January or mid-July. Expiration days are thus
generally at least 150 days after the present. We look for a file
that expires more than 180 - `~astropy.utils.iers.Conf.auto_max_age`
after the present.
"""
offset = 180 - (30 if conf.auto_max_age is None else conf.auto_max_age)
good_enough = cls._today() + TimeDelta(offset, format="jd")
if files is None:
# Basic files to go over (entries in _auto_open_files can be
# configuration items, which we want to be sure are up to date).
files = [getattr(conf, f, f) for f in cls._auto_open_files]
# Remove empty entries and normalize Path objects to string
files = [os.fspath(f) for f in files if f]
# Our trials start with normal files and remote ones that are
# already in cache. The bools here indicate that the cache
# should be used.
trials = [
(f, True) for f in files if not urlparse(f).netloc or is_url_in_cache(f)
]
# If we are allowed to download, we try downloading new versions
# if none of the above worked.
if conf.auto_download:
trials += [(f, False) for f in files if urlparse(f).netloc]
self = None
err_list = []
# Go through all entries, and return the first one that
# is not expired, or the most up to date one.
for f, allow_cache in trials:
if not allow_cache:
clear_download_cache(f)
try:
trial = cls.open(f, cache=True)
except Exception as exc:
err_list.append(exc)
continue
if self is None or trial.expires > self.expires:
self = trial
self.meta["data_url"] = str(f)
if self.expires > good_enough:
break
if self is None:
raise ValueError(
"none of the files could be read. The "
f"following errors were raised:\n {err_list}"
)
if self.expires < self._today() and conf.auto_max_age is not None:
warn("leap-second file is expired.", IERSStaleWarning)
return self
@property
def expires(self):
"""The limit of validity of the table."""
return self._expires
@classmethod
def _read_leap_seconds(cls, file, **kwargs):
"""Read a file, identifying expiration by matching 'File expires'."""
expires = None
# Find expiration date.
with get_readable_fileobj(file) as fh:
lines = fh.readlines()
for line in lines:
match = cls._re_expires.match(line)
if match:
day, month, year = match.groups()[0].split()
month_nb = MONTH_ABBR.index(month[:3]) + 1
expires = Time(
f"{year}-{month_nb:02d}-{day}", scale="tai", out_subfmt="date"
)
break
else:
raise ValueError(f"did not find expiration date in {file}")
self = cls.read(lines, format="ascii.no_header", **kwargs)
self._expires = expires
return self
@classmethod
def from_iers_leap_seconds(cls, file=IERS_LEAP_SECOND_FILE):
"""Create a table from a file like the IERS ``Leap_Second.dat``.
Parameters
----------
file : path-like, optional
Full local or network path to the file holding leap-second data
in a format consistent with that used by IERS. By default, uses
``iers.IERS_LEAP_SECOND_FILE``.
Notes
-----
The file *must* contain the expiration date in a comment line, like
'# File expires on 28 June 2020'
"""
return cls._read_leap_seconds(
file, names=["mjd", "day", "month", "year", "tai_utc"]
)
@classmethod
def from_leap_seconds_list(cls, file):
"""Create a table from a file like the IETF ``leap-seconds.list``.
Parameters
----------
file : path-like, optional
Full local or network path to the file holding leap-second data
in a format consistent with that used by IETF. Up to date versions
can be retrieved from ``iers.IETF_LEAP_SECOND_URL``.
Notes
-----
The file *must* contain the expiration date in a comment line, like
'# File expires on: 28 June 2020'
"""
from astropy.io.ascii import convert_numpy # Here to avoid circular import
names = ["ntp_seconds", "tai_utc", "comment", "day", "month", "year"]
# Note: ntp_seconds does not fit in 32 bit, so causes problems on
# 32-bit systems without the np.int64 converter.
self = cls._read_leap_seconds(
file,
names=names,
include_names=names[:2],
converters={"ntp_seconds": [convert_numpy(np.int64)]},
)
self["mjd"] = (self["ntp_seconds"] / 86400 + 15020).round()
# Note: cannot use Time.ymdhms, since that might require leap seconds.
isot = Time(self["mjd"], format="mjd", scale="tai").isot
ymd = np.array(
[[int(part) for part in t.partition("T")[0].split("-")] for t in isot]
)
self["year"], self["month"], self["day"] = ymd.T
return self
@classmethod
def from_erfa(cls, built_in=False):
"""Create table from the leap-second list in ERFA.
Parameters
----------
built_in : bool
If `False` (default), retrieve the list currently used by ERFA,
which may have been updated. If `True`, retrieve the list shipped
with erfa.
"""
current = cls(erfa.leap_seconds.get())
expires = erfa.leap_seconds.expires
current._expires = Time(
f"{expires.year:04d}-{expires.month:02d}-{expires.day:02d}",
scale="tai",
)
if not built_in:
return current
try:
erfa.leap_seconds.set(None) # reset to defaults
return cls.from_erfa(built_in=False)
finally:
erfa.leap_seconds.set(current)
def update_erfa_leap_seconds(self, initialize_erfa=False):
"""Add any leap seconds not already present to the ERFA table.
This method matches leap seconds with those present in the ERFA table,
and extends the latter as necessary.
Parameters
----------
initialize_erfa : bool, or 'only', or 'empty'
Initialize the ERFA leap second table to its built-in value before
trying to expand it. This is generally not needed but can help
in case it somehow got corrupted. If equal to 'only', the ERFA
table is reinitialized and no attempt it made to update it.
If 'empty', the leap second table is emptied before updating, i.e.,
it is overwritten altogether (note that this may break things in
surprising ways, as most leap second tables do not include pre-1970
pseudo leap-seconds; you were warned).
Returns
-------
n_update : int
Number of items updated.
Raises
------
ValueError
If the leap seconds in the table are not on 1st of January or July,
or if the matches are inconsistent. This would normally suggest
a corrupted leap second table, but might also indicate that the
ERFA table was corrupted. If needed, the ERFA table can be reset
by calling this method with an appropriate value for
``initialize_erfa``.
"""
if initialize_erfa == "empty":
# Initialize to empty and update is the same as overwrite.
erfa.leap_seconds.set(self)
return len(self)
if initialize_erfa:
erfa.leap_seconds.set()
if initialize_erfa == "only":
return 0
return erfa.leap_seconds.update(self)
| LeapSeconds |
python | spack__spack | lib/spack/spack/spec.py | {
"start": 46585,
"end": 51954
} | class ____(lang.ObjectWrapper):
# home is available in the base Package so no default is needed
home = ForwardQueryToPackage("home", default_handler=None)
headers = ForwardQueryToPackage("headers", default_handler=_headers_default_handler)
libs = ForwardQueryToPackage("libs", default_handler=_libs_default_handler)
command = ForwardQueryToPackage("command", default_handler=None, _indirect=True)
def __init__(
self,
spec: "Spec",
name: str,
query_parameters: List[str],
_parent: "Spec",
is_virtual: bool,
):
super().__init__(spec)
# Adding new attributes goes after super() call since the ObjectWrapper
# resets __dict__ to behave like the passed object
original_spec = getattr(spec, "wrapped_obj", spec)
self.wrapped_obj = original_spec
self.token = original_spec, name, query_parameters, _parent, is_virtual
self.last_query = QueryState(
name=name, extra_parameters=query_parameters, isvirtual=is_virtual
)
# TODO: this ad-hoc logic makes `spec["python"].command` return
# `spec["python-venv"].command` and should be removed when `python` is a virtual.
self.indirect_spec = None
if spec.name == "python":
python_venvs = _parent.dependencies("python-venv")
if not python_venvs:
return
self.indirect_spec = python_venvs[0]
def __reduce__(self):
return SpecBuildInterface, self.token
def copy(self, *args, **kwargs):
return self.wrapped_obj.copy(*args, **kwargs)
def tree(
specs: List["Spec"],
*,
color: Optional[bool] = None,
depth: bool = False,
hashes: bool = False,
hashlen: Optional[int] = None,
cover: spack.traverse.CoverType = "nodes",
indent: int = 0,
format: str = DEFAULT_FORMAT,
deptypes: Union[dt.DepFlag, dt.DepTypes] = dt.ALL,
show_types: bool = False,
depth_first: bool = False,
recurse_dependencies: bool = True,
status_fn: Optional[Callable[["Spec"], InstallStatus]] = None,
prefix: Optional[Callable[["Spec"], str]] = None,
key: Callable[["Spec"], Any] = id,
) -> str:
"""Prints out specs and their dependencies, tree-formatted with indentation.
Status function may either output a boolean or an InstallStatus
Args:
color: if True, always colorize the tree. If False, don't colorize the tree. If None,
use the default from spack.llnl.tty.color
depth: print the depth from the root
hashes: if True, print the hash of each node
hashlen: length of the hash to be printed
cover: either ``"nodes"`` or ``"edges"``
indent: extra indentation for the tree being printed
format: format to be used to print each node
deptypes: dependency types to be represented in the tree
show_types: if True, show the (merged) dependency type of a node
depth_first: if True, traverse the DAG depth first when representing it as a tree
recurse_dependencies: if True, recurse on dependencies
status_fn: optional callable that takes a node as an argument and return its
installation status
prefix: optional callable that takes a node as an argument and return its
installation prefix
"""
out = ""
if color is None:
color = clr.get_color_when()
# reduce deptypes over all in-edges when covering nodes
if show_types and cover == "nodes":
deptype_lookup: Dict[str, dt.DepFlag] = collections.defaultdict(dt.DepFlag)
for edge in spack.traverse.traverse_edges(
specs, cover="edges", deptype=deptypes, root=False
):
deptype_lookup[edge.spec.dag_hash()] |= edge.depflag
# SupportsRichComparisonT issue with List[Spec]
sorted_specs: List["Spec"] = sorted(specs) # type: ignore[type-var]
for d, dep_spec in spack.traverse.traverse_tree(
sorted_specs, cover=cover, deptype=deptypes, depth_first=depth_first, key=key
):
node = dep_spec.spec
if prefix is not None:
out += prefix(node)
out += " " * indent
if depth:
out += "%-4d" % d
if status_fn:
status = status_fn(node)
if status in list(InstallStatus):
out += clr.colorize(status.value, color=color)
elif status:
out += clr.colorize("@g{[+]} ", color=color)
else:
out += clr.colorize("@r{[-]} ", color=color)
if hashes:
out += clr.colorize("@K{%s} ", color=color) % node.dag_hash(hashlen)
if show_types:
if cover == "nodes":
depflag = deptype_lookup[dep_spec.spec.dag_hash()]
else:
# when covering edges or paths, we show dependency
# types only for the edge through which we visited
depflag = dep_spec.depflag
type_chars = dt.flag_to_chars(depflag)
out += "[%s] " % type_chars
out += " " * d
if d > 0:
out += "^"
out += node.format(format, color=color) + "\n"
# Check if we wanted just the first line
if not recurse_dependencies:
break
return out
| SpecBuildInterface |
python | pyodide__pyodide | src/py/pyodide/ffi/wrappers.py | {
"start": 714,
"end": 4116
} | class ____:
@staticmethod
def destroy():
pass
EVENT_LISTENERS: dict[
tuple[int, str, Callable[[Any], None]],
JsWeakRef[JsCallableDoubleProxy[[Any], None]],
] = {}
def add_event_listener(
elt: JsDomElement, event: str, listener: Callable[[Any], None]
) -> None:
"""Wrapper for JavaScript's
:js:meth:`~EventTarget.addEventListener` which automatically manages the lifetime of a
JsProxy corresponding to the ``listener`` parameter.
"""
proxy = create_proxy(listener)
# Use weakref so the proxy can be freed if DOM element is removed.
EVENT_LISTENERS[(elt.js_id, event, listener)] = proxy.to_weakref()
elt.addEventListener(event, cast(Callable[[Any], None], proxy))
def remove_event_listener(
elt: JsDomElement, event: str, listener: Callable[[Any], None]
) -> None:
"""Wrapper for JavaScript's
:js:meth:`~EventTarget.removeEventListener` which automatically manages the
lifetime of a JsProxy corresponding to the ``listener`` parameter.
"""
proxy = EVENT_LISTENERS.pop((elt.js_id, event, listener)).deref()
if proxy is None:
return
elt.removeEventListener(event, cast(Callable[[Any], None], proxy))
proxy.destroy()
TIMEOUTS: dict[int, Destroyable] = {}
def set_timeout(callback: Callable[[], None], timeout: int) -> int | JsProxy:
"""Wrapper for JavaScript's :js:func:`setTimeout` which
automatically manages the lifetime of a JsProxy corresponding to the
callback param.
"""
id = -1
def wrapper():
nonlocal id
callback()
TIMEOUTS.pop(id, None)
callable = create_once_callable(wrapper)
timeout_retval: int | JsProxy = setTimeout(callable, timeout)
id = timeout_retval if isinstance(timeout_retval, int) else timeout_retval.js_id
TIMEOUTS[id] = callable
return timeout_retval
def clear_timeout(timeout_retval: int | JsProxy) -> None:
"""Wrapper for JavaScript's :js:func:`clearTimeout` which
automatically manages the lifetime of a JsProxy corresponding to the
``callback`` parameter.
"""
clearTimeout(timeout_retval)
id = timeout_retval if isinstance(timeout_retval, int) else timeout_retval.js_id
TIMEOUTS.pop(id, DUMMY_DESTROYABLE).destroy()
INTERVAL_CALLBACKS: dict[int, Destroyable] = {}
def set_interval(callback: Callable[[], None], interval: int) -> int | JsProxy:
"""Wrapper for JavaScript's :js:func:`setInterval` which
automatically manages the lifetime of a JsProxy corresponding to the
``callback`` parameter.
"""
proxy = create_proxy(callback)
interval_retval = setInterval(cast(Callable[[], None], proxy), interval)
id = interval_retval if isinstance(interval_retval, int) else interval_retval.js_id
INTERVAL_CALLBACKS[id] = proxy
return interval_retval
def clear_interval(interval_retval: int | JsProxy) -> None:
"""Wrapper for JavaScript's :js:func:`clearInterval`
which automatically manages the lifetime of a JsProxy corresponding to
the ``callback`` parameter.
"""
clearInterval(interval_retval)
id = interval_retval if isinstance(interval_retval, int) else interval_retval.js_id
INTERVAL_CALLBACKS.pop(id, DUMMY_DESTROYABLE).destroy()
__all__ = [
"add_event_listener",
"remove_event_listener",
"set_timeout",
"clear_timeout",
"set_interval",
"clear_interval",
]
| DUMMY_DESTROYABLE |
python | django__django | tests/admin_scripts/another_app_waiting_migration/migrations/0001_initial.py | {
"start": 43,
"end": 606
} | class ____(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Foo",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("name", models.CharField(max_length=255)),
],
),
]
| Migration |
python | conda__conda | conda/gateways/connection/adapters/http.py | {
"start": 2755,
"end": 2825
} | class ____(_SSLContextAdapterMixin, BaseHTTPAdapter):
pass
| HTTPAdapter |
python | GoogleCloudPlatform__python-docs-samples | dialogflow-cx/streaming_detect_intent_infinite_test.py | {
"start": 1058,
"end": 1967
} | class ____:
def __init__(self: object, audio_filename: str) -> None:
self.audio_filename = audio_filename
self.streams = []
def __call__(self: object, *args: object) -> object:
return self
def open(
self: object,
rate: int,
input: bool = False,
output: bool = False,
stream_callback: object = None,
*args: object,
**kwargs: object,
) -> object:
stream = MockStream(self.audio_filename, rate, input, output, stream_callback)
self.streams.append(stream)
return stream
def get_default_input_device_info(self: object) -> dict:
return {"name": "input-device"}
def get_default_output_device_info(self: object) -> dict:
return {"name": "output-device"}
def terminate(self: object) -> None:
for stream in self.streams:
stream.close()
| MockPyAudio |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_data_labels13.py | {
"start": 315,
"end": 1408
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_data_labels13.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "pie"})
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
chart.add_series(
{
"values": "=Sheet1!$A$1:$A$5",
"data_labels": {
"value": 1,
"leader_lines": 1,
"position": "inside_end",
},
}
)
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | pyparsing__pyparsing | pyparsing/diagram/__init__.py | {
"start": 2983,
"end": 3224
} | class ____(railroad.Group):
"""
Simple subclass of Group that creates an annotation label
"""
def __init__(self, label: str, item) -> None:
super().__init__(item=item, label=f"[{label}]" if label else "")
| AnnotatedItem |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP024_3.py | {
"start": 0,
"end": 99
} | class ____(Exception):
pass
try:
raise SocketError()
except SocketError:
pass
| SocketError |
python | huggingface__transformers | utils/test_module/custom_video_processing.py | {
"start": 56,
"end": 123
} | class ____(LlavaOnevisionVideoProcessor):
pass
| CustomVideoProcessor |
python | facebook__pyre-check | client/language_server/protocol.py | {
"start": 13046,
"end": 13470
} | class ____(json_mixins.CamlCaseAndExcludeJsonMixin):
text_document: TextDocumentIdentifier
content_changes: List[ContentChange]
@staticmethod
def from_json_rpc_parameters(
parameters: json_rpc.Parameters,
) -> "DidChangeTextDocumentParameters":
return _parse_parameters(parameters, target=DidChangeTextDocumentParameters)
@dataclasses.dataclass(frozen=True)
| DidChangeTextDocumentParameters |
python | pypa__warehouse | warehouse/oidc/models/github.py | {
"start": 14140,
"end": 15777
} | class ____(GitHubPublisherMixin, PendingOIDCPublisher):
__tablename__ = "pending_github_oidc_publishers"
__mapper_args__ = {"polymorphic_identity": "pending_github_oidc_publishers"}
__table_args__ = ( # type: ignore[assignment]
UniqueConstraint(
"repository_name",
"repository_owner",
"workflow_filename",
"environment",
name="_pending_github_oidc_publisher_uc",
),
)
id: Mapped[UUID] = mapped_column(
PG_UUID(as_uuid=True), ForeignKey(PendingOIDCPublisher.id), primary_key=True
)
def reify(self, session: Session) -> GitHubPublisher:
"""
Returns a `GitHubPublisher` for this `PendingGitHubPublisher`,
deleting the `PendingGitHubPublisher` in the process.
"""
maybe_publisher = (
session.query(GitHubPublisher)
.filter(
GitHubPublisher.repository_name == self.repository_name,
GitHubPublisher.repository_owner == self.repository_owner,
GitHubPublisher.workflow_filename == self.workflow_filename,
GitHubPublisher.environment == self.environment,
)
.one_or_none()
)
publisher = maybe_publisher or GitHubPublisher(
repository_name=self.repository_name,
repository_owner=self.repository_owner,
repository_owner_id=self.repository_owner_id,
workflow_filename=self.workflow_filename,
environment=self.environment,
)
session.delete(self)
return publisher
| PendingGitHubPublisher |
python | Lightning-AI__lightning | tests/tests_fabric/utilities/test_load.py | {
"start": 1363,
"end": 4854
} | class ____(torch.Tensor):
pass
def test_lazy_load_tensor(tmp_path):
"""Test that lazy load can handle different classes of tensors."""
expected = {
"tensor": torch.rand(2),
"parameter": nn.Parameter(torch.rand(3)),
"subclass": torch.Tensor._make_subclass(ATensor, torch.rand(4)),
}
torch.save(expected, tmp_path / "data.pt")
loaded = _lazy_load(tmp_path / "data.pt")
for t0, t1 in zip(expected.values(), loaded.values()):
assert isinstance(t1, _NotYetLoadedTensor)
t1_materialized = _materialize_tensors(t1)
assert type(t0) == type(t1_materialized) # noqa: E721
assert torch.equal(t0, t1_materialized)
def test_lazy_load_mixed_state(tmp_path):
model0 = nn.Linear(2, 2)
optim0 = torch.optim.Adam(model0.parameters())
checkpoint = {
"int": 1,
"dict": {"a": 1, "b": 2},
"list": [1, 2, 3],
"pickled_model": model0,
"model": model0.state_dict(),
"optimizer": optim0.state_dict(),
}
torch.save(checkpoint, tmp_path / "checkpoint.pt")
model1 = nn.Linear(2, 2)
optim1 = torch.optim.Adam(model0.parameters())
loaded_checkpoint = _lazy_load(tmp_path / "checkpoint.pt")
model1.load_state_dict(loaded_checkpoint["model"])
optim1.load_state_dict(loaded_checkpoint["optimizer"])
def test_lazy_load_raises():
with pytest.raises(FileNotFoundError, match="foo' does not exist"):
_lazy_load("foo")
def test_materialize_tensors(tmp_path):
# Single tensor
tensor = torch.tensor([1, 2])
torch.save(tensor, tmp_path / "tensor.pt")
loaded = _lazy_load(tmp_path / "tensor.pt")
materialized = _materialize_tensors(loaded)
assert torch.equal(materialized, tensor)
assert type(tensor) == type(materialized) # noqa: E721
# Collection of tensors
collection = {
"tensor": torch.tensor([1, 2]),
"nested": {"int": 1, "list": [torch.tensor([3.0]), torch.tensor([4])]},
}
torch.save(collection, tmp_path / "collection.pt")
loaded = _lazy_load(tmp_path / "collection.pt")
materialized = _materialize_tensors(loaded)
assert torch.equal(materialized["tensor"], collection["tensor"])
assert torch.equal(materialized["nested"]["list"][0], collection["nested"]["list"][0])
assert torch.equal(materialized["nested"]["list"][1], collection["nested"]["list"][1])
assert materialized["nested"]["int"] == 1
def test_move_state_into():
# all keys from the source
source = {"apple": 1, "cocofruit": 2}
destination = {"banana": 100}
_move_state_into(source, destination)
assert source == {}
assert destination == {"apple": 1, "cocofruit": 2, "banana": 100}
# subset of keys from the source
source = {"apple": 1, "cocofruit": 2}
destination = {"banana": 100}
keys = {"apple"}
_move_state_into(source, destination, keys=keys)
assert source == {"cocofruit": 2}
assert destination == {"apple": 1, "banana": 100}
# with stateful objects in destination
class Fruit:
count = 1
def state_dict(self):
return {"count": self.count}
def load_state_dict(self, state_dict):
self.count = state_dict["count"]
source = {"cocofruit": 2, "banana": {"count": 100}}
destination = {"banana": Fruit()}
_move_state_into(source, destination)
assert source == {}
assert destination["cocofruit"] == 2
assert destination["banana"].count == 100
| ATensor |
python | sqlalchemy__sqlalchemy | test/orm/test_attributes.py | {
"start": 32041,
"end": 37417
} | class ____(fixtures.ORMTest):
def test_m2m(self):
class Student:
pass
class Course:
pass
instrumentation.register_class(Student)
instrumentation.register_class(Course)
_register_attribute(
Student,
"courses",
uselist=True,
backref="students",
useobject=True,
)
_register_attribute(
Course, "students", uselist=True, backref="courses", useobject=True
)
s = Student()
c = Course()
s.courses.append(c)
self.assert_(c.students == [s])
s.courses.remove(c)
self.assert_(c.students == [])
(s1, s2, s3) = (Student(), Student(), Student())
c.students = [s1, s2, s3]
self.assert_(s2.courses == [c])
self.assert_(s1.courses == [c])
s1.courses.remove(c)
self.assert_(c.students == [s2, s3])
def test_o2m(self):
class Post:
pass
class Blog:
pass
instrumentation.register_class(Post)
instrumentation.register_class(Blog)
_register_attribute(
Post,
"blog",
uselist=False,
backref="posts",
trackparent=True,
useobject=True,
)
_register_attribute(
Blog,
"posts",
uselist=True,
backref="blog",
trackparent=True,
useobject=True,
)
b = Blog()
(p1, p2, p3) = (Post(), Post(), Post())
b.posts.append(p1)
b.posts.append(p2)
b.posts.append(p3)
self.assert_(b.posts == [p1, p2, p3])
self.assert_(p2.blog is b)
p3.blog = None
self.assert_(b.posts == [p1, p2])
p4 = Post()
p4.blog = b
self.assert_(b.posts == [p1, p2, p4])
p4.blog = b
p4.blog = b
self.assert_(b.posts == [p1, p2, p4])
# assert no failure removing None
p5 = Post()
p5.blog = None
del p5.blog
def test_o2o(self):
class Port:
pass
class Jack:
pass
instrumentation.register_class(Port)
instrumentation.register_class(Jack)
_register_attribute(
Port, "jack", uselist=False, useobject=True, backref="port"
)
_register_attribute(
Jack, "port", uselist=False, useobject=True, backref="jack"
)
p = Port()
j = Jack()
p.jack = j
self.assert_(j.port is p)
self.assert_(p.jack is not None)
j.port = None
self.assert_(p.jack is None)
def test_symmetric_o2o_inheritance(self):
"""Test that backref 'initiator' catching goes against
a token that is global to all InstrumentedAttribute objects
within a particular class, not just the individual IA object
since we use distinct objects in an inheritance scenario.
"""
class Parent:
pass
class Child:
pass
class SubChild(Child):
pass
p_token = object()
c_token = object()
instrumentation.register_class(Parent)
instrumentation.register_class(Child)
instrumentation.register_class(SubChild)
_register_attribute(
Parent,
"child",
uselist=False,
backref="parent",
parent_token=p_token,
useobject=True,
)
_register_attribute(
Child,
"parent",
uselist=False,
backref="child",
parent_token=c_token,
useobject=True,
)
_register_attribute(
SubChild,
"parent",
uselist=False,
backref="child",
parent_token=c_token,
useobject=True,
)
p1 = Parent()
c1 = Child()
p1.child = c1
c2 = SubChild()
c2.parent = p1
def test_symmetric_o2m_inheritance(self):
class Parent:
pass
class SubParent(Parent):
pass
class Child:
pass
p_token = object()
c_token = object()
instrumentation.register_class(Parent)
instrumentation.register_class(SubParent)
instrumentation.register_class(Child)
_register_attribute(
Parent,
"children",
uselist=True,
backref="parent",
parent_token=p_token,
useobject=True,
)
_register_attribute(
SubParent,
"children",
uselist=True,
backref="parent",
parent_token=p_token,
useobject=True,
)
_register_attribute(
Child,
"parent",
uselist=False,
backref="children",
parent_token=c_token,
useobject=True,
)
p1 = Parent()
p2 = SubParent()
c1 = Child()
p1.children.append(c1)
assert c1.parent is p1
assert c1 in p1.children
p2.children.append(c1)
assert c1.parent is p2
# event propagates to remove as of [ticket:2789]
assert c1 not in p1.children
| BackrefTest |
python | django__django | tests/from_db_value/models.py | {
"start": 99,
"end": 427
} | class ____(models.DecimalField):
def __init__(self, **kwargs):
kwargs["max_digits"] = 20
kwargs["decimal_places"] = 2
super().__init__(**kwargs)
def from_db_value(self, value, expression, connection):
cash = Cash(value)
cash.vendor = connection.vendor
return cash
| CashField |
python | pypa__warehouse | tests/unit/admin/views/test_organizations.py | {
"start": 57463,
"end": 62273
} | class ____:
@pytest.mark.usefixtures("_enable_organizations")
def test_set_upload_limit_with_integer(self, db_request):
organization = OrganizationFactory.create(name="foo")
db_request.route_path = pretend.call_recorder(
lambda a, organization_id: "/admin/organizations/1/"
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.matchdict["organization_id"] = organization.id
db_request.POST = MultiDict({"upload_limit": "150"})
result = views.set_upload_limit(db_request)
assert db_request.session.flash.calls == [
pretend.call("Upload limit set to 150.0MiB", queue="success")
]
assert result.status_code == 303
assert result.location == "/admin/organizations/1/"
assert organization.upload_limit == 150 * views.ONE_MIB
@pytest.mark.usefixtures("_enable_organizations")
def test_set_upload_limit_with_none(self, db_request):
organization = OrganizationFactory.create(name="foo")
organization.upload_limit = 150 * views.ONE_MIB
db_request.route_path = pretend.call_recorder(
lambda a, organization_id: "/admin/organizations/1/"
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.matchdict["organization_id"] = organization.id
db_request.POST = MultiDict({"upload_limit": ""})
result = views.set_upload_limit(db_request)
assert db_request.session.flash.calls == [
pretend.call("Upload limit set to (default)", queue="success")
]
assert result.status_code == 303
assert result.location == "/admin/organizations/1/"
assert organization.upload_limit is None
@pytest.mark.usefixtures("_enable_organizations")
def test_set_upload_limit_invalid_value(self, db_request):
organization = OrganizationFactory.create(name="foo")
db_request.route_path = pretend.call_recorder(
lambda a, organization_id: "/admin/organizations/1/"
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.matchdict["organization_id"] = organization.id
db_request.POST = MultiDict({"upload_limit": "not_an_integer"})
result = views.set_upload_limit(db_request)
assert db_request.session.flash.calls == [
pretend.call(
"upload_limit: Upload limit must be a valid integer or empty",
queue="error",
)
]
assert result.status_code == 303
@pytest.mark.usefixtures("_enable_organizations")
def test_set_upload_limit_not_found(self, db_request):
db_request.matchdict["organization_id"] = "00000000-0000-0000-0000-000000000000"
with pytest.raises(HTTPNotFound):
views.set_upload_limit(db_request)
@pytest.mark.usefixtures("_enable_organizations")
def test_set_upload_limit_above_cap(self, db_request):
organization = OrganizationFactory.create(name="foo")
db_request.route_path = pretend.call_recorder(
lambda a, organization_id: "/admin/organizations/1/"
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.matchdict["organization_id"] = organization.id
db_request.POST = MultiDict({"upload_limit": "2048"}) # 2048 MiB > 1024 MiB cap
result = views.set_upload_limit(db_request)
assert db_request.session.flash.calls == [
pretend.call(
"upload_limit: Upload limit can not be greater than 1024.0MiB",
queue="error",
)
]
assert result.status_code == 303
@pytest.mark.usefixtures("_enable_organizations")
def test_set_upload_limit_below_default(self, db_request):
organization = OrganizationFactory.create(name="foo")
db_request.route_path = pretend.call_recorder(
lambda a, organization_id: "/admin/organizations/1/"
)
db_request.session = pretend.stub(
flash=pretend.call_recorder(lambda *a, **kw: None)
)
db_request.matchdict["organization_id"] = organization.id
db_request.POST = MultiDict({"upload_limit": "50"}) # 50 MiB < 100 MiB default
result = views.set_upload_limit(db_request)
assert db_request.session.flash.calls == [
pretend.call(
"upload_limit: Upload limit can not be less than 100.0MiB",
queue="error",
)
]
assert result.status_code == 303
| TestSetUploadLimit |
python | ansible__ansible | lib/ansible/utils/_junit_xml.py | {
"start": 1493,
"end": 1721
} | class ____(TestResult):
"""Error info for a test case."""
@property
def tag(self) -> str:
"""Tag name for the XML element created by this result type."""
return 'error'
@dataclasses.dataclass
| TestError |
python | chardet__chardet | chardet/mbcsgroupprober.py | {
"start": 1592,
"end": 2065
} | class ____(CharSetGroupProber):
def __init__(self, lang_filter: LanguageFilter = LanguageFilter.NONE) -> None:
super().__init__(lang_filter=lang_filter)
self.probers = [
UTF8Prober(),
SJISProber(),
EUCJPProber(),
GB2312Prober(),
EUCKRProber(),
CP949Prober(),
Big5Prober(),
EUCTWProber(),
JOHABProber(),
]
self.reset()
| MBCSGroupProber |
python | pypa__warehouse | tests/unit/accounts/test_forms.py | {
"start": 43337,
"end": 47530
} | class ____:
def test_validate(self, monkeypatch):
request = pretend.stub(remote_addr=REMOTE_ADDR)
user = pretend.stub(id=pretend.stub(), username="foobar")
user_service = pretend.stub(
check_recovery_code=pretend.call_recorder(lambda *a, **kw: True),
get_user=lambda _: user,
)
form = forms.RecoveryCodeAuthenticationForm(
formdata=MultiDict({"recovery_code_value": "deadbeef00001111"}),
request=request,
user_id=user.id,
user_service=user_service,
)
send_recovery_code_used_email = pretend.call_recorder(
lambda request, user: None
)
monkeypatch.setattr(
forms, "send_recovery_code_used_email", send_recovery_code_used_email
)
assert form.request is request
assert form.user_id is user.id
assert form.user_service is user_service
assert form.validate()
assert send_recovery_code_used_email.calls == [pretend.call(request, user)]
def test_missing_value(self):
request = pretend.stub()
form = forms.RecoveryCodeAuthenticationForm(
formdata=MultiDict({"recovery_code_value": ""}),
request=request,
user_id=pretend.stub(),
user_service=pretend.stub(),
)
assert not form.validate()
assert form.recovery_code_value.errors.pop() == "This field is required."
@pytest.mark.parametrize(
("exception", "expected_reason", "expected_error"),
[
(InvalidRecoveryCode, "invalid_recovery_code", "Invalid recovery code."),
(NoRecoveryCodes, "invalid_recovery_code", "Invalid recovery code."),
(
BurnedRecoveryCode,
"burned_recovery_code",
"Recovery code has been previously used.",
),
],
)
def test_invalid_recovery_code(
self, pyramid_config, exception, expected_reason, expected_error
):
request = pretend.stub(remote_addr="127.0.0.1")
user = pretend.stub(
record_event=pretend.call_recorder(lambda *a, **kw: None),
)
user_service = pretend.stub(
check_recovery_code=pretend.raiser(exception),
get_user=pretend.call_recorder(lambda userid: user),
)
form = forms.RecoveryCodeAuthenticationForm(
formdata=MultiDict({"recovery_code_value": "deadbeef00001111"}),
request=request,
user_id=1,
user_service=user_service,
)
assert not form.validate()
assert str(form.recovery_code_value.errors.pop()) == expected_error
assert user.record_event.calls == [
pretend.call(
tag=EventTag.Account.LoginFailure,
request=request,
additional={"reason": expected_reason},
)
]
@pytest.mark.parametrize(
("input_string", "validates"),
[
(" deadbeef00001111 ", True),
("deadbeef00001111 ", True),
(" deadbeef00001111", True),
("deadbeef00001111", True),
("wu-tang", False),
("deadbeef00001111 deadbeef11110000", False),
],
)
def test_recovery_code_string_validation(
self, monkeypatch, input_string, validates
):
request = pretend.stub(remote_addr="127.0.0.1")
user = pretend.stub(id=pretend.stub(), username="foobar")
form = forms.RecoveryCodeAuthenticationForm(
request=request,
formdata=MultiDict({"recovery_code_value": input_string}),
user_id=pretend.stub(),
user_service=pretend.stub(
check_recovery_code=pretend.call_recorder(lambda *a, **kw: True),
get_user=lambda _: user,
),
)
send_recovery_code_used_email = pretend.call_recorder(
lambda request, user: None
)
monkeypatch.setattr(
forms, "send_recovery_code_used_email", send_recovery_code_used_email
)
assert form.validate() == validates
| TestRecoveryCodeForm |
python | Textualize__textual | docs/examples/guide/layout/grid_layout6_row_span.py | {
"start": 80,
"end": 572
} | class ____(App):
CSS_PATH = "grid_layout6_row_span.tcss"
def compose(self) -> ComposeResult:
yield Static("One", classes="box")
yield Static("Two [b](column-span: 2 and row-span: 2)", classes="box", id="two")
yield Static("Three", classes="box")
yield Static("Four", classes="box")
yield Static("Five", classes="box")
yield Static("Six", classes="box")
app = GridLayoutExample()
if __name__ == "__main__":
app.run()
| GridLayoutExample |
python | allegroai__clearml | clearml/backend_api/services/v2_13/tasks.py | {
"start": 85212,
"end": 87894
} | class ____(Request):
"""
Archive tasks.
If a task is queued it will first be dequeued and then archived.
:param tasks: List of task ids
:type tasks: Sequence[str]
:param status_reason: Reason for status change
:type status_reason: str
:param status_message: Extra information regarding status change
:type status_message: str
"""
_service = "tasks"
_action = "archive"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"status_message": {
"description": "Extra information regarding status change",
"type": "string",
},
"status_reason": {
"description": "Reason for status change",
"type": "string",
},
"tasks": {
"description": "List of task ids",
"items": {"type": "string"},
"type": "array",
},
},
"required": ["tasks"],
"type": "object",
}
def __init__(
self, tasks: List[str], status_reason: Optional[str] = None, status_message: Optional[str] = None, **kwargs: Any
) -> None:
super(ArchiveRequest, self).__init__(**kwargs)
self.tasks = tasks
self.status_reason = status_reason
self.status_message = status_message
@schema_property("tasks")
def tasks(self) -> List[str]:
return self._property_tasks
@tasks.setter
def tasks(self, value: List[str]) -> None:
if value is None:
self._property_tasks = None
return
self.assert_isinstance(value, "tasks", (list, tuple))
self.assert_isinstance(value, "tasks", six.string_types, is_array=True)
self._property_tasks = value
@schema_property("status_reason")
def status_reason(self) -> Optional[str]:
return self._property_status_reason
@status_reason.setter
def status_reason(self, value: Optional[str]) -> None:
if value is None:
self._property_status_reason = None
return
self.assert_isinstance(value, "status_reason", six.string_types)
self._property_status_reason = value
@schema_property("status_message")
def status_message(self) -> Optional[str]:
return self._property_status_message
@status_message.setter
def status_message(self, value: Optional[str]) -> None:
if value is None:
self._property_status_message = None
return
self.assert_isinstance(value, "status_message", six.string_types)
self._property_status_message = value
| ArchiveRequest |
python | pytorch__pytorch | torch/distributed/elastic/rendezvous/etcd_rendezvous.py | {
"start": 1435,
"end": 1635
} | class ____(Exception):
pass
# Similar to retryable failure, but the new state we observed suggests we
# can re-try immediately, i.e. without a need for "safety delay".
| EtcdRendezvousRetryableFailure |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.