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 | jmcnamara__XlsxWriter | xlsxwriter/styles.py | {
"start": 329,
"end": 553
} | class ____(Enum):
"""
Enum to distinguish the type of cell xf format since style and the default
(the first format) are handled slightly differently.
"""
USER = 1
STYLE = 2
DEFAULT = 3
| XFormatType |
python | tornadoweb__tornado | demos/chat/chatdemo.py | {
"start": 2569,
"end": 4112
} | class ____(tornado.web.RequestHandler):
"""Long-polling request for new messages.
Waits until new messages are available before returning anything.
"""
async def post(self):
cursor = self.get_argument("cursor", None)
messages = global_message_buffer.get_messages_since(cursor)
while not messages:
# Save the Future returned here so we can cancel it in
# on_connection_close.
self.wait_future = global_message_buffer.cond.wait()
try:
await self.wait_future
except asyncio.CancelledError:
return
messages = global_message_buffer.get_messages_since(cursor)
if self.request.connection.stream.closed():
return
self.write(dict(messages=messages))
def on_connection_close(self):
self.wait_future.cancel()
async def main():
parse_command_line()
app = tornado.web.Application(
[
(r"/", MainHandler),
(r"/a/message/new", MessageNewHandler),
(r"/a/message/updates", MessageUpdatesHandler),
],
cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
xsrf_cookies=True,
debug=options.debug,
)
app.listen(options.port)
await asyncio.Event().wait()
if __name__ == "__main__":
asyncio.run(main())
| MessageUpdatesHandler |
python | numba__llvmlite | llvmlite/ir/values.py | {
"start": 28386,
"end": 30655
} | class ____(AttributeSet):
# List from
# https://releases.llvm.org/14.0.0/docs/LangRef.html#parameter-attributes
_known = MappingProxyType({
# True (emit type),
# False (emit name only)
'byref': True,
'byval': True,
'elementtype': True,
'immarg': False,
'inalloca': True,
'inreg': False,
'nest': False,
'noalias': False,
'nocapture': False,
'nofree': False,
'nonnull': False,
'noundef': False,
'preallocated': True,
'returned': False,
'signext': False,
'sret': True,
'swiftasync': False,
'swifterror': False,
'swiftself': False,
'zeroext': False,
})
def __init__(self, args=()):
self._align = 0
self._dereferenceable = 0
self._dereferenceable_or_null = 0
super(ArgumentAttributes, self).__init__(args)
def _expand(self, name, typ):
requires_type = self._known.get(name)
if requires_type:
return f"{name}({typ.pointee})"
else:
return name
@property
def align(self):
return self._align
@align.setter
def align(self, val):
assert isinstance(val, int) and val >= 0
self._align = val
@property
def dereferenceable(self):
return self._dereferenceable
@dereferenceable.setter
def dereferenceable(self, val):
assert isinstance(val, int) and val >= 0
self._dereferenceable = val
@property
def dereferenceable_or_null(self):
return self._dereferenceable_or_null
@dereferenceable_or_null.setter
def dereferenceable_or_null(self, val):
assert isinstance(val, int) and val >= 0
self._dereferenceable_or_null = val
def _to_list(self, typ):
attrs = super()._to_list(typ)
if self.align:
attrs.append('align {0:d}'.format(self.align))
if self.dereferenceable:
attrs.append('dereferenceable({0:d})'.format(self.dereferenceable))
if self.dereferenceable_or_null:
dref = 'dereferenceable_or_null({0:d})'
attrs.append(dref.format(self.dereferenceable_or_null))
return attrs
| ArgumentAttributes |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip.py | {
"start": 5697,
"end": 7025
} | class ____(ModelOutput):
r"""
itm_score (`torch.FloatTensor`):
The image-text similarity scores.
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss from the text decoder.
image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
The image embeddings obtained by applying the projection layer to the pooler_output.
vision_pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*):
Last layer hidden-state of the vision of the vision-only branch of the model.
question_embeds (`torch.FloatTensor`):
The question embeddings obtained by the text projection layer.
"""
itm_score: Optional[torch.FloatTensor] = None
loss: Optional[torch.FloatTensor] = None
image_embeds: Optional[torch.FloatTensor] = None
last_hidden_state: Optional[torch.FloatTensor] = None
hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
vision_pooler_output: Optional[torch.FloatTensor] = None
attentions: Optional[tuple[torch.FloatTensor, ...]] = None
question_embeds: Optional[tuple[torch.FloatTensor]] = None
@dataclass
@auto_docstring
| BlipImageTextMatchingModelOutput |
python | dagster-io__dagster | python_modules/dagster/dagster/_config/evaluate_value_result.py | {
"start": 318,
"end": 1390
} | class ____(Generic[T]):
success: bool
value: Optional[T]
errors: Optional[Sequence[EvaluationError]]
@staticmethod
def for_error(error: EvaluationError) -> "EvaluateValueResult[Any]":
return EvaluateValueResult(success=False, value=None, errors=[error])
@staticmethod
def for_errors(errors: Sequence[EvaluationError]) -> "EvaluateValueResult[Any]":
return EvaluateValueResult(success=False, value=None, errors=errors)
@staticmethod
def for_value(value: T) -> "EvaluateValueResult[T]":
return EvaluateValueResult(success=True, value=value, errors=None)
def errors_at_level(self, *levels: str) -> Sequence[EvaluationError]:
return list(self._iterate_errors_at_level(list(levels)))
def _iterate_errors_at_level(
self, levels: Sequence[str]
) -> Generator[EvaluationError, None, None]:
check.sequence_param(levels, "levels", of_type=str)
for error in check.is_list(self.errors):
if error.stack.levels == levels:
yield error
| EvaluateValueResult |
python | getsentry__sentry | tests/sentry/relocation/tasks/test_transfer.py | {
"start": 3629,
"end": 5419
} | class ____(TestCase):
@patch("sentry.relocation.tasks.transfer.process_relocation_transfer_region")
def test_no_records(self, mock_process: MagicMock) -> None:
find_relocation_transfer_region()
assert not mock_process.delay.called
@patch("sentry.relocation.tasks.transfer.process_relocation_transfer_region")
def test_no_due_records(self, mock_process: MagicMock) -> None:
create_region_relocation_transfer(
organization=self.organization, scheduled_for=timezone.now() + timedelta(minutes=2)
)
find_relocation_transfer_region()
assert not mock_process.delay.called
@patch("sentry.relocation.tasks.transfer.process_relocation_transfer_region")
def test_due_records(self, mock_process: MagicMock) -> None:
transfer = create_region_relocation_transfer(
organization=self.organization, scheduled_for=timezone.now() - timedelta(minutes=2)
)
find_relocation_transfer_region()
assert mock_process.delay.called
transfer.refresh_from_db()
assert transfer.scheduled_for > timezone.now()
@patch("sentry.relocation.tasks.transfer.process_relocation_transfer_region")
def test_purge_expired(self, mock_process: MagicMock) -> None:
transfer = create_region_relocation_transfer(
organization=self.organization,
scheduled_for=timezone.now() - timedelta(minutes=2),
)
transfer.date_added = timezone.now() - timedelta(hours=1, minutes=2)
transfer.save()
find_relocation_transfer_region()
assert not mock_process.delay.called
assert not RegionRelocationTransfer.objects.filter(id=transfer.id).exists()
@control_silo_test(regions=TEST_REGIONS)
| FindRelocationTransferRegionTest |
python | kamyu104__LeetCode-Solutions | Python/next-greater-element-i.py | {
"start": 37,
"end": 494
} | class ____(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
stk, lookup = [], {}
for num in nums:
while stk and num > stk[-1]:
lookup[stk.pop()] = num
stk.append(num)
while stk:
lookup[stk.pop()] = -1
return map(lambda x : lookup[x], findNums)
| Solution |
python | walkccc__LeetCode | solutions/2233. Maximum Product After K Increments/2233.py | {
"start": 0,
"end": 358
} | class ____:
def maximumProduct(self, nums: list[int], k: int) -> int:
MOD = 1_000_000_007
ans = 1
minHeap = nums.copy()
heapq.heapify(minHeap)
for _ in range(k):
minNum = heapq.heappop(minHeap)
heapq.heappush(minHeap, minNum + 1)
while minHeap:
ans *= heapq.heappop(minHeap)
ans %= MOD
return ans
| Solution |
python | getsentry__sentry | src/sentry/api/serializers/models/project_transaction_threshold.py | {
"start": 248,
"end": 744
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs):
return {
"id": str(obj.id),
"threshold": str(obj.threshold),
"metric": TRANSACTION_METRICS[obj.metric],
"projectId": str(obj.project_id),
"editedBy": str(obj.edited_by_id),
"dateUpdated": obj.date_updated,
"dateAdded": obj.date_added,
}
@register(ProjectTransactionThresholdOverride)
| ProjectTransactionThresholdSerializer |
python | pytorch__pytorch | torch/nn/utils/rnn.py | {
"start": 753,
"end": 23409
} | class ____(PackedSequence_):
r"""Holds the data and list of :attr:`batch_sizes` of a packed sequence.
All RNN modules accept packed sequences as inputs.
Note:
Instances of this class should never be created manually. They are meant
to be instantiated by functions like :func:`pack_padded_sequence`.
Batch sizes represent the number elements at each sequence step in
the batch, not the varying sequence lengths passed to
:func:`pack_padded_sequence`. For instance, given data ``abc`` and ``x``
the :class:`PackedSequence` would contain data ``axbc`` with
``batch_sizes=[2,1,1]``.
Attributes:
data (Tensor): Tensor containing packed sequence
batch_sizes (Tensor): Tensor of integers holding
information about the batch size at each sequence step
sorted_indices (Tensor, optional): Tensor of integers holding how this
:class:`PackedSequence` is constructed from sequences.
unsorted_indices (Tensor, optional): Tensor of integers holding how this
to recover the original sequences with correct order.
.. note::
:attr:`data` can be on arbitrary device and of arbitrary dtype.
:attr:`sorted_indices` and :attr:`unsorted_indices` must be ``torch.int64``
tensors on the same device as :attr:`data`.
However, :attr:`batch_sizes` should always be a CPU ``torch.int64`` tensor.
This invariant is maintained throughout :class:`PackedSequence` class,
and all functions that construct a :class:`PackedSequence` in PyTorch
(i.e., they only pass in tensors conforming to this constraint).
"""
def __new__(
cls,
data: Tensor,
batch_sizes: Tensor | None = None,
sorted_indices: Tensor | None = None,
unsorted_indices: Tensor | None = None,
) -> Self:
return super().__new__(
cls,
*_packed_sequence_init_args(
data, batch_sizes, sorted_indices, unsorted_indices
),
)
# NOTE [ device and dtype of a PackedSequence ]
#
# See the note above in doc string (starting with ":attr:`data` can be on
# arbitrary device...").
def pin_memory(self) -> Self:
# Why not convert `batch_sizes`?
# See NOTE [ device and dtype of a PackedSequence ]
return type(self)(
self.data.pin_memory(),
self.batch_sizes,
bind(self.sorted_indices, lambda t: t.pin_memory()),
bind(self.unsorted_indices, lambda t: t.pin_memory()),
)
@overload
def to(
self,
dtype: torch.dtype,
non_blocking: bool = ...,
copy: bool = ...,
) -> Self: ...
@overload
def to(
self,
device: str | torch.device | int | None = ...,
dtype: torch.dtype | None = ...,
non_blocking: bool = ...,
copy: bool = ...,
) -> Self: ...
@overload
def to(
self,
other: Tensor,
non_blocking: bool = ...,
copy: bool = ...,
) -> Self: ...
def to(self, *args: Any, **kwargs: Any) -> Self:
r"""Perform dtype and/or device conversion on `self.data`.
It has similar signature as :meth:`torch.Tensor.to`, except optional
arguments like `non_blocking` and `copy` should be passed as kwargs,
not args, or they will not apply to the index tensors.
.. note::
If the ``self.data`` Tensor already has the correct :class:`torch.dtype`
and :class:`torch.device`, then ``self`` is returned.
Otherwise, returns a copy with the desired configuration.
"""
# Why not convert `batch_sizes`?
# See NOTE [ device and dtype of a PackedSequence ]
data = self.data.to(*args, **kwargs)
if data is self.data:
return self
else:
# Does not forward device or dtype arg/kwargs, device is set from data.device
kwargs = dict(
filter(lambda t: t[0] != "device" and t[0] != "dtype", kwargs.items())
)
sorted_indices = bind(
self.sorted_indices, lambda t: t.to(data.device, **kwargs)
)
unsorted_indices = bind(
self.unsorted_indices, lambda t: t.to(data.device, **kwargs)
)
return type(self)(data, self.batch_sizes, sorted_indices, unsorted_indices)
def cuda(self, *args: Any, **kwargs: Any) -> Self:
# Tests to see if 'cuda' should be added to kwargs
ex = torch.tensor((), dtype=self.data.dtype, device=self.data.device).to(
*args, **kwargs
)
if ex.is_cuda:
return self.to(*args, **kwargs)
kwargs["device"] = "cuda"
return self.to(*args, **kwargs)
def cpu(self, *args: Any, **kwargs: Any) -> Self:
ex = torch.tensor((), dtype=self.data.dtype, device=self.data.device).to(
*args, **kwargs
)
if ex.device.type == "cpu":
return self.to(*args, **kwargs)
kwargs["device"] = "cpu"
return self.to(*args, **kwargs)
def double(self) -> Self:
return self.to(dtype=torch.double)
def float(self) -> Self:
return self.to(dtype=torch.float)
def half(self) -> Self:
return self.to(dtype=torch.half)
def long(self) -> Self:
return self.to(dtype=torch.long)
def int(self) -> Self:
return self.to(dtype=torch.int)
def short(self) -> Self:
return self.to(dtype=torch.short)
def char(self) -> Self:
return self.to(dtype=torch.int8)
def byte(self) -> Self:
return self.to(dtype=torch.uint8)
@property
def is_cuda(self) -> bool:
r"""Return true if `self.data` stored on a gpu."""
return self.data.is_cuda
def is_pinned(self) -> bool:
r"""Return true if `self.data` stored on in pinned memory."""
return self.data.is_pinned()
# TorchScript doesn't support constructors on named tuples, so we use this helper
# method to construct PackedSequence
def _packed_sequence_init_args(
data: Tensor,
batch_sizes: Tensor | None = None,
sorted_indices: Tensor | None = None,
unsorted_indices: Tensor | None = None,
) -> tuple[Tensor, Tensor, Tensor | None, Tensor | None]:
# NB: if unsorted_indices is provided, it should be the inverse permutation
# to sorted_indices. Don't assert it here because the PackedSequence ctor
# should only be used internally.
if unsorted_indices is None:
unsorted_indices = invert_permutation(sorted_indices)
# support being called as `PackedSequence(data, batch_sizes, sorted_indices)`
if batch_sizes is not None:
# TODO: Re-enable this check (.type isn't supported in TorchScript)
if batch_sizes.device.type != "cpu":
raise ValueError(
"batch_sizes should always be on CPU. "
"Instances of PackedSequence should never be created manually. "
"They should be instantiated by functions like pack_sequence "
"and pack_padded_sequences in nn.utils.rnn. "
"https://pytorch.org/docs/stable/nn.html#torch.nn.utils.rnn.pack_sequence"
)
return data, batch_sizes, sorted_indices, unsorted_indices
# support being called as `PackedSequence((data, batch_sizes), *, sorted_indices)`
else:
assert isinstance(data, (list, tuple)) and len(data) == 2
return data[0], data[1], sorted_indices, unsorted_indices
def _packed_sequence_init(
data: Tensor,
batch_sizes: Tensor | None = None,
sorted_indices: Tensor | None = None,
unsorted_indices: Tensor | None = None,
) -> PackedSequence:
data, batch_sizes, sorted_indices, unsorted_indices = _packed_sequence_init_args(
data, batch_sizes, sorted_indices, unsorted_indices
)
return PackedSequence(data, batch_sizes, sorted_indices, unsorted_indices)
def invert_permutation(permutation: Tensor | None) -> Tensor | None:
"""Returns the inverse of ``permutation``.
This is useful for converting between sorted and unsorted indices in
a :class:`~nn.utils.rnn.PackedSequence`.
Args:
permutation (Tensor, optional): a 1-D tensor of indices to invert
"""
if permutation is None:
return None
output = torch.empty_like(permutation, memory_format=torch.legacy_contiguous_format)
output.scatter_(
0, permutation, torch.arange(0, permutation.numel(), device=permutation.device)
)
return output
def pack_padded_sequence(
input: Tensor,
lengths: Tensor | list[int],
batch_first: bool = False,
enforce_sorted: bool = True,
) -> PackedSequence:
r"""Packs a Tensor containing padded sequences of variable length.
:attr:`input` can be of size ``T x B x *`` (if :attr:`batch_first` is ``False``)
or ``B x T x *`` (if :attr:`batch_first` is ``True``) where ``T`` is the length
of the longest sequence, ``B`` is the batch size, and ``*`` is any number of dimensions
(including 0).
For unsorted sequences, use `enforce_sorted = False`. If :attr:`enforce_sorted` is
``True``, the sequences should be sorted by length in a decreasing order, i.e.
``input[:,0]`` should be the longest sequence, and ``input[:,B-1]`` the shortest
one. `enforce_sorted = True` is only necessary for ONNX export.
It is an inverse operation to :func:`pad_packed_sequence`, and hence :func:`pad_packed_sequence`
can be used to recover the underlying tensor packed in :class:`PackedSequence`.
Note:
This function accepts any input that has at least two dimensions. You
can apply it to pack the labels, and use the output of the RNN with
them to compute the loss directly. A Tensor can be retrieved from
a :class:`PackedSequence` object by accessing its ``.data`` attribute.
Args:
input (Tensor): padded batch of variable length sequences.
lengths (Tensor or list(int)): list of sequence lengths of each batch
element (must be on the CPU if provided as a tensor).
batch_first (bool, optional): if ``True``, the input is expected in ``B x T x *``
format, ``T x B x *`` otherwise. Default: ``False``.
enforce_sorted (bool, optional): if ``True``, the input is expected to
contain sequences sorted by length in a decreasing order. If
``False``, the input will get sorted unconditionally. Default: ``True``.
.. warning::
The dim of ``input`` tensor will be truncated if its length larger than
correspond value in ``length``.
Returns:
a :class:`PackedSequence` object
"""
if not isinstance(lengths, torch.Tensor):
if torch._C._get_tracing_state():
warnings.warn(
"pack_padded_sequence has been called with a Python list of "
"sequence lengths. The tracer cannot track the data flow of Python "
"values, and it will treat them as constants, likely rendering "
"the trace incorrect for any other combination of lengths.",
stacklevel=2,
)
lengths = torch.as_tensor(lengths, dtype=torch.int64, device="cpu")
else:
lengths = lengths.to(dtype=torch.int64)
if enforce_sorted:
sorted_indices = None
else:
lengths, sorted_indices = torch.sort(lengths, descending=True)
sorted_indices = sorted_indices.to(input.device)
batch_dim = 0 if batch_first else 1
input = input.index_select(batch_dim, sorted_indices)
data, batch_sizes = _VF._pack_padded_sequence(input, lengths, batch_first)
return _packed_sequence_init(data, batch_sizes, sorted_indices, None)
def pad_packed_sequence(
sequence: PackedSequence,
batch_first: bool = False,
padding_value: float = 0.0,
total_length: int | None = None,
) -> tuple[Tensor, Tensor]:
r"""Pad a packed batch of variable length sequences.
It is an inverse operation to :func:`pack_padded_sequence`.
The returned Tensor's data will be of size ``T x B x *`` (if :attr:`batch_first` is ``False``)
or ``B x T x *`` (if :attr:`batch_first` is ``True``) , where ``T`` is the length of the longest
sequence and ``B`` is the batch size.
Example:
>>> from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
>>> seq = torch.tensor([[1, 2, 0], [3, 0, 0], [4, 5, 6]])
>>> lens = [2, 1, 3]
>>> packed = pack_padded_sequence(
... seq, lens, batch_first=True, enforce_sorted=False
... )
>>> packed
PackedSequence(data=tensor([4, 1, 3, 5, 2, 6]), batch_sizes=tensor([3, 2, 1]),
sorted_indices=tensor([2, 0, 1]), unsorted_indices=tensor([1, 2, 0]))
>>> seq_unpacked, lens_unpacked = pad_packed_sequence(packed, batch_first=True)
>>> seq_unpacked
tensor([[1, 2, 0],
[3, 0, 0],
[4, 5, 6]])
>>> lens_unpacked
tensor([2, 1, 3])
.. note::
:attr:`total_length` is useful to implement the
``pack sequence -> recurrent network -> unpack sequence`` pattern in a
:class:`~torch.nn.Module` wrapped in :class:`~torch.nn.DataParallel`.
See :ref:`this FAQ section <pack-rnn-unpack-with-data-parallelism>` for
details.
Args:
sequence (PackedSequence): batch to pad
batch_first (bool, optional): if ``True``, the output will be in ``B x T x *``
format, ``T x B x *`` otherwise.
padding_value (float, optional): values for padded elements.
total_length (int, optional): if not ``None``, the output will be padded to
have length :attr:`total_length`. This method will throw :class:`ValueError`
if :attr:`total_length` is less than the max sequence length in
:attr:`sequence`.
Returns:
Tuple of Tensor containing the padded sequence, and a Tensor
containing the list of lengths of each sequence in the batch.
Batch elements will be re-ordered as they were ordered originally when
the batch was passed to ``pack_padded_sequence`` or ``pack_sequence``.
"""
max_seq_length = sequence.batch_sizes.size(0)
if total_length is not None:
if total_length < max_seq_length:
raise ValueError(
"Expected total_length to be at least the length "
"of the longest sequence in input, but got "
f"total_length={total_length} and max sequence length being {max_seq_length}"
)
max_seq_length = total_length
padded_output, lengths = _VF._pad_packed_sequence(
sequence.data, sequence.batch_sizes, batch_first, padding_value, max_seq_length
)
unsorted_indices = sequence.unsorted_indices
if unsorted_indices is not None:
batch_dim = 0 if batch_first else 1
return (
padded_output.index_select(batch_dim, unsorted_indices),
lengths[unsorted_indices.cpu()],
)
return padded_output, lengths
# NOTE: for JIT-compatibility, we need to be more restrictive here and use specific types instead of Iterable.
def pad_sequence(
sequences: Tensor | list[Tensor],
batch_first: bool = False,
padding_value: float = 0.0,
padding_side: str = "right",
) -> Tensor:
r"""Pad a list of variable length Tensors with :attr:`padding_value`.
``pad_sequence`` stacks a list of Tensors along a new dimension, and pads them
to equal length. :attr:`sequences` can be list of sequences with size ``L x *``,
where `L` is length of the sequence and ``*`` is any number of dimensions
(including ``0``). If :attr:`batch_first` is ``False``, the output is of size
``T x B x *``, and ``B x T x *`` otherwise, where ``B`` is the batch size
(the number of elements in :attr:`sequences`), ``T`` is the length of the longest
sequence.
Example:
>>> from torch.nn.utils.rnn import pad_sequence
>>> a = torch.ones(25, 300)
>>> b = torch.ones(22, 300)
>>> c = torch.ones(15, 300)
>>> pad_sequence([a, b, c]).size()
torch.Size([25, 3, 300])
Note:
This function returns a Tensor of size ``T x B x *`` or ``B x T x *``
where `T` is the length of the longest sequence. This function assumes
trailing dimensions and type of all the Tensors in sequences are same.
Args:
sequences (list[Tensor]): list of variable length sequences.
batch_first (bool, optional): if ``True``, the output will be in ``B x T x *``
format, ``T x B x *`` otherwise.
padding_value (float, optional): value for padded elements. Default: ``0``.
padding_side (str, optional): the side to pad the sequences on.
Default: ``'right'``.
Returns:
Tensor of size ``T x B x *`` if :attr:`batch_first` is ``False``.
Tensor of size ``B x T x *`` otherwise
"""
if not (torch.jit.is_tracing() or torch.jit.is_scripting()):
# JIT doesn't support `Iterable`
if not isinstance(sequences, Iterable):
msg = (
"pad_sequence: Expected iterable for input sequences, but got arg of type: "
f"{type(sequences)}"
)
raise RuntimeError(msg)
# In JIT context this leads to,
# RuntimeError: cannot statically infer the expected size of a list in this context
sequences = tuple(sequences) # type: ignore[assignment]
else:
# For JIT, we only support Union[Tensor, Tuple[Tensor]]
if isinstance(sequences, torch.Tensor):
sequences = sequences.unbind(0) # type: ignore[assignment]
# assuming trailing dimensions and type of all the Tensors
# in sequences are same and fetching those from sequences[0]
return torch._C._nn.pad_sequence(
sequences, # type: ignore[arg-type]
batch_first,
padding_value,
padding_side, # type: ignore[arg-type]
)
def unpad_sequence(
padded_sequences: Tensor,
lengths: Tensor,
batch_first: bool = False,
) -> list[Tensor]:
r"""Unpad padded Tensor into a list of variable length Tensors.
``unpad_sequence`` unstacks padded Tensor into a list of variable length Tensors.
Example:
>>> from torch.nn.utils.rnn import pad_sequence, unpad_sequence
>>> a = torch.ones(25, 300)
>>> b = torch.ones(22, 300)
>>> c = torch.ones(15, 300)
>>> sequences = [a, b, c]
>>> padded_sequences = pad_sequence(sequences)
>>> lengths = torch.as_tensor([v.size(0) for v in sequences])
>>> unpadded_sequences = unpad_sequence(padded_sequences, lengths)
>>> torch.allclose(sequences[0], unpadded_sequences[0])
True
>>> torch.allclose(sequences[1], unpadded_sequences[1])
True
>>> torch.allclose(sequences[2], unpadded_sequences[2])
True
Args:
padded_sequences (Tensor): padded sequences.
lengths (Tensor): length of original (unpadded) sequences.
batch_first (bool, optional): whether batch dimension first or not. Default: ``False``.
Returns:
a list of :class:`Tensor` objects
"""
unpadded_sequences = []
if not batch_first:
padded_sequences.transpose_(0, 1)
max_length = padded_sequences.shape[1]
idx = torch.arange(max_length, device=lengths.device)
for seq, length in zip(padded_sequences, lengths, strict=True):
mask = idx < length
unpacked_seq = seq[mask]
unpadded_sequences.append(unpacked_seq)
return unpadded_sequences
def pack_sequence(
sequences: list[Tensor],
enforce_sorted: bool = True,
) -> PackedSequence:
r"""Packs a list of variable length Tensors.
Consecutive call of the next functions: ``pad_sequence``, ``pack_padded_sequence``.
``sequences`` should be a list of Tensors of size ``L x *``, where `L` is
the length of a sequence and `*` is any number of trailing dimensions,
including ``0``.
For unsorted sequences, use `enforce_sorted = False`. If ``enforce_sorted``
is ``True``, the sequences should be sorted in the order of decreasing length.
``enforce_sorted = True`` is only necessary for ONNX export.
Example:
>>> from torch.nn.utils.rnn import pack_sequence
>>> a = torch.tensor([1, 2, 3])
>>> b = torch.tensor([4, 5])
>>> c = torch.tensor([6])
>>> pack_sequence([a, b, c])
PackedSequence(data=tensor([1, 4, 6, 2, 5, 3]), batch_sizes=tensor([3, 2, 1]), sorted_indices=None, unsorted_indices=None)
Args:
sequences (list[Tensor]): A list of sequences of decreasing length.
enforce_sorted (bool, optional): if ``True``, checks that the input
contains sequences sorted by length in a decreasing order. If
``False``, this condition is not checked. Default: ``True``.
Returns:
a :class:`PackedSequence` object
"""
lengths = torch.as_tensor([v.size(0) for v in sequences])
return pack_padded_sequence(
pad_sequence(sequences), lengths, enforce_sorted=enforce_sorted
)
def unpack_sequence(packed_sequences: PackedSequence) -> list[Tensor]:
r"""Unpack PackedSequence into a list of variable length Tensors.
``packed_sequences`` should be a PackedSequence object.
Example:
>>> from torch.nn.utils.rnn import pack_sequence, unpack_sequence
>>> a = torch.tensor([1, 2, 3])
>>> b = torch.tensor([4, 5])
>>> c = torch.tensor([6])
>>> sequences = [a, b, c]
>>> print(sequences)
[tensor([1, 2, 3]), tensor([4, 5]), tensor([6])]
>>> packed_sequences = pack_sequence(sequences)
>>> print(packed_sequences)
PackedSequence(data=tensor([1, 4, 6, 2, 5, 3]), batch_sizes=tensor([3, 2, 1]), sorted_indices=None, unsorted_indices=None)
>>> unpacked_sequences = unpack_sequence(packed_sequences)
>>> print(unpacked_sequences)
[tensor([1, 2, 3]), tensor([4, 5]), tensor([6])]
Args:
packed_sequences (PackedSequence): A PackedSequence object.
Returns:
a list of :class:`Tensor` objects
"""
padded_sequences, lengths = pad_packed_sequence(packed_sequences, batch_first=True)
unpacked_sequences = unpad_sequence(padded_sequences, lengths, batch_first=True)
return unpacked_sequences
| PackedSequence |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_hyperlink04.py | {
"start": 315,
"end": 2424
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("hyperlink04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with hyperlinks."""
workbook = Workbook(self.got_filename)
# Turn off default URL format for testing.
workbook.default_url_format = None
worksheet1 = workbook.add_worksheet()
workbook.add_worksheet()
workbook.add_worksheet("Data Sheet")
worksheet1.write_url("A1", "internal:Sheet2!A1")
worksheet1.write_url("A3", "internal:Sheet2!A1:A5")
worksheet1.write_url("A5", "internal:'Data Sheet'!D5", None, "Some text")
worksheet1.write_url("E12", "internal:Sheet1!J1")
worksheet1.write_url("G17", "internal:Sheet2!A1", None, "Some text")
worksheet1.write_url("A18", "internal:Sheet2!A1", None, None, "Tool Tip 1")
worksheet1.write_url(
"A20", "internal:Sheet2!A1", None, "More text", "Tool Tip 2"
)
workbook.close()
self.assertExcelEqual()
def test_create_file_write(self):
"""Test the creation of a simple XlsxWriter file with hyperlinks with write()"""
workbook = Workbook(self.got_filename)
# Turn off default URL format for testing.
workbook.default_url_format = None
worksheet1 = workbook.add_worksheet()
workbook.add_worksheet()
workbook.add_worksheet("Data Sheet")
worksheet1.write("A1", "internal:Sheet2!A1")
worksheet1.write("A3", "internal:Sheet2!A1:A5")
worksheet1.write("A5", "internal:'Data Sheet'!D5", None, "Some text")
worksheet1.write("E12", "internal:Sheet1!J1")
worksheet1.write("G17", "internal:Sheet2!A1", None, "Some text")
worksheet1.write("A18", "internal:Sheet2!A1", None, None, "Tool Tip 1")
worksheet1.write("A20", "internal:Sheet2!A1", None, "More text", "Tool Tip 2")
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | Textualize__textual | docs/examples/styles/scrollbar_gutter.py | {
"start": 385,
"end": 595
} | class ____(App):
CSS_PATH = "scrollbar_gutter.tcss"
def compose(self):
yield Static(TEXT, id="text-box")
if __name__ == "__main__":
app = ScrollbarGutterApp()
app.run()
| ScrollbarGutterApp |
python | getsentry__sentry | src/sentry/testutils/cases.py | {
"start": 27825,
"end": 30025
} | class ____(APITestCase):
@cached_property
def path_2fa(self):
return reverse("sentry-account-settings-security")
def enable_org_2fa(self, organization):
organization.flags.require_2fa = True
organization.save()
def api_enable_org_2fa(self, organization, user):
self.login_as(user)
url = reverse(
"sentry-api-0-organization-details",
kwargs={"organization_id_or_slug": organization.slug},
)
return self.client.put(url, data={"require2FA": True})
def api_disable_org_2fa(self, organization, user):
url = reverse(
"sentry-api-0-organization-details",
kwargs={"organization_id_or_slug": organization.slug},
)
return self.client.put(url, data={"require2FA": False})
def assert_can_enable_org_2fa(self, organization, user, status_code=200):
self.__helper_enable_organization_2fa(organization, user, status_code)
def assert_cannot_enable_org_2fa(self, organization, user, status_code, err_msg=None):
self.__helper_enable_organization_2fa(organization, user, status_code, err_msg)
def __helper_enable_organization_2fa(self, organization, user, status_code, err_msg=None):
response = self.api_enable_org_2fa(organization, user)
assert response.status_code == status_code
if err_msg:
assert err_msg.encode("utf-8") in response.content
organization = Organization.objects.get(id=organization.id)
if 200 <= status_code < 300:
assert organization.flags.require_2fa
else:
assert not organization.flags.require_2fa
def add_2fa_users_to_org(self, organization, num_of_users=10, num_with_2fa=5):
non_compliant_members = []
for num in range(0, num_of_users):
user = self.create_user("foo_%s@example.com" % num)
self.create_member(organization=organization, user=user)
if num_with_2fa:
TotpInterface().enroll(user)
num_with_2fa -= 1
else:
non_compliant_members.append(user.email)
return non_compliant_members
| TwoFactorAPITestCase |
python | tensorflow__tensorflow | tensorflow/python/ops/math_grad_test.py | {
"start": 6437,
"end": 8458
} | class ____(test.TestCase):
@test_util.run_deprecated_v1
def testProdGradient(self):
inputs = constant_op.constant([[1., 2.], [3., 4.]],
dtype=dtypes.float32)
outputs = math_ops.reduce_prod(inputs)
with self.cached_session():
error = gradient_checker.compute_gradient_error(
inputs, inputs.get_shape().as_list(),
outputs, outputs.get_shape().as_list())
self.assertLess(error, 1e-4)
@test_util.run_deprecated_v1
def testProdGradientForNegativeAxis(self):
inputs = constant_op.constant([[1., 2.], [3., 4.]],
dtype=dtypes.float32)
outputs = math_ops.reduce_prod(inputs, -1)
with self.cached_session():
error = gradient_checker.compute_gradient_error(
inputs, inputs.get_shape().as_list(),
outputs, outputs.get_shape().as_list())
self.assertLess(error, 1e-4)
@test_util.run_deprecated_v1
def testProdGradientComplex(self):
for dtype in dtypes.complex64, dtypes.complex128:
inputs = constant_op.constant([[1 + 3j, 2 - 1j], [3j, 4]],
dtype=dtype)
outputs = math_ops.reduce_prod(inputs)
with self.cached_session():
error = gradient_checker.compute_gradient_error(
inputs, inputs.get_shape().as_list(),
outputs, outputs.get_shape().as_list())
self.assertLess(error, 1e-4)
@test_util.run_deprecated_v1
def testProdGradientForNegativeAxisComplex(self):
for dtype in dtypes.complex64, dtypes.complex128:
inputs = constant_op.constant([[1 + 3j, 2 - 1j], [3j, 4]],
dtype=dtype)
outputs = math_ops.reduce_prod(inputs, -1)
with self.cached_session():
error = gradient_checker.compute_gradient_error(
inputs, inputs.get_shape().as_list(),
outputs, outputs.get_shape().as_list())
self.assertLess(error, 1e-4)
@test_util.run_all_in_graph_and_eager_modes
| ProdGradientTest |
python | nryoung__algorithms | tests/test_sorting.py | {
"start": 778,
"end": 1027
} | class ____(SortingAlgorithmTestCase):
"""
Tests Bubble sort on a small range from 0-9
"""
def test_bubblesort(self):
self.output = bubble_sort.sort(self.input)
self.assertEqual(self.correct, self.output)
| TestBubbleSort |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_outline05.py | {
"start": 315,
"end": 3105
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("outline05.xlsx")
self.ignore_files = [
"xl/calcChain.xml",
"[Content_Types].xml",
"xl/_rels/workbook.xml.rels",
]
def test_create_file(self):
"""
Test the creation of a outlines in a XlsxWriter file. These tests are
based on the outline programs in the examples directory.
"""
workbook = Workbook(self.got_filename)
worksheet2 = workbook.add_worksheet("Collapsed Rows")
bold = workbook.add_format({"bold": 1})
worksheet2.set_row(1, None, None, {"level": 2, "hidden": True})
worksheet2.set_row(2, None, None, {"level": 2, "hidden": True})
worksheet2.set_row(3, None, None, {"level": 2, "hidden": True})
worksheet2.set_row(4, None, None, {"level": 2, "hidden": True})
worksheet2.set_row(
5, None, None, {"level": 1, "hidden": True, "collapsed": True}
)
worksheet2.set_row(6, None, None, {"level": 2, "hidden": True})
worksheet2.set_row(7, None, None, {"level": 2, "hidden": True})
worksheet2.set_row(8, None, None, {"level": 2, "hidden": True})
worksheet2.set_row(9, None, None, {"level": 2, "hidden": True})
worksheet2.set_row(
10, None, None, {"level": 1, "hidden": True, "collapsed": True}
)
worksheet2.set_row(11, None, None, {"collapsed": True})
worksheet2.set_column("A:A", 20)
worksheet2.set_selection("A14")
worksheet2.write("A1", "Region", bold)
worksheet2.write("A2", "North")
worksheet2.write("A3", "North")
worksheet2.write("A4", "North")
worksheet2.write("A5", "North")
worksheet2.write("A6", "North Total", bold)
worksheet2.write("B1", "Sales", bold)
worksheet2.write("B2", 1000)
worksheet2.write("B3", 1200)
worksheet2.write("B4", 900)
worksheet2.write("B5", 1200)
worksheet2.write("B6", "=SUBTOTAL(9,B2:B5)", bold, 4300)
worksheet2.write("A7", "South")
worksheet2.write("A8", "South")
worksheet2.write("A9", "South")
worksheet2.write("A10", "South")
worksheet2.write("A11", "South Total", bold)
worksheet2.write("B7", 400)
worksheet2.write("B8", 600)
worksheet2.write("B9", 500)
worksheet2.write("B10", 600)
worksheet2.write("B11", "=SUBTOTAL(9,B7:B10)", bold, 2100)
worksheet2.write("A12", "Grand Total", bold)
worksheet2.write("B12", "=SUBTOTAL(9,B2:B10)", bold, 6400)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 7099,
"end": 7798
} | class ____(StringIORewind):
params = [None, "custom", "iso8601", "ymd"]
param_names = ["format"]
def setup(self, format):
rng = date_range("1/1/2000", periods=1000)
formats = {
None: None,
"custom": "%m/%d/%Y %H:%M:%S.%f",
"iso8601": "%Y-%m-%d %H:%M:%S",
"ymd": "%Y%m%d",
}
dt_format = formats[format]
self.StringIO_input = StringIO("\n".join(rng.strftime(dt_format).tolist()))
def time_read_csv(self, format):
read_csv(
self.data(self.StringIO_input),
header=None,
names=["foo"],
parse_dates=["foo"],
)
| ReadCSVDInferDatetimeFormat |
python | xlwings__xlwings | tests/test_shape.py | {
"start": 9670,
"end": 10600
} | class ____(TestBase):
def test_add_properties(self):
sht = self.wb1.sheets[0]
sht.range("A1").value = [["one", "two"], [1.1, 2.2]]
self.assertEqual(len(sht.charts), 0)
chart = sht.charts.add()
self.assertEqual(len(sht.charts), 1)
chart.name = "My Chart"
chart.set_source_data(sht.range("A1").expand("table"))
chart.chart_type = "line"
self.assertEqual("My Chart", chart.name)
self.assertEqual(sht.charts[0].chart_type, "line")
chart.chart_type = "pie"
self.assertEqual(sht.charts[0].chart_type, "pie")
for a in ("left", "top", "width", "height"):
setattr(chart, a, 400)
self.assertEqual(getattr(sht.charts[0], a), 400)
setattr(sht.charts[0], a, 500)
self.assertEqual(getattr(chart, a), 500)
chart.delete()
self.assertEqual(sht.charts.count, 0)
| TestCharts |
python | apache__airflow | providers/openlineage/tests/unit/openlineage/extractors/test_base.py | {
"start": 2081,
"end": 2167
} | class ____(JobFacet):
finished: bool = field(default=False)
@define
| CompleteRunFacet |
python | pypa__warehouse | tests/unit/oidc/models/test_activestate.py | {
"start": 1748,
"end": 12803
} | class ____:
def test_publisher_name(self):
publisher = ActiveStatePublisher()
assert publisher.publisher_name == "ActiveState"
def test_publisher_base_url(self):
org_name = "fakeorg"
project_name = "fakeproject"
publisher = ActiveStatePublisher(
organization=org_name, activestate_project_name=project_name
)
assert (
publisher.publisher_base_url
== f"https://platform.activestate.com/{org_name}/{project_name}"
)
def test_publisher_url(self):
org_name = "fakeorg"
project_name = "fakeproject"
publisher = ActiveStatePublisher(
organization=org_name, activestate_project_name=project_name
)
assert (
publisher.publisher_url()
== f"https://platform.activestate.com/{org_name}/{project_name}"
)
def test_stored_claims(self):
publisher = ActiveStatePublisher(
organization="fake", activestate_project_name="fake"
)
assert publisher.stored_claims() == {}
def test_admin_details(self):
publisher = ActiveStatePublisher(
organization="fakeorg",
activestate_project_name="fakeproject",
actor="fakeactor",
actor_id="fakeactorid",
)
assert publisher.admin_details == [
("Organization", "fakeorg"),
("Project", "fakeproject"),
("Actor", "fakeactor"),
("Actor ID", "fakeactorid"),
]
def test_stringifies_as_project_url(self):
org_name = "fakeorg"
project_name = "fakeproject"
publisher = ActiveStatePublisher(
organization=org_name, activestate_project_name=project_name
)
assert (
str(publisher)
== f"https://platform.activestate.com/{org_name}/{project_name}"
)
def test_activestate_publisher_all_known_claims(self):
assert ActiveStatePublisher.all_known_claims() == {
# verifiable claims
"organization",
"project",
"actor_id",
"actor",
"builder",
"sub",
"artifact_id",
# preverified claims
"iss",
"iat",
"nbf",
"exp",
"aud",
# unchecked claims
"project_visibility",
"project_path",
"ingredient",
"organization_id",
"project_id",
}
def test_activestate_publisher_unaccounted_claims(self, monkeypatch):
scope = pretend.stub()
sentry_sdk = pretend.stub(
capture_message=pretend.call_recorder(lambda s: None),
new_scope=pretend.call_recorder(
lambda: pretend.stub(
__enter__=lambda *a: scope, __exit__=lambda *a: None
)
),
)
monkeypatch.setattr(_core, "sentry_sdk", sentry_sdk)
signed_claims = new_signed_claims()
signed_claims["fake-claim"] = "fake"
signed_claims["another-fake-claim"] = "also-fake"
ActiveStatePublisher.check_claims_existence(signed_claims)
assert sentry_sdk.capture_message.calls == [
pretend.call(
"JWT for ActiveStatePublisher has unaccounted claims: "
"['another-fake-claim', 'fake-claim']"
)
]
assert scope.fingerprint == ["another-fake-claim", "fake-claim"]
@pytest.mark.parametrize(
("claim_to_drop", "valid", "error_msg"),
[
("organization", False, "Missing claim 'organization'"),
("project", False, "Missing claim 'project'"),
("actor_id", False, "Missing claim 'actor_id'"),
("actor", True, None),
("builder", False, "Missing claim 'builder'"),
("organization_id", True, None),
("project_id", True, None),
("project_visibility", True, None),
("project_path", True, None),
],
)
def test_activestate_publisher_missing_claims(
self, monkeypatch, claim_to_drop: str, valid: bool, error_msg: str | None
):
publisher = ActiveStatePublisher(
organization=ORG_URL_NAME,
activestate_project_name=PROJECT_NAME,
actor_id=ACTOR_ID,
actor=ACTOR,
)
scope = pretend.stub()
sentry_sdk = pretend.stub(
capture_message=pretend.call_recorder(lambda s: None),
new_scope=pretend.call_recorder(
lambda: pretend.stub(
__enter__=lambda *a: scope, __exit__=lambda *a: None
)
),
)
monkeypatch.setattr(_core, "sentry_sdk", sentry_sdk)
signed_claims = new_signed_claims()
signed_claims.pop(claim_to_drop)
assert claim_to_drop not in signed_claims
if valid:
ActiveStatePublisher.check_claims_existence(signed_claims)
assert (
publisher.verify_claims(
signed_claims=signed_claims, publisher_service=pretend.stub
)
is valid
)
else:
with pytest.raises(InvalidPublisherError) as e:
ActiveStatePublisher.check_claims_existence(signed_claims)
assert str(e.value) == error_msg
assert sentry_sdk.capture_message.calls == [
pretend.call(
"JWT for ActiveStatePublisher is missing claim: " + claim_to_drop
)
]
assert scope.fingerprint == [claim_to_drop]
@pytest.mark.parametrize(
("expect", "actual", "valid"),
[
(ORG_URL_NAME, ORG_URL_NAME, True),
(ORG_URL_NAME, PROJECT_NAME, False),
],
)
def test_activestate_publisher_org_id_verified(
self, expect: str, actual: str, valid: bool
):
publisher = ActiveStatePublisher(
organization=actual,
activestate_project_name=PROJECT_NAME,
actor_id=ACTOR_ID,
actor=ACTOR,
)
signed_claims = new_signed_claims(organization=expect)
check = publisher.__required_verifiable_claims__["organization"]
assert check(actual, expect, signed_claims) is valid
@pytest.mark.parametrize(
("expect", "actual", "valid"),
[
(PROJECT_NAME, PROJECT_NAME, True),
(PROJECT_NAME, ORG_URL_NAME, False),
],
)
def test_activestate_publisher_project_id_verified(
self, expect: str, actual: str, valid: bool
):
publisher = ActiveStatePublisher(
organization=ORG_URL_NAME,
activestate_project_name=actual,
actor_id=ACTOR_ID,
actor=ACTOR,
)
signed_claims = new_signed_claims(project=expect)
check = publisher.__required_verifiable_claims__["project"]
assert check(actual, expect, signed_claims) is valid
@pytest.mark.parametrize(
("expect", "actual", "valid"),
[
(ACTOR_ID, ACTOR_ID, True),
(ACTOR_ID, ORG_URL_NAME, False),
],
)
def test_activestate_publisher_user_id_verified(
self, expect: str, actual: str, valid: bool
):
publisher = ActiveStatePublisher(
organization=ORG_URL_NAME,
activestate_project_name=PROJECT_NAME,
actor_id=actual,
actor=ACTOR,
)
signed_claims = new_signed_claims(actor_id=expect)
check = publisher.__required_verifiable_claims__["actor_id"]
assert check(actual, expect, signed_claims) is valid
@pytest.mark.parametrize(
("expected", "actual", "valid", "error_msg"),
[
# Both present: must match.
(
f"org:{ORG_URL_NAME}:project:{PROJECT_NAME}",
f"org:{ORG_URL_NAME}:project:{PROJECT_NAME}",
True,
None,
),
# Both present: must match.
(
f"org:{ORG_URL_NAME}:project:{PROJECT_NAME}",
"",
False,
"Missing 'subject' claim",
),
# Wrong value, project, must fail.
(
f"org:{ORG_URL_NAME}:project:{PROJECT_NAME}",
f"org:{ORG_URL_NAME}:project:{ORG_URL_NAME}",
False,
"Invalid 'subject' claim",
),
# Wrong value, org_id, must fail.
(
f"org:{ORG_URL_NAME}:project:{PROJECT_NAME}",
f"org:{PROJECT_NAME}:project:{PROJECT_NAME}",
False,
"Invalid 'subject' claim",
),
# Just nonsenes, must fail.
(
f"org:{ORG_URL_NAME}:project:{PROJECT_NAME}",
"Nonsense",
False,
"Invalid 'subject' claim. Wrong format",
),
],
)
def test_activestate_publisher_sub(
self, expected: str, actual: str, valid: bool, error_msg: str | None
):
check = ActiveStatePublisher.__required_verifiable_claims__["sub"]
signed_claims = new_signed_claims(sub=actual)
if valid:
assert check(expected, actual, signed_claims) is True
else:
with pytest.raises(InvalidPublisherError) as e:
check(expected, actual, signed_claims)
assert str(e.value) == error_msg
@pytest.mark.parametrize(
("url", "expected"),
[
("https://platform.activestate.com/repository_name/project_name", True),
("https://platform.activestate.com/repository_name/PrOjECt_NaMe", False),
],
)
def test_activestate_publisher_verify_url(self, url, expected):
publisher = ActiveStatePublisher(
organization="repository_name",
activestate_project_name="project_name",
actor_id=ACTOR_ID,
actor=ACTOR,
)
assert publisher.verify_url(url) == expected
@pytest.mark.parametrize("exists_in_db", [True, False])
def test_exists(self, db_request, exists_in_db):
publisher = ActiveStatePublisher(
organization="repository_name",
activestate_project_name="project_name",
actor_id=ACTOR_ID,
actor=ACTOR,
)
if exists_in_db:
db_request.db.add(publisher)
db_request.db.flush()
assert publisher.exists(db_request.db) == exists_in_db
def test_lookup_no_matching_publishers(self, db_request):
signed_claims = new_signed_claims(actor_id="my_id")
with pytest.raises(InvalidPublisherError) as e:
ActiveStatePublisher.lookup_by_claims(db_request.db, signed_claims)
assert str(e.value) == "Publisher with matching claims was not found"
| TestActiveStatePublisher |
python | ethereum__web3.py | ens/exceptions.py | {
"start": 1645,
"end": 1745
} | class ____(ENSException):
"""
Raised if you bid less than the minimum amount
"""
| BidTooLow |
python | sympy__sympy | sympy/parsing/latex/lark/transformer.py | {
"start": 467,
"end": 25754
} | class ____(Transformer):
"""Returns a SymPy expression that is generated by traversing the ``lark.Tree``
passed to the ``.transform()`` function.
Notes
=====
**This class is never supposed to be used directly.**
In order to tweak the behavior of this class, it has to be subclassed and then after
the required modifications are made, the name of the new class should be passed to
the :py:class:`LarkLaTeXParser` class by using the ``transformer`` argument in the
constructor.
Parameters
==========
visit_tokens : bool, optional
For information about what this option does, see `here
<https://lark-parser.readthedocs.io/en/latest/visitors.html#lark.visitors.Transformer>`_.
Note that the option must be set to ``True`` for the default parser to work.
"""
SYMBOL = sympy.Symbol
DIGIT = sympy.core.numbers.Integer
def CMD_INFTY(self, tokens):
return sympy.oo
def GREEK_SYMBOL_WITH_PRIMES(self, tokens):
# we omit the first character because it is a backslash. Also, if the variable name has "var" in it,
# like "varphi" or "varepsilon", we remove that too
variable_name = re.sub("var", "", tokens[1:])
return sympy.Symbol(variable_name)
def LATIN_SYMBOL_WITH_LATIN_SUBSCRIPT(self, tokens):
base, sub = tokens.value.split("_")
if sub.startswith("{"):
return sympy.Symbol("%s_{%s}" % (base, sub[1:-1]))
else:
return sympy.Symbol("%s_{%s}" % (base, sub))
def GREEK_SYMBOL_WITH_LATIN_SUBSCRIPT(self, tokens):
base, sub = tokens.value.split("_")
greek_letter = re.sub("var", "", base[1:])
if sub.startswith("{"):
return sympy.Symbol("%s_{%s}" % (greek_letter, sub[1:-1]))
else:
return sympy.Symbol("%s_{%s}" % (greek_letter, sub))
def LATIN_SYMBOL_WITH_GREEK_SUBSCRIPT(self, tokens):
base, sub = tokens.value.split("_")
if sub.startswith("{"):
greek_letter = sub[2:-1]
else:
greek_letter = sub[1:]
greek_letter = re.sub("var", "", greek_letter)
return sympy.Symbol("%s_{%s}" % (base, greek_letter))
def GREEK_SYMBOL_WITH_GREEK_SUBSCRIPT(self, tokens):
base, sub = tokens.value.split("_")
greek_base = re.sub("var", "", base[1:])
if sub.startswith("{"):
greek_sub = sub[2:-1]
else:
greek_sub = sub[1:]
greek_sub = re.sub("var", "", greek_sub)
return sympy.Symbol("%s_{%s}" % (greek_base, greek_sub))
def multi_letter_symbol(self, tokens):
if len(tokens) == 4: # no primes (single quotes) on symbol
return sympy.Symbol(tokens[2])
if len(tokens) == 5: # there are primes on the symbol
return sympy.Symbol(tokens[2] + tokens[4])
def number(self, tokens):
if tokens[0].type == "CMD_IMAGINARY_UNIT":
return sympy.I
if "." in tokens[0]:
return sympy.core.numbers.Float(tokens[0])
else:
return sympy.core.numbers.Integer(tokens[0])
def latex_string(self, tokens):
return tokens[0]
def group_round_parentheses(self, tokens):
return tokens[1]
def group_square_brackets(self, tokens):
return tokens[1]
def group_curly_parentheses(self, tokens):
return tokens[1]
def eq(self, tokens):
return sympy.Eq(tokens[0], tokens[2])
def ne(self, tokens):
return sympy.Ne(tokens[0], tokens[2])
def lt(self, tokens):
return sympy.Lt(tokens[0], tokens[2])
def lte(self, tokens):
return sympy.Le(tokens[0], tokens[2])
def gt(self, tokens):
return sympy.Gt(tokens[0], tokens[2])
def gte(self, tokens):
return sympy.Ge(tokens[0], tokens[2])
def add(self, tokens):
if len(tokens) == 2: # +a
return tokens[1]
if len(tokens) == 3: # a + b
lh = tokens[0]
rh = tokens[2]
if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh):
return sympy.MatAdd(lh, rh)
return sympy.Add(lh, rh)
def sub(self, tokens):
if len(tokens) == 2: # -a
x = tokens[1]
if self._obj_is_sympy_Matrix(x):
return sympy.MatMul(-1, x)
return -x
if len(tokens) == 3: # a - b
lh = tokens[0]
rh = tokens[2]
if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh):
return sympy.MatAdd(lh, sympy.MatMul(-1, rh))
return sympy.Add(lh, -rh)
def mul(self, tokens):
lh = tokens[0]
rh = tokens[2]
if self._obj_is_sympy_Matrix(lh) or self._obj_is_sympy_Matrix(rh):
return sympy.MatMul(lh, rh)
return sympy.Mul(lh, rh)
def div(self, tokens):
return self._handle_division(tokens[0], tokens[2])
def adjacent_expressions(self, tokens):
# Most of the time, if two expressions are next to each other, it means implicit multiplication,
# but not always
from sympy.physics.quantum import Bra, Ket
if isinstance(tokens[0], Ket) and isinstance(tokens[1], Bra):
from sympy.physics.quantum import OuterProduct
return OuterProduct(tokens[0], tokens[1])
elif tokens[0] == sympy.Symbol("d"):
# If the leftmost token is a "d", then it is highly likely that this is a differential
return tokens[0], tokens[1]
elif isinstance(tokens[0], tuple):
# then we have a derivative
return sympy.Derivative(tokens[1], tokens[0][1])
else:
return sympy.Mul(tokens[0], tokens[1])
def superscript(self, tokens):
def isprime(x):
return isinstance(x, Token) and x.type == "PRIMES"
def iscmdprime(x):
return isinstance(x, Token) and (x.type == "PRIMES_VIA_CMD"
or x.type == "CMD_PRIME")
def isstar(x):
return isinstance(x, Token) and x.type == "STARS"
def iscmdstar(x):
return isinstance(x, Token) and (x.type == "STARS_VIA_CMD"
or x.type == "CMD_ASTERISK")
base = tokens[0]
if len(tokens) == 3: # a^b OR a^\prime OR a^\ast
sup = tokens[2]
if len(tokens) == 5:
# a^{'}, a^{''}, ... OR
# a^{*}, a^{**}, ... OR
# a^{\prime}, a^{\prime\prime}, ... OR
# a^{\ast}, a^{\ast\ast}, ...
sup = tokens[3]
if self._obj_is_sympy_Matrix(base):
if sup == sympy.Symbol("T"):
return sympy.Transpose(base)
if sup == sympy.Symbol("H"):
return sympy.adjoint(base)
if isprime(sup):
sup = sup.value
if len(sup) % 2 == 0:
return base
return sympy.Transpose(base)
if iscmdprime(sup):
sup = sup.value
if (len(sup)/len(r"\prime")) % 2 == 0:
return base
return sympy.Transpose(base)
if isstar(sup):
sup = sup.value
# need .doit() in order to be consistent with
# sympy.adjoint() which returns the evaluated adjoint
# of a matrix
if len(sup) % 2 == 0:
return base.doit()
return sympy.adjoint(base)
if iscmdstar(sup):
sup = sup.value
# need .doit() for same reason as above
if (len(sup)/len(r"\ast")) % 2 == 0:
return base.doit()
return sympy.adjoint(base)
if isprime(sup) or iscmdprime(sup) or isstar(sup) or iscmdstar(sup):
raise LaTeXParsingError(f"{base} with superscript {sup} is not understood.")
return sympy.Pow(base, sup)
def matrix_prime(self, tokens):
base = tokens[0]
primes = tokens[1].value
if not self._obj_is_sympy_Matrix(base):
raise LaTeXParsingError(f"({base}){primes} is not understood.")
if len(primes) % 2 == 0:
return base
return sympy.Transpose(base)
def symbol_prime(self, tokens):
base = tokens[0]
primes = tokens[1].value
return sympy.Symbol(f"{base.name}{primes}")
def fraction(self, tokens):
numerator = tokens[1]
if isinstance(tokens[2], tuple):
# we only need the variable w.r.t. which we are differentiating
_, variable = tokens[2]
# we will pass this information upwards
return "derivative", variable
else:
denominator = tokens[2]
return self._handle_division(numerator, denominator)
def binomial(self, tokens):
return sympy.binomial(tokens[1], tokens[2])
def normal_integral(self, tokens):
underscore_index = None
caret_index = None
if "_" in tokens:
# we need to know the index because the next item in the list is the
# arguments for the lower bound of the integral
underscore_index = tokens.index("_")
if "^" in tokens:
# we need to know the index because the next item in the list is the
# arguments for the upper bound of the integral
caret_index = tokens.index("^")
lower_bound = tokens[underscore_index + 1] if underscore_index else None
upper_bound = tokens[caret_index + 1] if caret_index else None
differential_symbol = self._extract_differential_symbol(tokens)
if differential_symbol is None:
raise LaTeXParsingError("Differential symbol was not found in the expression."
"Valid differential symbols are \"d\", \"\\text{d}, and \"\\mathrm{d}\".")
# else we can assume that a differential symbol was found
differential_variable_index = tokens.index(differential_symbol) + 1
differential_variable = tokens[differential_variable_index]
# we can't simply do something like `if (lower_bound and not upper_bound) ...` because this would
# evaluate to `True` if the `lower_bound` is 0 and upper bound is non-zero
if lower_bound is not None and upper_bound is None:
# then one was given and the other wasn't
raise LaTeXParsingError("Lower bound for the integral was found, but upper bound was not found.")
if upper_bound is not None and lower_bound is None:
# then one was given and the other wasn't
raise LaTeXParsingError("Upper bound for the integral was found, but lower bound was not found.")
# check if any expression was given or not. If it wasn't, then set the integrand to 1.
if underscore_index is not None and underscore_index == differential_variable_index - 3:
# The Token at differential_variable_index - 2 should be the integrand. However, if going one more step
# backwards after that gives us the underscore, then that means that there _was_ no integrand.
# Example: \int^7_0 dx
integrand = 1
elif caret_index is not None and caret_index == differential_variable_index - 3:
# The Token at differential_variable_index - 2 should be the integrand. However, if going one more step
# backwards after that gives us the caret, then that means that there _was_ no integrand.
# Example: \int_0^7 dx
integrand = 1
elif differential_variable_index == 2:
# this means we have something like "\int dx", because the "\int" symbol will always be
# at index 0 in `tokens`
integrand = 1
else:
# The Token at differential_variable_index - 1 is the differential symbol itself, so we need to go one
# more step before that.
integrand = tokens[differential_variable_index - 2]
if lower_bound is not None:
# then we have a definite integral
# we can assume that either both the lower and upper bounds are given, or
# neither of them are
return sympy.Integral(integrand, (differential_variable, lower_bound, upper_bound))
else:
# we have an indefinite integral
return sympy.Integral(integrand, differential_variable)
def group_curly_parentheses_int(self, tokens):
# return signature is a tuple consisting of the expression in the numerator, along with the variable of
# integration
if len(tokens) == 3:
return 1, tokens[1]
elif len(tokens) == 4:
return tokens[1], tokens[2]
# there are no other possibilities
def special_fraction(self, tokens):
numerator, variable = tokens[1]
denominator = tokens[2]
# We pass the integrand, along with information about the variable of integration, upw
return sympy.Mul(numerator, sympy.Pow(denominator, -1)), variable
def integral_with_special_fraction(self, tokens):
underscore_index = None
caret_index = None
if "_" in tokens:
# we need to know the index because the next item in the list is the
# arguments for the lower bound of the integral
underscore_index = tokens.index("_")
if "^" in tokens:
# we need to know the index because the next item in the list is the
# arguments for the upper bound of the integral
caret_index = tokens.index("^")
lower_bound = tokens[underscore_index + 1] if underscore_index else None
upper_bound = tokens[caret_index + 1] if caret_index else None
# we can't simply do something like `if (lower_bound and not upper_bound) ...` because this would
# evaluate to `True` if the `lower_bound` is 0 and upper bound is non-zero
if lower_bound is not None and upper_bound is None:
# then one was given and the other wasn't
raise LaTeXParsingError("Lower bound for the integral was found, but upper bound was not found.")
if upper_bound is not None and lower_bound is None:
# then one was given and the other wasn't
raise LaTeXParsingError("Upper bound for the integral was found, but lower bound was not found.")
integrand, differential_variable = tokens[-1]
if lower_bound is not None:
# then we have a definite integral
# we can assume that either both the lower and upper bounds are given, or
# neither of them are
return sympy.Integral(integrand, (differential_variable, lower_bound, upper_bound))
else:
# we have an indefinite integral
return sympy.Integral(integrand, differential_variable)
def group_curly_parentheses_special(self, tokens):
underscore_index = tokens.index("_")
caret_index = tokens.index("^")
# given the type of expressions we are parsing, we can assume that the lower limit
# will always use braces around its arguments. This is because we don't support
# converting unconstrained sums into SymPy expressions.
# first we isolate the bottom limit
left_brace_index = tokens.index("{", underscore_index)
right_brace_index = tokens.index("}", underscore_index)
bottom_limit = tokens[left_brace_index + 1: right_brace_index]
# next, we isolate the upper limit
top_limit = tokens[caret_index + 1:]
# the code below will be useful for supporting things like `\sum_{n = 0}^{n = 5} n^2`
# if "{" in top_limit:
# left_brace_index = tokens.index("{", caret_index)
# if left_brace_index != -1:
# # then there's a left brace in the string, and we need to find the closing right brace
# right_brace_index = tokens.index("}", caret_index)
# top_limit = tokens[left_brace_index + 1: right_brace_index]
# print(f"top limit = {top_limit}")
index_variable = bottom_limit[0]
lower_limit = bottom_limit[-1]
upper_limit = top_limit[0] # for now, the index will always be 0
# print(f"return value = ({index_variable}, {lower_limit}, {upper_limit})")
return index_variable, lower_limit, upper_limit
def summation(self, tokens):
return sympy.Sum(tokens[2], tokens[1])
def product(self, tokens):
return sympy.Product(tokens[2], tokens[1])
def limit_dir_expr(self, tokens):
caret_index = tokens.index("^")
if "{" in tokens:
left_curly_brace_index = tokens.index("{", caret_index)
direction = tokens[left_curly_brace_index + 1]
else:
direction = tokens[caret_index + 1]
if direction == "+":
return tokens[0], "+"
elif direction == "-":
return tokens[0], "-"
else:
return tokens[0], "+-"
def group_curly_parentheses_lim(self, tokens):
limit_variable = tokens[1]
if isinstance(tokens[3], tuple):
destination, direction = tokens[3]
else:
destination = tokens[3]
direction = "+-"
return limit_variable, destination, direction
def limit(self, tokens):
limit_variable, destination, direction = tokens[2]
return sympy.Limit(tokens[-1], limit_variable, destination, direction)
def differential(self, tokens):
return tokens[1]
def derivative(self, tokens):
return sympy.Derivative(tokens[-1], tokens[5])
def list_of_expressions(self, tokens):
if len(tokens) == 1:
# we return it verbatim because the function_applied node expects
# a list
return tokens
else:
def remove_tokens(args):
if isinstance(args, Token):
if args.type != "COMMA":
# An unexpected token was encountered
raise LaTeXParsingError("A comma token was expected, but some other token was encountered.")
return False
return True
return filter(remove_tokens, tokens)
def function_applied(self, tokens):
return sympy.Function(tokens[0])(*tokens[2])
def min(self, tokens):
return sympy.Min(*tokens[2])
def max(self, tokens):
return sympy.Max(*tokens[2])
def bra(self, tokens):
from sympy.physics.quantum import Bra
return Bra(tokens[1])
def ket(self, tokens):
from sympy.physics.quantum import Ket
return Ket(tokens[1])
def inner_product(self, tokens):
from sympy.physics.quantum import Bra, Ket, InnerProduct
return InnerProduct(Bra(tokens[1]), Ket(tokens[3]))
def sin(self, tokens):
return sympy.sin(tokens[1])
def cos(self, tokens):
return sympy.cos(tokens[1])
def tan(self, tokens):
return sympy.tan(tokens[1])
def csc(self, tokens):
return sympy.csc(tokens[1])
def sec(self, tokens):
return sympy.sec(tokens[1])
def cot(self, tokens):
return sympy.cot(tokens[1])
def sin_power(self, tokens):
exponent = tokens[2]
if exponent == -1:
return sympy.asin(tokens[-1])
else:
return sympy.Pow(sympy.sin(tokens[-1]), exponent)
def cos_power(self, tokens):
exponent = tokens[2]
if exponent == -1:
return sympy.acos(tokens[-1])
else:
return sympy.Pow(sympy.cos(tokens[-1]), exponent)
def tan_power(self, tokens):
exponent = tokens[2]
if exponent == -1:
return sympy.atan(tokens[-1])
else:
return sympy.Pow(sympy.tan(tokens[-1]), exponent)
def csc_power(self, tokens):
exponent = tokens[2]
if exponent == -1:
return sympy.acsc(tokens[-1])
else:
return sympy.Pow(sympy.csc(tokens[-1]), exponent)
def sec_power(self, tokens):
exponent = tokens[2]
if exponent == -1:
return sympy.asec(tokens[-1])
else:
return sympy.Pow(sympy.sec(tokens[-1]), exponent)
def cot_power(self, tokens):
exponent = tokens[2]
if exponent == -1:
return sympy.acot(tokens[-1])
else:
return sympy.Pow(sympy.cot(tokens[-1]), exponent)
def arcsin(self, tokens):
return sympy.asin(tokens[1])
def arccos(self, tokens):
return sympy.acos(tokens[1])
def arctan(self, tokens):
return sympy.atan(tokens[1])
def arccsc(self, tokens):
return sympy.acsc(tokens[1])
def arcsec(self, tokens):
return sympy.asec(tokens[1])
def arccot(self, tokens):
return sympy.acot(tokens[1])
def sinh(self, tokens):
return sympy.sinh(tokens[1])
def cosh(self, tokens):
return sympy.cosh(tokens[1])
def tanh(self, tokens):
return sympy.tanh(tokens[1])
def asinh(self, tokens):
return sympy.asinh(tokens[1])
def acosh(self, tokens):
return sympy.acosh(tokens[1])
def atanh(self, tokens):
return sympy.atanh(tokens[1])
def abs(self, tokens):
return sympy.Abs(tokens[1])
def floor(self, tokens):
return sympy.floor(tokens[1])
def ceil(self, tokens):
return sympy.ceiling(tokens[1])
def factorial(self, tokens):
return sympy.factorial(tokens[0])
def conjugate(self, tokens):
return sympy.conjugate(tokens[1])
def square_root(self, tokens):
if len(tokens) == 2:
# then there was no square bracket argument
return sympy.sqrt(tokens[1])
elif len(tokens) == 3:
# then there _was_ a square bracket argument
return sympy.root(tokens[2], tokens[1])
def exponential(self, tokens):
return sympy.exp(tokens[1])
def log(self, tokens):
if tokens[0].type == "FUNC_LG":
# we don't need to check if there's an underscore or not because having one
# in this case would be meaningless
# TODO: ANTLR refers to ISO 80000-2:2019. should we keep base 10 or base 2?
return sympy.log(tokens[1], 10)
elif tokens[0].type == "FUNC_LN":
return sympy.log(tokens[1])
elif tokens[0].type == "FUNC_LOG":
# we check if a base was specified or not
if "_" in tokens:
# then a base was specified
return sympy.log(tokens[3], tokens[2])
else:
# a base was not specified
return sympy.log(tokens[1])
def _extract_differential_symbol(self, s: str):
differential_symbols = {"d", r"\text{d}", r"\mathrm{d}"}
differential_symbol = next((symbol for symbol in differential_symbols if symbol in s), None)
return differential_symbol
def matrix(self, tokens):
def is_matrix_row(x):
return (isinstance(x, Tree) and x.data == "matrix_row")
def is_not_col_delim(y):
return (not isinstance(y, Token) or y.type != "MATRIX_COL_DELIM")
matrix_body = tokens[1].children
return sympy.Matrix([[y for y in x.children if is_not_col_delim(y)]
for x in matrix_body if is_matrix_row(x)])
def determinant(self, tokens):
if len(tokens) == 2: # \det A
if not self._obj_is_sympy_Matrix(tokens[1]):
raise LaTeXParsingError("Cannot take determinant of non-matrix.")
return tokens[1].det()
if len(tokens) == 3: # | A |
return self.matrix(tokens).det()
def trace(self, tokens):
if not self._obj_is_sympy_Matrix(tokens[1]):
raise LaTeXParsingError("Cannot take trace of non-matrix.")
return sympy.Trace(tokens[1])
def adjugate(self, tokens):
if not self._obj_is_sympy_Matrix(tokens[1]):
raise LaTeXParsingError("Cannot take adjugate of non-matrix.")
# need .doit() since MatAdd does not support .adjugate() method
return tokens[1].doit().adjugate()
def _obj_is_sympy_Matrix(self, obj):
if hasattr(obj, "is_Matrix"):
return obj.is_Matrix
return isinstance(obj, sympy.Matrix)
def _handle_division(self, numerator, denominator):
if self._obj_is_sympy_Matrix(denominator):
raise LaTeXParsingError("Cannot divide by matrices like this since "
"it is not clear if left or right multiplication "
"by the inverse is intended. Try explicitly "
"multiplying by the inverse instead.")
if self._obj_is_sympy_Matrix(numerator):
return sympy.MatMul(numerator, sympy.Pow(denominator, -1))
return sympy.Mul(numerator, sympy.Pow(denominator, -1))
| TransformToSymPyExpr |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 21963,
"end": 22165
} | class ____(InetTestBase):
"""Base class for UDPLITE-over-IPv4 tests."""
def newSocket(self):
return socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDPLITE)
| UDPLITETestBase |
python | PyCQA__pyflakes | pyflakes/messages.py | {
"start": 2058,
"end": 2335
} | class ____(Message):
message = 'syntax error in doctest'
def __init__(self, filename, loc, position=None):
Message.__init__(self, filename, loc)
if position:
(self.lineno, self.col) = position
self.message_args = ()
| DoctestSyntaxError |
python | django__django | tests/admin_filters/tests.py | {
"start": 6540,
"end": 6840
} | class ____(ModelAdmin):
def __init__(self, user, *args, **kwargs):
self.user = user
super().__init__(*args, **kwargs)
list_filter = ("year",)
def get_queryset(self, request):
return super().get_queryset(request).filter(author=self.user)
| BookAdminWithCustomQueryset |
python | tiangolo__fastapi | docs_src/cookie_param_models/tutorial002_an_py310.py | {
"start": 116,
"end": 383
} | class ____(BaseModel):
model_config = {"extra": "forbid"}
session_id: str
fatebook_tracker: str | None = None
googall_tracker: str | None = None
@app.get("/items/")
async def read_items(cookies: Annotated[Cookies, Cookie()]):
return cookies
| Cookies |
python | astropy__astropy | astropy/cosmology/_src/flrw/base.py | {
"start": 43290,
"end": 46477
} | class ____(FlatCosmologyMixin):
"""Mixin class for flat FLRW cosmologies.
Do NOT instantiate directly. Must precede the base class in the
multiple-inheritance so that this mixin's ``__init__`` proceeds the
base class'. Note that all instances of ``FlatFLRWMixin`` are flat, but
not all flat cosmologies are instances of ``FlatFLRWMixin``. As
example, ``LambdaCDM`` **may** be flat (for the a specific set of
parameter values), but ``FlatLambdaCDM`` **will** be flat.
"""
Ode0: Parameter = field( # now a derived param.
default=ParameterOde0.clone(default=0, derived=True),
init=False,
repr=False,
)
def __init_subclass__(cls) -> None:
super().__init_subclass__()
# Check that Ode0 is not in __init__
if (
getattr(
vars(cls).get("Ode0", cls.__dataclass_fields__.get("Ode0")),
"init",
True,
)
or "Ode0" in signature(cls.__init__).parameters
):
msg = "subclasses of `FlatFLRWMixin` cannot have `Ode0` in `__init__`"
raise TypeError(msg)
def __post_init__(self) -> None:
self.__dict__["Ode0"] = 0
super().__post_init__()
# Do some twiddling after the fact to get flatness
self.__dict__["Ok0"] = 0.0
self.__dict__["Ode0"] = 1.0 - (self.Om0 + self.Ogamma0 + self.Onu0 + self.Ok0)
@lazyproperty
def nonflat(self: _FlatFLRWMixinT) -> _FLRWT: # noqa: PYI019
# Create BoundArgument to handle args versus kwargs.
# This also handles all errors from mismatched arguments
ba = inspect.signature(self.__nonflatclass__).bind_partial(
**dict(self.parameters), Ode0=self.Ode0, name=self.name
)
# Make new instance, respecting args vs kwargs
inst = self.__nonflatclass__(*ba.args, **ba.kwargs)
# Because of machine precision, make sure parameters exactly match
inst.__dict__.update(inst.parameters)
inst.__dict__.update(inst._derived_parameters)
inst.__dict__["Ok0"] = self.Ok0
return inst
@property
def Otot0(self) -> float:
"""Omega total; the total density/critical density at z=0."""
return 1.0
def Otot(self, z: u.Quantity | ArrayLike, /) -> FArray:
"""The total density parameter at redshift ``z``.
Parameters
----------
z : Quantity-like ['redshift'], array-like
Input redshift.
.. versionchanged:: 7.0
Passing z as a keyword argument is deprecated.
.. versionchanged:: 8.0
z must be a positional argument.
Returns
-------
Otot : array
"""
return np.ones_like(aszarr(z), subok=True)
def clone(
self, *, meta: CosmoMeta | None = None, to_nonflat: bool = False, **kwargs: Any
) -> "FLRW":
if not to_nonflat and kwargs.get("Ode0") is not None:
msg = "Cannot set 'Ode0' in clone unless 'to_nonflat=True'. "
raise ValueError(msg)
return super().clone(meta=meta, to_nonflat=to_nonflat, **kwargs)
| FlatFLRWMixin |
python | encode__django-rest-framework | rest_framework/permissions.py | {
"start": 3586,
"end": 3882
} | class ____(BasePermission):
"""
Allow any access.
This isn't strictly required, since you could use an empty
permission_classes list, but it's useful because it makes the intention
more explicit.
"""
def has_permission(self, request, view):
return True
| AllowAny |
python | pydata__xarray | asv_bench/benchmarks/coding.py | {
"start": 126,
"end": 520
} | class ____:
def setup(self, calendar):
self.units = "days since 2000-01-01"
self.dtype = np.dtype("int64")
self.times = xr.date_range(
"2000", freq="D", periods=10000, calendar=calendar
).values
def time_encode_cf_datetime(self, calendar):
xr.coding.times.encode_cf_datetime(self.times, self.units, calendar, self.dtype)
| EncodeCFDatetime |
python | gevent__gevent | src/greentest/3.11/test_subprocess.py | {
"start": 71246,
"end": 80531
} | class ____(BaseTestCase):
def run_python(self, code, **kwargs):
"""Run Python code in a subprocess using subprocess.run"""
argv = [sys.executable, "-c", code]
return subprocess.run(argv, **kwargs)
def test_returncode(self):
# call() function with sequence argument
cp = self.run_python("import sys; sys.exit(47)")
self.assertEqual(cp.returncode, 47)
with self.assertRaises(subprocess.CalledProcessError):
cp.check_returncode()
def test_check(self):
with self.assertRaises(subprocess.CalledProcessError) as c:
self.run_python("import sys; sys.exit(47)", check=True)
self.assertEqual(c.exception.returncode, 47)
def test_check_zero(self):
# check_returncode shouldn't raise when returncode is zero
cp = subprocess.run(ZERO_RETURN_CMD, check=True)
self.assertEqual(cp.returncode, 0)
def test_timeout(self):
# run() function with timeout argument; we want to test that the child
# process gets killed when the timeout expires. If the child isn't
# killed, this call will deadlock since subprocess.run waits for the
# child.
with self.assertRaises(subprocess.TimeoutExpired):
self.run_python("while True: pass", timeout=0.0001)
def test_capture_stdout(self):
# capture stdout with zero return code
cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
self.assertIn(b'BDFL', cp.stdout)
def test_capture_stderr(self):
cp = self.run_python("import sys; sys.stderr.write('BDFL')",
stderr=subprocess.PIPE)
self.assertIn(b'BDFL', cp.stderr)
def test_check_output_stdin_arg(self):
# run() can be called with stdin set to a file
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
tf.write(b'pear')
tf.seek(0)
cp = self.run_python(
"import sys; sys.stdout.write(sys.stdin.read().upper())",
stdin=tf, stdout=subprocess.PIPE)
self.assertIn(b'PEAR', cp.stdout)
def test_check_output_input_arg(self):
# check_output() can be called with input set to a string
cp = self.run_python(
"import sys; sys.stdout.write(sys.stdin.read().upper())",
input=b'pear', stdout=subprocess.PIPE)
self.assertIn(b'PEAR', cp.stdout)
def test_check_output_stdin_with_input_arg(self):
# run() refuses to accept 'stdin' with 'input'
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
tf.write(b'pear')
tf.seek(0)
with self.assertRaises(ValueError,
msg="Expected ValueError when stdin and input args supplied.") as c:
output = self.run_python("print('will not be run')",
stdin=tf, input=b'hare')
self.assertIn('stdin', c.exception.args[0])
self.assertIn('input', c.exception.args[0])
@support.requires_resource('walltime')
def test_check_output_timeout(self):
with self.assertRaises(subprocess.TimeoutExpired) as c:
cp = self.run_python((
"import sys, time\n"
"sys.stdout.write('BDFL')\n"
"sys.stdout.flush()\n"
"time.sleep(3600)"),
# Some heavily loaded buildbots (sparc Debian 3.x) require
# this much time to start and print.
timeout=3, stdout=subprocess.PIPE)
self.assertEqual(c.exception.output, b'BDFL')
# output is aliased to stdout
self.assertEqual(c.exception.stdout, b'BDFL')
def test_run_kwargs(self):
newenv = os.environ.copy()
newenv["FRUIT"] = "banana"
cp = self.run_python(('import sys, os;'
'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
env=newenv)
self.assertEqual(cp.returncode, 33)
def test_run_with_pathlike_path(self):
# bpo-31961: test run(pathlike_object)
# the name of a command that can be run without
# any arguments that exit fast
prog = 'tree.com' if mswindows else 'ls'
path = shutil.which(prog)
if path is None:
self.skipTest(f'{prog} required for this test')
path = FakePath(path)
res = subprocess.run(path, stdout=subprocess.DEVNULL)
self.assertEqual(res.returncode, 0)
with self.assertRaises(TypeError):
subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
def test_run_with_bytes_path_and_arguments(self):
# bpo-31961: test run([bytes_object, b'additional arguments'])
path = os.fsencode(sys.executable)
args = [path, '-c', b'import sys; sys.exit(57)']
res = subprocess.run(args)
self.assertEqual(res.returncode, 57)
def test_run_with_pathlike_path_and_arguments(self):
# bpo-31961: test run([pathlike_object, 'additional arguments'])
path = FakePath(sys.executable)
args = [path, '-c', 'import sys; sys.exit(57)']
res = subprocess.run(args)
self.assertEqual(res.returncode, 57)
@unittest.skipUnless(mswindows, "Maybe test trigger a leak on Ubuntu")
def test_run_with_an_empty_env(self):
# gh-105436: fix subprocess.run(..., env={}) broken on Windows
args = [sys.executable, "-c", 'pass']
# Ignore subprocess errors - we only care that the API doesn't
# raise an OSError
subprocess.run(args, env={})
def test_capture_output(self):
cp = self.run_python(("import sys;"
"sys.stdout.write('BDFL'); "
"sys.stderr.write('FLUFL')"),
capture_output=True)
self.assertIn(b'BDFL', cp.stdout)
self.assertIn(b'FLUFL', cp.stderr)
def test_stdout_with_capture_output_arg(self):
# run() refuses to accept 'stdout' with 'capture_output'
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
with self.assertRaises(ValueError,
msg=("Expected ValueError when stdout and capture_output "
"args supplied.")) as c:
output = self.run_python("print('will not be run')",
capture_output=True, stdout=tf)
self.assertIn('stdout', c.exception.args[0])
self.assertIn('capture_output', c.exception.args[0])
def test_stderr_with_capture_output_arg(self):
# run() refuses to accept 'stderr' with 'capture_output'
tf = tempfile.TemporaryFile()
self.addCleanup(tf.close)
with self.assertRaises(ValueError,
msg=("Expected ValueError when stderr and capture_output "
"args supplied.")) as c:
output = self.run_python("print('will not be run')",
capture_output=True, stderr=tf)
self.assertIn('stderr', c.exception.args[0])
self.assertIn('capture_output', c.exception.args[0])
# This test _might_ wind up a bit fragile on loaded build+test machines
# as it depends on the timing with wide enough margins for normal situations
# but does assert that it happened "soon enough" to believe the right thing
# happened.
@unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
def test_run_with_shell_timeout_and_capture_output(self):
"""Output capturing after a timeout mustn't hang forever on open filehandles."""
before_secs = time.monotonic()
try:
subprocess.run('sleep 3', shell=True, timeout=0.1,
capture_output=True) # New session unspecified.
except subprocess.TimeoutExpired as exc:
after_secs = time.monotonic()
stacks = traceback.format_exc() # assertRaises doesn't give this.
else:
self.fail("TimeoutExpired not raised.")
self.assertLess(after_secs - before_secs, 1.5,
msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
f"{stacks}```")
def test_encoding_warning(self):
code = textwrap.dedent("""\
from subprocess import *
run("echo hello", shell=True, text=True)
check_output("echo hello", shell=True, text=True)
""")
cp = subprocess.run([sys.executable, "-Xwarn_default_encoding", "-c", code],
capture_output=True)
lines = cp.stderr.splitlines()
self.assertEqual(len(lines), 2, lines)
self.assertTrue(lines[0].startswith(b"<string>:2: EncodingWarning: "))
self.assertTrue(lines[1].startswith(b"<string>:3: EncodingWarning: "))
def _get_test_grp_name():
for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
if grp:
try:
grp.getgrnam(name_group)
except KeyError:
continue
return name_group
else:
raise unittest.SkipTest('No identified group name to use for this test on this platform.')
@unittest.skipIf(mswindows, "POSIX specific tests")
| RunFuncTestCase |
python | viewflow__viewflow | viewflow/workflow/fields.py | {
"start": 4698,
"end": 5144
} | class ____(models.CharField):
def __init__(self, *args, **kwargs):
kwargs.setdefault("max_length", 150)
super(TokenField, self).__init__(*args, **kwargs)
def from_db_value(self, value, expression, connection):
if value is None:
return value
return Token(value)
def to_python(self, value):
return Token(value)
def get_prep_value(self, value):
return value.token
| TokenField |
python | great-expectations__great_expectations | contrib/great_expectations_geospatial_expectations/great_expectations_geospatial_expectations/expectations/expect_column_values_to_be_line_miles_distance_between.py | {
"start": 2130,
"end": 6841
} | class ____(ColumnMapExpectation):
"""Expect the distance of each Linestring in the column to be between two values in miles."""
# These examples will be shown in the public gallery, and also executed as unit tests for your Expectation
examples = [
{
"data": {
"linestring_less_than_500_miles": [
mapping(LineString([(0, 0), (111319.490793, 110568.8124), (0, 110568.8124)])),
mapping(
LineString(
[
(0, 0),
(111319.490793, 110568.8124),
(111319.490793, 0),
(0, 110568.8124),
]
)
),
mapping(
LineString([(0, 0), (222638.981587, 221104.845779), (222638.981587, 0)])
),
],
"linestring_between_1000_and_2000_miles": [
mapping(
LineString(
[
(222638.981587, 552188.640112),
(111319.490793, 772147.013102),
(1113194.907933, 1209055.279421),
]
)
),
mapping(
LineString(
[
(111319.490793, 881798.964757),
(1001875.417139, 221104.845779),
(111319.490793, 0),
(556597.453966, 1317466.085138),
]
)
),
mapping(
LineString(
[
(556597.453966, 552188.640112),
(1224514.398726, 1209055.279421),
(779236.435553, 881798.964757),
]
)
),
],
},
"tests": [
{
"title": "basic_positive_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"column": "linestring_less_than_500_miles",
"min_distance": 0,
"max_distance": 1000,
},
"out": {
"success": True,
},
},
{
"title": "basic_negative_test",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"column": "linestring_between_1000_and_2000_miles",
"min_distance": 1000,
"max_distance": 2000,
},
"out": {
"success": False,
},
},
],
}
]
# This dictionary contains metadata for display in the public gallery
library_metadata = {
"maturity": "experimental", # "experimental", "beta", or "production"
"tags": [
"geospatial",
"hackathon-22",
], # Tags for this Expectation in the gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@luismdiaz01",
"@derekma73",
],
"requirements": ["geopandas", "shapely"],
}
# This is the id string of the Metric used by this Expectation.
# For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above.
map_metric = "column_values.linestring_distance_miles"
# This is a list of parameter names that can affect whether the Expectation evaluates to True or False
# Please see {some doc} for more information about domain and success keys, and other arguments to Expectations
success_keys = (
"mostly",
"min_distance",
"max_distance",
)
# This dictionary contains default values for any parameters that should have default values
default_kwarg_values = {
"min_distance": 0,
"max_distance": 0,
"mostly": 1.0,
}
if __name__ == "__main__":
ExpectColumnValuesToBeLineMilesDistanceBetween().print_diagnostic_checklist()
| ExpectColumnValuesToBeLineMilesDistanceBetween |
python | django__django | tests/admin_widgets/test_autocomplete_widget.py | {
"start": 1020,
"end": 1267
} | class ____(forms.Form):
band = ModelChoiceField(
queryset=Album.objects.all(),
widget=AutocompleteSelect(
Album._meta.get_field("band").remote_field, admin.site
),
required=True,
)
| RequiredBandForm |
python | google__pytype | pytype/preprocess.py | {
"start": 94,
"end": 1281
} | class ____(ast.NodeVisitor):
"""Collect line numbers of annotations to augment."""
def __init__(self):
self.annotation_lines = []
self.in_function = False
def visit_AnnAssign(self, node):
if self.in_function and node.value is None:
self.annotation_lines.append(node.end_lineno - 1) # change to 0-based
def visit_FunctionDef(self, node):
self.in_function = True
for n in node.body:
self.visit(n)
self.in_function = False
# pylint: enable=invalid-name
def augment_annotations(src):
"""Add an assignment to bare variable annotations."""
try:
tree = ast.parse(src)
except SyntaxError:
# Let the compiler catch and report this later.
return src
visitor = CollectAnnotationLines()
visitor.visit(tree)
if visitor.annotation_lines:
lines = src.split("\n")
for i in visitor.annotation_lines:
# Preserve comments, as they may be pytype directives. We don't bother to
# keep the formatting, since users never see the transformed source code.
line, mark, comment = lines[i].partition("#")
lines[i] = line + " = ..." + mark + comment
src = "\n".join(lines)
return src
| CollectAnnotationLines |
python | PyCQA__pylint | tests/functional/ext/docparams/parameter/missing_param_doc_required_Sphinx.py | {
"start": 8254,
"end": 8516
} | class ____:
"""test_finds_property_return_type_sphinx
Example of a property having return documentation in
a Sphinx style docstring
"""
@property
def foo(self):
"""docstring ...
:type: int
"""
return 10
| Foo |
python | cherrypy__cherrypy | cherrypy/lib/gctools.py | {
"start": 4778,
"end": 8551
} | class ____(object):
"""A CherryPy page handler for testing reference leaks."""
classes = [
(
_cprequest.Request,
2,
2,
'Should be 1 in this request thread and 1 in the main thread.',
),
(
_cprequest.Response,
2,
2,
'Should be 1 in this request thread and 1 in the main thread.',
),
(
_cpwsgi.AppResponse,
1,
1,
'Should be 1 in this request thread only.',
),
]
@cherrypy.expose
def index(self):
"""Render the index page HTML content."""
return 'Hello, world!'
@cherrypy.expose
def stats(self):
"""Render garbage collection statistics page HTML content."""
output = ['Statistics:']
for trial in range(10):
if request_counter.count > 0:
break
time.sleep(0.5)
else:
output.append('\nNot all requests closed properly.')
# gc_collect isn't perfectly synchronous, because it may
# break reference cycles that then take time to fully
# finalize. Call it thrice and hope for the best.
gc.collect()
gc.collect()
unreachable = gc.collect()
if unreachable:
if objgraph is not None:
final = objgraph.by_type('Nondestructible')
if final:
objgraph.show_backrefs(final, filename='finalizers.png')
trash = {}
for x in gc.garbage:
trash[type(x)] = trash.get(type(x), 0) + 1
if trash:
output.insert(0, '\n%s unreachable objects:' % unreachable)
trash = [(v, k) for k, v in trash.items()]
trash.sort()
for pair in trash:
output.append(' ' + repr(pair))
# Check declared classes to verify uncollected instances.
# These don't have to be part of a cycle; they can be
# any objects that have unanticipated referrers that keep
# them from being collected.
allobjs = {}
for cls, minobj, maxobj, msg in self.classes:
allobjs[cls] = get_instances(cls)
for cls, minobj, maxobj, msg in self.classes:
objs = allobjs[cls]
lenobj = len(objs)
if lenobj < minobj or lenobj > maxobj:
if minobj == maxobj:
output.append(
'\nExpected %s %r references, got %s.'
% (minobj, cls, lenobj),
)
else:
output.append(
'\nExpected %s to %s %r references, got %s.'
% (minobj, maxobj, cls, lenobj),
)
for obj in objs:
if objgraph is not None:
ig = [id(objs), id(inspect.currentframe())]
fname = 'graph_%s_%s.png' % (cls.__name__, id(obj))
objgraph.show_backrefs(
obj,
extra_ignore=ig,
max_depth=4,
too_many=20,
filename=fname,
extra_info=get_context,
)
output.append(
'\nReferrers for %s (refcount=%s):'
% (repr(obj), sys.getrefcount(obj)),
)
t = ReferrerTree(ignore=[objs], maxdepth=3)
tree = t.ascend(obj)
output.extend(t.format(tree))
return '\n'.join(output)
| GCRoot |
python | kamyu104__LeetCode-Solutions | Python/minimum-number-of-valid-strings-to-form-target-i.py | {
"start": 3786,
"end": 5174
} | class ____(object):
def minValidStrings(self, words, target):
"""
:type words: List[str]
:type target: str
:rtype: int
"""
def getPrefix(pattern):
prefix = [-1]*len(pattern)
j = -1
for i in xrange(1, len(pattern)):
while j+1 > 0 and pattern[j+1] != pattern[i]:
j = prefix[j]
if pattern[j+1] == pattern[i]:
j += 1
prefix[i] = j
return prefix
def KMP(text, pattern, callback):
prefix = getPrefix(pattern)
j = -1
for i in xrange(len(text)):
while j+1 > 0 and pattern[j+1] != text[i]:
j = prefix[j]
if pattern[j+1] == text[i]:
j += 1
callback(i, j)
if j+1 == len(pattern):
j = prefix[j]
def update(i, j):
lookup[i] = max(lookup[i], j+1)
lookup = [0]*len(target)
for w in words:
KMP(target, w, update)
dp = [0]*(len(target)+1)
for i in xrange(len(target)):
if not lookup[i]:
return -1
dp[i+1] = dp[(i-lookup[i])+1]+1
return dp[-1]
# Time: O(w * l + n * l)
# Space: O(n + t), t is the total size of trie
# trie, dp
| Solution3 |
python | plotly__plotly.py | plotly/graph_objs/scattermap/marker/colorbar/_title.py | {
"start": 233,
"end": 4042
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattermap.marker.colorbar"
_path_str = "scattermap.marker.colorbar.title"
_valid_props = {"font", "side", "text"}
@property
def font(self):
"""
Sets this color bar's title font.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.scattermap.marker.colorbar.title.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Returns
-------
plotly.graph_objs.scattermap.marker.colorbar.title.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
@property
def side(self):
"""
Determines the location of color bar's title with respect to
the color bar. Defaults to "top" when `orientation` if "v" and
defaults to "right" when `orientation` if "h".
The 'side' property is an enumeration that may be specified as:
- One of the following enumeration values:
['right', 'top', 'bottom']
Returns
-------
Any
"""
return self["side"]
@side.setter
def side(self, val):
self["side"] = val
@property
def text(self):
"""
Sets the title of the color bar.
The 'text' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["text"]
@text.setter
def text(self, val):
self["text"] = val
@property
def _prop_descriptions(self):
return """\
font
Sets this color bar's title font.
side
Determines the location of color bar's title with
respect to the color bar. Defaults to "top" when
`orientation` if "v" and defaults to "right" when
`orientation` if "h".
text
Sets the title of the color bar.
"""
def __init__(self, arg=None, font=None, side=None, text=None, **kwargs):
"""
Construct a new Title object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.scattermap.mar
ker.colorbar.Title`
font
Sets this color bar's title font.
side
Determines the location of color bar's title with
respect to the color bar. Defaults to "top" when
`orientation` if "v" and defaults to "right" when
`orientation` if "h".
text
Sets the title of the color bar.
Returns
-------
Title
"""
super().__init__("title")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.scattermap.marker.colorbar.Title
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scattermap.marker.colorbar.Title`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("font", arg, font)
self._set_property("side", arg, side)
self._set_property("text", arg, text)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Title |
python | huggingface__transformers | tests/models/modernbert/test_modeling_modernbert.py | {
"start": 22372,
"end": 29266
} | class ____(unittest.TestCase):
@slow
def test_inference_masked_lm(self):
if version.parse(torch.__version__) < version.parse("2.4.0"):
self.skipTest(reason="This test requires torch >= 2.4 to run.")
model = ModernBertForMaskedLM.from_pretrained(
"answerdotai/ModernBERT-base", reference_compile=False, attn_implementation="sdpa"
)
tokenizer = AutoTokenizer.from_pretrained("answerdotai/ModernBERT-base")
inputs = tokenizer("Hello World!", return_tensors="pt")
with torch.no_grad():
output = model(**inputs)[0]
expected_shape = torch.Size((1, 5, 50368))
self.assertEqual(output.shape, expected_shape)
# compare the actual values for a slice.
expected_slice = torch.tensor(
[[[3.8387, -0.2017, 12.2839], [3.6300, 0.6869, 14.7123], [-5.1137, -3.8122, 11.9874]]]
)
torch.testing.assert_close(output[:, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
@slow
def test_inference_no_head(self):
if version.parse(torch.__version__) < version.parse("2.4.0"):
self.skipTest(reason="This test requires torch >= 2.4 to run.")
model = ModernBertModel.from_pretrained(
"answerdotai/ModernBERT-base", reference_compile=False, attn_implementation="sdpa"
)
tokenizer = AutoTokenizer.from_pretrained("answerdotai/ModernBERT-base")
inputs = tokenizer("Hello World!", return_tensors="pt")
with torch.no_grad():
output = model(**inputs)[0]
expected_shape = torch.Size((1, 5, 768))
self.assertEqual(output.shape, expected_shape)
# compare the actual values for a slice.
expected_slice = torch.tensor(
[[[0.3151, -0.6417, -0.7027], [-0.7834, -1.5810, 0.4576], [1.0614, -0.7268, -0.0871]]]
)
torch.testing.assert_close(output[:, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
@slow
def test_inference_token_classification(self):
if version.parse(torch.__version__) < version.parse("2.4.0"):
self.skipTest(reason="This test requires torch >= 2.4 to run.")
model = ModernBertForTokenClassification.from_pretrained(
"hf-internal-testing/tiny-random-ModernBertForTokenClassification",
reference_compile=False,
attn_implementation="sdpa",
)
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-ModernBertForTokenClassification")
inputs = tokenizer("Hello World!", return_tensors="pt")
with torch.no_grad():
output = model(**inputs)[0]
expected_shape = torch.Size((1, 5, 2))
self.assertEqual(output.shape, expected_shape)
expected = torch.tensor(
[[[2.0159, 4.6569], [-0.9430, 3.1595], [-3.8770, 3.2653], [1.5752, 4.5167], [-1.6939, 1.2524]]]
)
torch.testing.assert_close(output, expected, rtol=1e-4, atol=1e-4)
@slow
def test_inference_sequence_classification(self):
if version.parse(torch.__version__) < version.parse("2.4.0"):
self.skipTest(reason="This test requires torch >= 2.4 to run.")
model = ModernBertForSequenceClassification.from_pretrained(
"hf-internal-testing/tiny-random-ModernBertForSequenceClassification",
reference_compile=False,
attn_implementation="sdpa",
)
tokenizer = AutoTokenizer.from_pretrained(
"hf-internal-testing/tiny-random-ModernBertForSequenceClassification"
)
inputs = tokenizer("Hello World!", return_tensors="pt")
with torch.no_grad():
output = model(**inputs)[0]
expected_shape = torch.Size((1, 2))
self.assertEqual(output.shape, expected_shape)
expected = torch.tensor([[1.6466, 4.5662]])
torch.testing.assert_close(output, expected, rtol=1e-4, atol=1e-4)
@pytest.mark.torch_export_test
@slow
def test_export(self):
if version.parse(torch.__version__) < version.parse("2.4.0"):
self.skipTest(reason="This test requires torch >= 2.4 to run.")
bert_model = "answerdotai/ModernBERT-base"
device = "cpu"
attn_implementation = "sdpa"
max_length = 512
tokenizer = AutoTokenizer.from_pretrained(bert_model)
inputs = tokenizer(
"the man worked as a [MASK].",
return_tensors="pt",
padding="max_length",
max_length=max_length,
)
model = ModernBertForMaskedLM.from_pretrained(
bert_model,
device_map=device,
attn_implementation=attn_implementation,
)
logits = model(**inputs).logits
eg_predicted_mask = tokenizer.decode(logits[0, 6].topk(5).indices)
self.assertEqual(eg_predicted_mask.split(), ["lawyer", "mechanic", "teacher", "doctor", "waiter"])
exported_program = torch.export.export(
model,
args=(inputs["input_ids"],),
kwargs={"attention_mask": inputs["attention_mask"]},
strict=True,
)
result = exported_program.module().forward(inputs["input_ids"], inputs["attention_mask"])
ep_predicted_mask = tokenizer.decode(result.logits[0, 6].topk(5).indices)
self.assertEqual(eg_predicted_mask, ep_predicted_mask)
@slow
def test_inference_multiple_choice(self):
if version.parse(torch.__version__) < version.parse("2.4.0"):
self.skipTest(reason="This test requires torch >= 2.4 to run.")
tokenizer = AutoTokenizer.from_pretrained("answerdotai/ModernBERT-base")
model = (
ModernBertForMultipleChoice.from_pretrained(
"netique/ModernBertForMultipleChoice",
reference_compile=False,
attn_implementation="sdpa",
)
.eval()
.to(torch_device)
)
prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
choices = [
"It is eaten with a fork and a knife.",
"It is eaten while held in the hand.",
"It also walks on the sidewalks.",
"It is a common drink.",
]
labels = torch.tensor([0], device=torch_device)
encoding = tokenizer([prompt for _ in choices], choices, return_tensors="pt", padding=True)
outputs = model(**{k: v.unsqueeze(0).to(torch_device) for k, v in encoding.items()}, labels=labels)
expected_logits = torch.tensor([[0.1973, 0.2041, 0.1835, 0.1896]])
logits = outputs.logits.to("cpu")
self.assertTrue(
torch.allclose(logits, expected_logits, atol=1e-4, rtol=1e-4),
f"Logits: {logits.tolist()}\nExpected: {expected_logits.tolist()}",
)
| ModernBertModelIntegrationTest |
python | kamyu104__LeetCode-Solutions | Python/last-day-where-you-can-still-cross.py | {
"start": 865,
"end": 1937
} | class ____(object):
def latestDayToCross(self, row, col, cells):
"""
:type row: int
:type col: int
:type cells: List[List[int]]
:rtype: int
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def index(n, i, j):
return i*n+j
start, end = row*col, row*col+1
uf = UnionFind(row*col+2)
lookup = [[False]*col for _ in xrange(row)]
for i in reversed(xrange(len(cells))):
r, c = cells[i]
r, c = r-1, c-1
for dr, dc in directions:
nr, nc = r+dr, c+dc
if not (0 <= nr < row and 0 <= nc < col and lookup[nr][nc]):
continue
uf.union_set(index(col, r, c), index(col, nr, nc))
if r == 0:
uf.union_set(start, index(col, r, c))
if r == row-1:
uf.union_set(end, index(col, r, c))
if uf.find_set(start) == uf.find_set(end):
return i
lookup[r][c] = True
return -1
| Solution |
python | pytorch__pytorch | tools/experimental/torchfuzz/operators/masked_select.py | {
"start": 160,
"end": 2670
} | class ____(Operator):
"""Operator for selecting elements from a tensor based on a mask."""
def __init__(self):
super().__init__("masked_select")
@property
def torch_op_name(self) -> str | None:
"""Return the torch operation name."""
return "torch.masked_select"
def can_produce(self, output_spec: Spec) -> bool:
"""Masked select produces a 1D tensor; we'll synthesize inputs to match size."""
return isinstance(output_spec, TensorSpec) and len(output_spec.size) == 1
def fuzz_inputs_specs(self, output_spec: Spec, num_inputs: int = 2) -> list[Spec]:
"""Generate input specs for masked_select operation."""
if not isinstance(output_spec, TensorSpec):
raise ValueError("MaskedSelectOperator can only produce TensorSpec outputs")
# Input tensor - can be any shape and type
input_tensor_spec = TensorSpec(
size=(2, 3), # Fixed size for consistency
stride=(3, 1), # Contiguous
dtype=output_spec.dtype, # Match output dtype
)
# Mask tensor - must be boolean and broadcastable to input
mask_spec = TensorSpec(
size=(2, 3), # Same size as input for simplicity
stride=(3, 1), # Contiguous
dtype=torch.bool,
)
return [input_tensor_spec, mask_spec]
def codegen(
self, output_name: str, input_names: list[str], output_spec: Spec
) -> str:
"""Generate code for masked_select with synthesized inputs to match size.
Constructs an input tensor and mask so that exactly k elements are selected,
where k = output_spec.size[0]. No data-dependent guards.
"""
if len(input_names) != 2:
raise ValueError("MaskedSelectOperator requires exactly two inputs")
if not isinstance(output_spec, TensorSpec) or len(output_spec.size) != 1:
raise ValueError("MaskedSelectOperator requires 1D TensorSpec output")
k = output_spec.size[0]
# Build a 1D input of length >= k and a mask with first k positions True
# Use input's device and output dtype to avoid mismatches
return (
f"_x_ms = torch.arange(max({k}, 1), device={input_names[0]}.device).to({input_names[0]}.dtype)\n"
f"_mask_ms = torch.zeros_like(_x_ms, dtype=torch.bool)\n"
f"_mask_ms[:{k}] = True\n"
f"{output_name} = torch.masked_select(_x_ms, _mask_ms)"
)
| MaskedSelectOperator |
python | allegroai__clearml | clearml/automation/auto_scaler.py | {
"start": 1361,
"end": 1489
} | class ____(str, Enum):
STARTING = "starting"
READY = "ready"
RUNNING = "running"
STOPPED = "stopped"
@attr.s
| State |
python | ray-project__ray | rllib/core/models/catalog.py | {
"start": 1071,
"end": 27260
} | class ____:
"""Describes the sub-module-architectures to be used in RLModules.
RLlib's native RLModules get their Models from a Catalog object.
By default, that Catalog builds the configs it has as attributes.
This component was build to be hackable and extensible. You can inject custom
components into RL Modules by overriding the `build_xxx` methods of this class.
Note that it is recommended to write a custom RL Module for a single use-case.
Modifications to Catalogs mostly make sense if you want to reuse the same
Catalog for different RL Modules. For example if you have written a custom
encoder and want to inject it into different RL Modules (e.g. for PPO, DQN, etc.).
You can influence the decision tree that determines the sub-components by modifying
`Catalog._determine_components_hook`.
Usage example:
# Define a custom catalog
.. testcode::
import torch
import gymnasium as gym
from ray.rllib.core.models.configs import MLPHeadConfig
from ray.rllib.core.models.catalog import Catalog
class MyCatalog(Catalog):
def __init__(
self,
observation_space: gym.Space,
action_space: gym.Space,
model_config_dict: dict,
):
super().__init__(observation_space, action_space, model_config_dict)
self.my_model_config = MLPHeadConfig(
hidden_layer_dims=[64, 32],
input_dims=[self.observation_space.shape[0]],
)
def build_my_head(self, framework: str):
return self.my_model_config.build(framework=framework)
# With that, RLlib can build and use models from this catalog like this:
catalog = MyCatalog(gym.spaces.Box(0, 1), gym.spaces.Box(0, 1), {})
my_head = catalog.build_my_head(framework="torch")
# Make a call to the built model.
out = my_head(torch.Tensor([[1]]))
"""
# TODO (Sven): Add `framework` arg to c'tor and remove this arg from `build`
# methods. This way, we can already know in the c'tor of Catalog, what the exact
# action distibution objects are and thus what the output dims for e.g. a pi-head
# will be.
def __init__(
self,
observation_space: gym.Space,
action_space: gym.Space,
model_config_dict: dict,
# deprecated args.
view_requirements=DEPRECATED_VALUE,
):
"""Initializes a Catalog with a default encoder config.
Args:
observation_space: The observation space of the environment.
action_space: The action space of the environment.
model_config_dict: The model config that specifies things like hidden
dimensions and activations functions to use in this Catalog.
"""
if view_requirements != DEPRECATED_VALUE:
deprecation_warning(old="Catalog(view_requirements=..)", error=True)
# TODO (sven): The following logic won't be needed anymore, once we get rid of
# Catalogs entirely. We will assert directly inside the algo's DefaultRLModule
# class that the `model_config` is a DefaultModelConfig. Thus users won't be
# able to pass in partial config dicts into a default model (alternatively, we
# could automatically augment the user provided dict by the default config
# dataclass object only(!) for default modules).
if dataclasses.is_dataclass(model_config_dict):
model_config_dict = dataclasses.asdict(model_config_dict)
default_config = dataclasses.asdict(DefaultModelConfig())
# end: TODO
self.observation_space = observation_space
self.action_space = action_space
self._model_config_dict = default_config | model_config_dict
self._latent_dims = None
self._determine_components_hook()
@OverrideToImplementCustomLogic_CallToSuperRecommended
def _determine_components_hook(self):
"""Decision tree hook for subclasses to override.
By default, this method executes the decision tree that determines the
components that a Catalog builds. You can extend the components by overriding
this or by adding to the constructor of your subclass.
Override this method if you don't want to use the default components
determined here. If you want to use them but add additional components, you
should call `super()._determine_components()` at the beginning of your
implementation.
This makes it so that subclasses are not forced to create an encoder config
if the rest of their catalog is not dependent on it or if it breaks.
At the end of this method, an attribute `Catalog.latent_dims`
should be set so that heads can be built using that information.
"""
self._encoder_config = self._get_encoder_config(
observation_space=self.observation_space,
action_space=self.action_space,
model_config_dict=self._model_config_dict,
)
# Create a function that can be called when framework is known to retrieve the
# class type for action distributions
self._action_dist_class_fn = functools.partial(
self._get_dist_cls_from_action_space, action_space=self.action_space
)
# The dimensions of the latent vector that is output by the encoder and fed
# to the heads.
self.latent_dims = self._encoder_config.output_dims
@property
def latent_dims(self):
"""Returns the latent dimensions of the encoder.
This establishes an agreement between encoder and heads about the latent
dimensions. Encoders can be built to output a latent tensor with
`latent_dims` dimensions, and heads can be built with tensors of
`latent_dims` dimensions as inputs. This can be safely ignored if this
agreement is not needed in case of modifications to the Catalog.
Returns:
The latent dimensions of the encoder.
"""
return self._latent_dims
@latent_dims.setter
def latent_dims(self, value):
self._latent_dims = value
@OverrideToImplementCustomLogic
def build_encoder(self, framework: str) -> Encoder:
"""Builds the encoder.
By default, this method builds an encoder instance from Catalog._encoder_config.
You should override this if you want to use RLlib's default RL Modules but
only want to change the encoder. For example, if you want to use a custom
encoder, but want to use RLlib's default heads, action distribution and how
tensors are routed between them. If you want to have full control over the
RL Module, we recommend writing your own RL Module by inheriting from one of
RLlib's RL Modules instead.
Args:
framework: The framework to use. Either "torch" or "tf2".
Returns:
The encoder.
"""
assert hasattr(self, "_encoder_config"), (
"You must define a `Catalog._encoder_config` attribute in your Catalog "
"subclass or override the `Catalog.build_encoder` method. By default, "
"an encoder_config is created in the __post_init__ method."
)
return self._encoder_config.build(framework=framework)
@OverrideToImplementCustomLogic
def get_action_dist_cls(self, framework: str):
"""Get the action distribution class.
The default behavior is to get the action distribution from the
`Catalog._action_dist_class_fn`.
You should override this to have RLlib build your custom action
distribution instead of the default one. For example, if you don't want to
use RLlib's default RLModules with their default models, but only want to
change the distribution that Catalog returns.
Args:
framework: The framework to use. Either "torch" or "tf2".
Returns:
The action distribution.
"""
assert hasattr(self, "_action_dist_class_fn"), (
"You must define a `Catalog._action_dist_class_fn` attribute in your "
"Catalog subclass or override the `Catalog.action_dist_class_fn` method. "
"By default, an action_dist_class_fn is created in the __post_init__ "
"method."
)
return self._action_dist_class_fn(framework=framework)
@classmethod
def _get_encoder_config(
cls,
observation_space: gym.Space,
model_config_dict: dict,
action_space: gym.Space = None,
) -> ModelConfig:
"""Returns an EncoderConfig for the given input_space and model_config_dict.
Encoders are usually used in RLModules to transform the input space into a
latent space that is then fed to the heads. The returned EncoderConfig
objects correspond to the built-in Encoder classes in RLlib.
For example, for a simple 1D-Box input_space, RLlib offers an
MLPEncoder, hence this method returns the MLPEncoderConfig. You can overwrite
this method to produce specific EncoderConfigs for your custom Models.
The following input spaces lead to the following configs:
- 1D-Box: MLPEncoderConfig
- 3D-Box: CNNEncoderConfig
# TODO (Artur): Support more spaces here
# ...
Args:
observation_space: The observation space to use.
model_config_dict: The model config to use.
action_space: The action space to use if actions are to be encoded. This
is commonly the case for LSTM models.
Returns:
The encoder config.
"""
activation = model_config_dict["fcnet_activation"]
output_activation = model_config_dict["fcnet_activation"]
use_lstm = model_config_dict["use_lstm"]
if use_lstm:
encoder_config = RecurrentEncoderConfig(
input_dims=observation_space.shape,
recurrent_layer_type="lstm",
hidden_dim=model_config_dict["lstm_cell_size"],
hidden_weights_initializer=model_config_dict["lstm_kernel_initializer"],
hidden_weights_initializer_config=model_config_dict[
"lstm_kernel_initializer_kwargs"
],
hidden_bias_initializer=model_config_dict["lstm_bias_initializer"],
hidden_bias_initializer_config=model_config_dict[
"lstm_bias_initializer_kwargs"
],
batch_major=True,
num_layers=1,
tokenizer_config=cls.get_tokenizer_config(
observation_space,
model_config_dict,
),
)
else:
# TODO (Artur): Maybe check for original spaces here
# input_space is a 1D Box
if isinstance(observation_space, Box) and len(observation_space.shape) == 1:
# In order to guarantee backward compatability with old configs,
# we need to check if no latent dim was set and simply reuse the last
# fcnet hidden dim for that purpose.
hidden_layer_dims = model_config_dict["fcnet_hiddens"][:-1]
encoder_latent_dim = model_config_dict["fcnet_hiddens"][-1]
encoder_config = MLPEncoderConfig(
input_dims=observation_space.shape,
hidden_layer_dims=hidden_layer_dims,
hidden_layer_activation=activation,
hidden_layer_weights_initializer=model_config_dict[
"fcnet_kernel_initializer"
],
hidden_layer_weights_initializer_config=model_config_dict[
"fcnet_kernel_initializer_kwargs"
],
hidden_layer_bias_initializer=model_config_dict[
"fcnet_bias_initializer"
],
hidden_layer_bias_initializer_config=model_config_dict[
"fcnet_bias_initializer_kwargs"
],
output_layer_dim=encoder_latent_dim,
output_layer_activation=output_activation,
output_layer_weights_initializer=model_config_dict[
"fcnet_kernel_initializer"
],
output_layer_weights_initializer_config=model_config_dict[
"fcnet_kernel_initializer_kwargs"
],
output_layer_bias_initializer=model_config_dict[
"fcnet_bias_initializer"
],
output_layer_bias_initializer_config=model_config_dict[
"fcnet_bias_initializer_kwargs"
],
)
# input_space is a 3D Box
elif (
isinstance(observation_space, Box) and len(observation_space.shape) == 3
):
if not model_config_dict.get("conv_filters"):
model_config_dict["conv_filters"] = get_filter_config(
observation_space.shape
)
encoder_config = CNNEncoderConfig(
input_dims=observation_space.shape,
cnn_filter_specifiers=model_config_dict["conv_filters"],
cnn_activation=model_config_dict["conv_activation"],
cnn_kernel_initializer=model_config_dict["conv_kernel_initializer"],
cnn_kernel_initializer_config=model_config_dict[
"conv_kernel_initializer_kwargs"
],
cnn_bias_initializer=model_config_dict["conv_bias_initializer"],
cnn_bias_initializer_config=model_config_dict[
"conv_bias_initializer_kwargs"
],
)
# input_space is a 2D Box
elif (
isinstance(observation_space, Box) and len(observation_space.shape) == 2
):
# RLlib used to support 2D Box spaces by silently flattening them
raise ValueError(
f"No default encoder config for obs space={observation_space},"
f" lstm={use_lstm} found. 2D Box "
f"spaces are not supported. They should be either flattened to a "
f"1D Box space or enhanced to be a 3D box space."
)
# input_space is a possibly nested structure of spaces.
else:
# NestedModelConfig
raise ValueError(
f"No default encoder config for obs space={observation_space},"
f" lstm={use_lstm} found."
)
return encoder_config
@classmethod
@OverrideToImplementCustomLogic
def get_tokenizer_config(
cls,
observation_space: gym.Space,
model_config_dict: dict,
# deprecated args.
view_requirements=DEPRECATED_VALUE,
) -> ModelConfig:
"""Returns a tokenizer config for the given space.
This is useful for recurrent / transformer models that need to tokenize their
inputs. By default, RLlib uses the models supported by Catalog out of the box to
tokenize.
You should override this method if you want to change the custom tokenizer
inside current encoders that Catalog returns without providing the recurrent
network as a whole. For example, if you want to define some custom CNN layers
as a tokenizer for a recurrent encoder that already includes the recurrent
layers and handles the state.
Args:
observation_space: The observation space to use.
model_config_dict: The model config to use.
"""
if view_requirements != DEPRECATED_VALUE:
deprecation_warning(old="Catalog(view_requirements=..)", error=True)
return cls._get_encoder_config(
observation_space=observation_space,
# Use model_config_dict without flags that would end up in complex models
model_config_dict={
**model_config_dict,
**{"use_lstm": False, "use_attention": False},
},
)
@classmethod
def _get_dist_cls_from_action_space(
cls,
action_space: gym.Space,
*,
framework: Optional[str] = None,
) -> Distribution:
"""Returns a distribution class for the given action space.
You can get the required input dimension for the distribution by calling
`action_dict_cls.required_input_dim(action_space)`
on the retrieved class. This is useful, because the Catalog needs to find out
about the required input dimension for the distribution before the model that
outputs these inputs is configured.
Args:
action_space: Action space of the target gym env.
framework: The framework to use.
Returns:
The distribution class for the given action space.
"""
# If no framework provided, return no action distribution class (None).
if framework is None:
return None
# This method is structured in two steps:
# Firstly, construct a dictionary containing the available distribution classes.
# Secondly, return the correct distribution class for the given action space.
# Step 1: Construct the dictionary.
class DistEnum(enum.Enum):
Categorical = "Categorical"
DiagGaussian = "Gaussian"
Deterministic = "Deterministic"
MultiDistribution = "MultiDistribution"
MultiCategorical = "MultiCategorical"
if framework == "torch":
from ray.rllib.core.distribution.torch.torch_distribution import (
TorchCategorical,
TorchDeterministic,
TorchDiagGaussian,
)
distribution_dicts = {
DistEnum.Deterministic: TorchDeterministic,
DistEnum.DiagGaussian: TorchDiagGaussian,
DistEnum.Categorical: TorchCategorical,
}
else:
raise ValueError(
f"Unknown framework: {framework}. Only 'torch' and 'tf2' are "
"supported for RLModule Catalogs."
)
# Only add a MultiAction distribution class to the dict if we can compute its
# components (we need a Tuple/Dict space for this).
if isinstance(action_space, (Tuple, Dict)):
partial_multi_action_distribution_cls = _multi_action_dist_partial_helper(
catalog_cls=cls,
action_space=action_space,
framework=framework,
)
distribution_dicts[
DistEnum.MultiDistribution
] = partial_multi_action_distribution_cls
# Only add a MultiCategorical distribution class to the dict if we can compute
# its components (we need a MultiDiscrete space for this).
if isinstance(action_space, MultiDiscrete):
partial_multi_categorical_distribution_cls = (
_multi_categorical_dist_partial_helper(
action_space=action_space,
framework=framework,
)
)
distribution_dicts[
DistEnum.MultiCategorical
] = partial_multi_categorical_distribution_cls
# Step 2: Return the correct distribution class for the given action space.
# Box space -> DiagGaussian OR Deterministic.
if isinstance(action_space, Box):
if action_space.dtype.char in np.typecodes["AllInteger"]:
raise ValueError(
"Box(..., `int`) action spaces are not supported. "
"Use MultiDiscrete or Box(..., `float`)."
)
else:
if len(action_space.shape) > 1:
raise UnsupportedSpaceException(
f"Action space has multiple dimensions {action_space.shape}. "
f"Consider reshaping this into a single dimension, using a "
f"custom action distribution, using a Tuple action space, "
f"or the multi-agent API."
)
return distribution_dicts[DistEnum.DiagGaussian]
# Discrete Space -> Categorical.
elif isinstance(action_space, Discrete):
return distribution_dicts[DistEnum.Categorical]
# Tuple/Dict Spaces -> MultiAction.
elif isinstance(action_space, (Tuple, Dict)):
return distribution_dicts[DistEnum.MultiDistribution]
# Simplex -> Dirichlet.
elif isinstance(action_space, Simplex):
# TODO(Artur): Supported Simplex (in torch).
raise NotImplementedError("Simplex action space not yet supported.")
# MultiDiscrete -> MultiCategorical.
elif isinstance(action_space, MultiDiscrete):
return distribution_dicts[DistEnum.MultiCategorical]
# Unknown type -> Error.
else:
raise NotImplementedError(f"Unsupported action space: `{action_space}`")
@staticmethod
def get_preprocessor(observation_space: gym.Space, **kwargs) -> Preprocessor:
"""Returns a suitable preprocessor for the given observation space.
Args:
observation_space: The input observation space.
**kwargs: Forward-compatible kwargs.
Returns:
preprocessor: Preprocessor for the observations.
"""
# TODO(Artur): Since preprocessors have long been @PublicAPI with the options
# kwarg as part of their constructor, we fade out support for this,
# beginning with this entrypoint.
# Next, we should deprecate the `options` kwarg from the Preprocessor itself,
# after deprecating the old catalog and other components that still pass this.
options = kwargs.get("options", {})
if options:
deprecation_warning(
old="get_preprocessor_for_space(..., options={...})",
help="Override `Catalog.get_preprocessor()` "
"in order to implement custom behaviour.",
error=False,
)
if options.get("custom_preprocessor"):
deprecation_warning(
old="model_config['custom_preprocessor']",
help="Custom preprocessors are deprecated, "
"since they sometimes conflict with the built-in "
"preprocessors for handling complex observation spaces. "
"Please use wrapper classes around your environment "
"instead.",
error=True,
)
else:
# TODO(Artur): Inline the get_preprocessor() call here once we have
# deprecated the old model catalog.
cls = get_preprocessor(observation_space)
prep = cls(observation_space, options)
return prep
def _multi_action_dist_partial_helper(
catalog_cls: "Catalog", action_space: gym.Space, framework: str
) -> Distribution:
"""Helper method to get a partial of a MultiActionDistribution.
This is useful for when we want to create MultiActionDistributions from
logits only (!) later, but know the action space now already.
Args:
catalog_cls: The ModelCatalog class to use.
action_space: The action space to get the child distribution classes for.
framework: The framework to use.
Returns:
A partial of the TorchMultiActionDistribution class.
"""
action_space_struct = get_base_struct_from_space(action_space)
flat_action_space = flatten_space(action_space)
child_distribution_cls_struct = tree.map_structure(
lambda s: catalog_cls._get_dist_cls_from_action_space(
action_space=s,
framework=framework,
),
action_space_struct,
)
flat_distribution_clses = tree.flatten(child_distribution_cls_struct)
logit_lens = [
int(dist_cls.required_input_dim(space))
for dist_cls, space in zip(flat_distribution_clses, flat_action_space)
]
if framework == "torch":
from ray.rllib.core.distribution.torch.torch_distribution import (
TorchMultiDistribution,
)
multi_action_dist_cls = TorchMultiDistribution
else:
raise ValueError(f"Unsupported framework: {framework}")
partial_dist_cls = multi_action_dist_cls.get_partial_dist_cls(
space=action_space,
child_distribution_cls_struct=child_distribution_cls_struct,
input_lens=logit_lens,
)
return partial_dist_cls
def _multi_categorical_dist_partial_helper(
action_space: gym.Space, framework: str
) -> Distribution:
"""Helper method to get a partial of a MultiCategorical Distribution.
This is useful for when we want to create MultiCategorical Distribution from
logits only (!) later, but know the action space now already.
Args:
action_space: The action space to get the child distribution classes for.
framework: The framework to use.
Returns:
A partial of the MultiCategorical class.
"""
if framework == "torch":
from ray.rllib.core.distribution.torch.torch_distribution import (
TorchMultiCategorical,
)
multi_categorical_dist_cls = TorchMultiCategorical
else:
raise ValueError(f"Unsupported framework: {framework}")
partial_dist_cls = multi_categorical_dist_cls.get_partial_dist_cls(
space=action_space, input_lens=list(action_space.nvec)
)
return partial_dist_cls
| Catalog |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-core/dagster_dg_core/config.py | {
"start": 6812,
"end": 9315
} | class ____:
cli: "DgCliConfig"
project: Optional["DgProjectConfig"] = None
workspace: Optional["DgWorkspaceConfig"] = None
@classmethod
def default(cls) -> Self:
return cls(DgCliConfig.default())
# Note that this function takes an argument called `container_workspace_file_config` instead of
# just `workspace_file_config` because this is only to be passed when the root file config
# points to a project inside of a workspace. If there is no package and the
# root is itself a workspace, then `root_file_config` corresponds to the workspace and
# `container_workspace_file_config` should be None.
@classmethod
def from_partial_configs(
cls,
root_file_config: Optional["DgFileConfig"] = None,
container_workspace_file_config: Optional["DgWorkspaceFileConfig"] = None,
command_line_config: Optional["DgRawCliConfig"] = None,
user_config: Optional["DgRawCliConfig"] = None,
) -> Self:
cli_partials: list[DgRawCliConfig] = []
if container_workspace_file_config:
if "cli" in container_workspace_file_config:
cli_partials.append(container_workspace_file_config["cli"])
workspace_config = DgWorkspaceConfig.from_raw(
container_workspace_file_config["workspace"]
)
if root_file_config:
if "cli" in root_file_config:
cli_partials.append(root_file_config["cli"])
if is_workspace_file_config(root_file_config):
project_config = None
workspace_config = DgWorkspaceConfig.from_raw(root_file_config["workspace"])
elif is_project_file_config(root_file_config):
project_config = DgProjectConfig.from_raw(root_file_config["project"])
if not container_workspace_file_config:
workspace_config = None
else:
project_config = None
workspace_config = None
if command_line_config:
cli_partials.append(command_line_config)
all_cli_config = [user_config, *cli_partials] if user_config else cli_partials
cli_config = (
DgCliConfig.from_raw(*all_cli_config) if all_cli_config else DgCliConfig.default()
)
return cls(cli_config, project_config, workspace_config) # pyright: ignore[reportPossiblyUnboundVariable]
# ########################
# ##### CLI
# ########################
@dataclass
| DgConfig |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-commcare/source_commcare/source.py | {
"start": 4609,
"end": 7778
} | class ____(IncrementalStream):
"""
docs: https://www.commcarehq.org/a/[domain]/api/[version]/case/
"""
cursor_field = "indexed_on"
primary_key = "id"
def __init__(self, start_date, app_id, schema, **kwargs):
super().__init__(**kwargs)
self._cursor_value = datetime.strptime(start_date, "%Y-%m-%dT%H:%M:%SZ")
self.schema = schema
def get_json_schema(self):
return self.schema
@property
def name(self):
# Airbyte orders streams in alpha order but since we have dependent peers and we need to
# pull all forms before cases, we name this stream to
# ensure this stream gets pulled last (assuming ascii stream names only)
return "zzz_case"
def path(
self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None
) -> str:
return "case"
def request_params(
self, stream_state: Mapping[str, Any], stream_slice: Mapping[str, any] = None, next_page_token: Mapping[str, Any] = None
) -> MutableMapping[str, Any]:
# start date is what we saved for forms
# if self.cursor_field in self.state else (CommcareStream.last_form_date or self.initial_date)
ix = self.state[self.cursor_field]
params = {"format": "json", "indexed_on_start": ix.strftime(self.dateformat), "order_by": "indexed_on", "limit": "5000"}
if next_page_token:
params.update(next_page_token)
return params
def read_records(self, *args, **kwargs) -> Iterable[Mapping[str, Any]]:
for record in super().read_records(*args, **kwargs):
found = False
for f in record["xform_ids"]:
if f in CommcareStream.forms:
found = True
break
if found:
self._cursor_value = datetime.strptime(record[self.cursor_field], self.dateformat)
# Make indexed_on tz aware
record.update({"streamname": "case", "indexed_on": record["indexed_on"] + "Z"})
# convert xform_ids field from array to comma separated list so flattening won't create
# one field per item. This is because some cases have up to 2000 xform_ids and we don't want 2000 extra
# fields in the schema
record["xform_ids"] = ",".join(record["xform_ids"])
frec = flatten(record)
yield frec
if self._cursor_value.microsecond == 0:
# Airbyte converts the cursor_field value (datetime) to string when it saves the state and
# our state setter parses the saved state with a format that contains microseconds
# self._cursor_value must have non-zero microseconds for the formatting and parsing to work correctly.
# This issue would also occur if an incoming record had a timestamp with zero microseconds
self._cursor_value = self._cursor_value.replace(microsecond=10)
# This cycle of pull is complete so clear out the form ids we saved for this cycle
CommcareStream.forms.clear()
| Case |
python | coleifer__peewee | tests/db_tests.py | {
"start": 33002,
"end": 33406
} | class ____(ModelTestCase):
database = get_in_memory_db()
requires = [User]
def test_exception_wrapper(self):
exc = None
try:
User.create(username=None)
except IntegrityError as e:
exc = e
if exc is None: raise Exception('expected integrity error not raised')
self.assertTrue(exc.orig.__module__ != 'peewee')
| TestExceptionWrapper |
python | django__django | tests/null_fk_ordering/models.py | {
"start": 288,
"end": 362
} | class ____(models.Model):
name = models.CharField(max_length=150)
| Author |
python | openai__openai-python | src/openai/types/responses/response_mcp_call_in_progress_event.py | {
"start": 207,
"end": 638
} | class ____(BaseModel):
item_id: str
"""The unique identifier of the MCP tool call item being processed."""
output_index: int
"""The index of the output item in the response's output array."""
sequence_number: int
"""The sequence number of this event."""
type: Literal["response.mcp_call.in_progress"]
"""The type of the event. Always 'response.mcp_call.in_progress'."""
| ResponseMcpCallInProgressEvent |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/metrics_test.py | {
"start": 169487,
"end": 171485
} | class ____(test.TestCase):
def setUp(self):
np.random.seed(1)
ops.reset_default_graph()
@test_util.run_deprecated_v1
def testVars(self):
metrics.false_positives(
labels=(0, 1, 0, 1),
predictions=(0, 0, 1, 1))
_assert_metric_variables(self, ('false_positives/count:0',))
@test_util.run_deprecated_v1
def testUnweighted(self):
labels = constant_op.constant(((0, 1, 0, 1, 0),
(0, 0, 1, 1, 1),
(1, 1, 1, 1, 0),
(0, 0, 0, 0, 1)))
predictions = constant_op.constant(((0, 0, 1, 1, 0),
(1, 1, 1, 1, 1),
(0, 1, 0, 1, 0),
(1, 1, 1, 1, 1)))
tn, tn_update_op = metrics.false_positives(
labels=labels, predictions=predictions)
with self.cached_session():
self.evaluate(variables.local_variables_initializer())
self.assertAllClose(0., tn)
self.assertAllClose(7., tn_update_op)
self.assertAllClose(7., tn)
@test_util.run_deprecated_v1
def testWeighted(self):
labels = constant_op.constant(((0, 1, 0, 1, 0),
(0, 0, 1, 1, 1),
(1, 1, 1, 1, 0),
(0, 0, 0, 0, 1)))
predictions = constant_op.constant(((0, 0, 1, 1, 0),
(1, 1, 1, 1, 1),
(0, 1, 0, 1, 0),
(1, 1, 1, 1, 1)))
weights = constant_op.constant((1., 1.5, 2., 2.5))
tn, tn_update_op = metrics.false_positives(
labels=labels, predictions=predictions, weights=weights)
with self.cached_session():
self.evaluate(variables.local_variables_initializer())
self.assertAllClose(0., tn)
self.assertAllClose(14., tn_update_op)
self.assertAllClose(14., tn)
| FalsePositivesTest |
python | spyder-ide__spyder | spyder/plugins/debugger/widgets/framesbrowser.py | {
"start": 1024,
"end": 1144
} | class ____:
Debug = 'debug'
DebugWait = 'debugwait'
Inspect = 'inspect'
Error = 'error'
| FramesBrowserState |
python | numba__numba | numba/tests/test_listobject.py | {
"start": 36699,
"end": 38574
} | class ____(MemoryLeakMixin, TestCase):
"""Test list equal and not equal. """
def test_list_empty_equal(self):
@njit
def foo():
t = listobject.new_list(int32)
o = listobject.new_list(int32)
return t == o, t != o
self.assertEqual(foo(), (True, False))
def test_list_singleton_equal(self):
@njit
def foo():
t = listobject.new_list(int32)
t.append(0)
o = listobject.new_list(int32)
o.append(0)
return t == o, t != o
self.assertEqual(foo(), (True, False))
def test_list_singleton_not_equal(self):
@njit
def foo():
t = listobject.new_list(int32)
t.append(0)
o = listobject.new_list(int32)
o.append(1)
return t == o, t != o
self.assertEqual(foo(), (False, True))
def test_list_length_mismatch(self):
@njit
def foo():
t = listobject.new_list(int32)
t.append(0)
o = listobject.new_list(int32)
return t == o, t != o
self.assertEqual(foo(), (False, True))
def test_list_multiple_equal(self):
@njit
def foo():
t = listobject.new_list(int32)
o = listobject.new_list(int32)
for i in range(10):
t.append(i)
o.append(i)
return t == o, t != o
self.assertEqual(foo(), (True, False))
def test_list_multiple_not_equal(self):
@njit
def foo():
t = listobject.new_list(int32)
o = listobject.new_list(int32)
for i in range(10):
t.append(i)
o.append(i)
o[-1] = 42
return t == o, t != o
self.assertEqual(foo(), (False, True))
| TestEqualNotEqual |
python | huggingface__transformers | src/transformers/models/zamba2/modeling_zamba2.py | {
"start": 49862,
"end": 53359
} | class ____(nn.Module):
def __init__(self, config: Zamba2Config, block_id: Optional[int] = None, layer_idx: Optional[int] = None):
super().__init__()
self.block_id = block_id
num_gs = len(config.hybrid_layer_ids)
self.self_attn = Zamba2Attention(config, layer_idx=-1, num_fwd_mem_blocks=num_gs, block_id=block_id)
self.feed_forward = Zamba2MLP(config, num_fwd_mem_blocks=num_gs, block_id=block_id)
self.input_layernorm = Zamba2RMSNorm(config.attention_hidden_size, eps=config.rms_norm_eps)
self.pre_ff_layernorm = Zamba2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
original_hidden_states: torch.Tensor,
layer_idx: int,
attention_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[Zamba2HybridDynamicCache] = None,
output_attentions: Optional[bool] = False,
position_embeddings: Optional[torch.LongTensor] = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
"""
Args:
hidden_states (`torch.FloatTensor`): output of previous Mamba layer of shape `(batch, seq_len, embed_dim)`
original_hidden_states (`torch.FloatTensor`): word embedding output of shape `(batch, seq_len, embed_dim)`.
This is concatenated with `hidden_states` (which is the output of the previous (mamba) layer). The
concatenated tensor is then used as input of the pre-attention RMSNorm
(see fig. 2 in https://huggingface.co/papers/2405.16712).
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
`(batch, sequence_length)` where padding elements are indicated by 0.
past_key_values (`Zamba2HybridDynamicCache`, *optional*): cached past key and value projection states
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
use_cache (`bool`, *optional*):
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
(see `past_key_values`).
position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
with `head_dim` being the embedding dimension of each attention head.
"""
hidden_states = torch.concatenate([hidden_states, original_hidden_states], dim=-1)
hidden_states = self.input_layernorm(hidden_states)
hidden_states, self_attn_weights = self.self_attn(
hidden_states=hidden_states,
layer_idx=layer_idx,
attention_mask=attention_mask,
past_key_values=past_key_values,
output_attentions=output_attentions,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = self.pre_ff_layernorm(hidden_states)
hidden_states = self.feed_forward(hidden_states, layer_idx)
outputs = (hidden_states,)
if output_attentions:
outputs += (self_attn_weights,)
return outputs
| Zamba2AttentionDecoderLayer |
python | Lightning-AI__lightning | tests/tests_pytorch/strategies/test_model_parallel_integration.py | {
"start": 3755,
"end": 4034
} | class ____(TemplateModel):
def configure_model(self):
parallelize = _parallelize_feed_forward_tp
if self._compile:
parallelize = _parallelize_with_compile(parallelize)
parallelize(self.model, device_mesh=self.device_mesh)
| TensorParallelModel |
python | mlflow__mlflow | mlflow/utils/gorilla.py | {
"start": 4837,
"end": 24049
} | class ____:
"""Describe all the information required to apply a patch.
Attributes
----------
destination : obj
Patch destination.
name : str
Name of the attribute at the destination.
obj : obj
Attribute value.
settings : gorilla.Settings or None
Settings. If ``None``, the default settings are used.
Warning
-------
It is highly recommended to use the output of the function
:func:`get_attribute` for setting the attribute :attr:`obj`. This will
ensure that the descriptor protocol is bypassed instead of possibly
retrieving attributes invalid for patching, such as bound methods.
"""
def __init__(self, destination, name, obj, settings=None):
"""Constructor.
Parameters
----------
destination : object
See the :attr:`~Patch.destination` attribute.
name : str
See the :attr:`~Patch.name` attribute.
obj : object
See the :attr:`~Patch.obj` attribute.
settings : gorilla.Settings
See the :attr:`~Patch.settings` attribute.
"""
self.destination = destination
self.name = name
self.obj = obj
self.settings = settings
self.is_inplace_patch = None
def __repr__(self):
return "{}(destination={!r}, name={!r}, obj={!r}, settings={!r})".format(
type(self).__name__,
self.destination,
self.name,
self.obj,
self.settings,
)
def __eq__(self, other):
if isinstance(other, type(self)):
return self.__dict__ == other.__dict__
return NotImplemented
def __ne__(self, other):
is_equal = self.__eq__(other)
return is_equal if is_equal is NotImplemented else not is_equal
def __hash__(self):
return super().__hash__()
def _update(self, **kwargs):
"""Update some attributes.
If a 'settings' attribute is passed as a dict, then it will update the
content of the settings, if any, instead of completely overwriting it.
Parameters
----------
kwargs
Attributes to update.
Raises
------
ValueError
The setting doesn't exist.
"""
for key, value in _iteritems(kwargs):
if key == "settings":
if isinstance(value, dict):
if self.settings is None:
self.settings = Settings(**value)
else:
self.settings._update(**value)
else:
self.settings = copy.deepcopy(value)
else:
setattr(self, key, value)
def apply(patch):
"""Apply a patch.
The patch's :attr:`~Patch.obj` attribute is injected into the patch's
:attr:`~Patch.destination` under the patch's :attr:`~Patch.name`.
This is a wrapper around calling
``setattr(patch.destination, patch.name, patch.obj)``.
Parameters
----------
patch : gorilla.Patch
Patch.
Raises
------
RuntimeError
Overwriting an existing attribute is not allowed when the setting
:attr:`Settings.allow_hit` is set to ``True``.
Note
----
If both the attributes :attr:`Settings.allow_hit` and
:attr:`Settings.store_hit` are ``True`` but that the target attribute seems
to have already been stored, then it won't be stored again to avoid losing
the original attribute that was stored the first time around.
"""
# is_inplace_patch = True represents the patch object will overwrite the original
# attribute
patch.is_inplace_patch = patch.name in patch.destination.__dict__
settings = Settings() if patch.settings is None else patch.settings
curr_active_patch = _ACTIVE_PATCH % (patch.name,)
if curr_active_patch in patch.destination.__dict__:
_logger.debug(
f"Patch {patch.name} on {destination.__name__} already existed. Overwrite old patch."
)
# When a hit occurs due to an attribute at the destination already existing
# with the patch's name, the existing attribute is referred to as 'target'.
try:
target = get_original_attribute(
patch.destination, patch.name, bypass_descriptor_protocol=True
)
except AttributeError:
pass
else:
if not settings.allow_hit:
raise RuntimeError(
"An attribute named '%s' already exists at the destination " # noqa: UP031
"'%s'. Set a different name through the patch object to avoid "
"a name clash or set the setting 'allow_hit' to True to "
"overwrite the attribute. In the latter case, it is "
"recommended to also set the 'store_hit' setting to True in "
"order to store the original attribute under a different "
"name so it can still be accessed." % (patch.name, patch.destination.__name__)
)
if settings.store_hit:
original_name = _ORIGINAL_NAME % (patch.name,)
setattr(patch.destination, original_name, target)
setattr(patch.destination, patch.name, patch.obj)
setattr(patch.destination, curr_active_patch, patch)
def revert(patch):
"""Revert a patch.
Parameters
----------
patch : gorilla.Patch
Patch.
Note
----
This is only possible if the attribute :attr:`Settings.store_hit` was set
to ``True`` when applying the patch and overriding an existing attribute.
Notice:
This method is taken from
https://github.com/christophercrouzet/gorilla/blob/v0.4.0/gorilla.py#L318-L351
with modifictions for autologging disablement purposes.
"""
# If an curr_active_patch has not been set on destination class for the current patch,
# then the patch has not been applied and we do not need to revert anything.
curr_active_patch = _ACTIVE_PATCH % (patch.name,)
if curr_active_patch not in patch.destination.__dict__:
# already reverted.
return
original_name = _ORIGINAL_NAME % (patch.name,)
if patch.is_inplace_patch:
# check whether original_name is in destination. We cannot use hasattr because it will
# try to get attribute from parent classes if attribute not found in destination class.
if original_name not in patch.destination.__dict__:
raise RuntimeError(
"Cannot revert the attribute named '%s' since the setting " # noqa: UP031
"'store_hit' was not set to True when applying the patch."
% (patch.destination.__name__,)
)
# restore original method
# during reverting patch, we need restore the raw attribute to the patch point
# so get original attribute bypassing descriptor protocal
original = object.__getattribute__(patch.destination, original_name)
setattr(patch.destination, patch.name, original)
else:
# delete patched method
delattr(patch.destination, patch.name)
if original_name in patch.destination.__dict__:
delattr(patch.destination, original_name)
delattr(patch.destination, curr_active_patch)
def patch(destination, name=None, settings=None):
"""Decorator to create a patch.
The object being decorated becomes the :attr:`~Patch.obj` attribute of the
patch.
Parameters
----------
destination : object
Patch destination.
name : str
Name of the attribute at the destination.
settings : gorilla.Settings
Settings.
Returns
-------
object
The decorated object.
See Also
--------
:class:`Patch`.
"""
def decorator(wrapped):
base = _get_base(wrapped)
name_ = base.__name__ if name is None else name
settings_ = copy.deepcopy(settings)
patch = Patch(destination, name_, wrapped, settings=settings_)
data = get_decorator_data(base, set_default=True)
data.patches.append(patch)
return wrapped
return decorator
def destination(value):
"""Modifier decorator to update a patch's destination.
This only modifies the behaviour of the :func:`create_patches` function
and the :func:`patches` decorator, given that their parameter
``use_decorators`` is set to ``True``.
Parameters
----------
value : object
Patch destination.
Returns
-------
object
The decorated object.
"""
def decorator(wrapped):
data = get_decorator_data(_get_base(wrapped), set_default=True)
data.override["destination"] = value
return wrapped
return decorator
def name(value):
"""Modifier decorator to update a patch's name.
This only modifies the behaviour of the :func:`create_patches` function
and the :func:`patches` decorator, given that their parameter
``use_decorators`` is set to ``True``.
Parameters
----------
value : object
Patch name.
Returns
-------
object
The decorated object.
"""
def decorator(wrapped):
data = get_decorator_data(_get_base(wrapped), set_default=True)
data.override["name"] = value
return wrapped
return decorator
def settings(**kwargs):
"""Modifier decorator to update a patch's settings.
This only modifies the behaviour of the :func:`create_patches` function
and the :func:`patches` decorator, given that their parameter
``use_decorators`` is set to ``True``.
Parameters
----------
kwargs
Settings to update. See :class:`Settings` for the list.
Returns
-------
object
The decorated object.
"""
def decorator(wrapped):
data = get_decorator_data(_get_base(wrapped), set_default=True)
data.override.setdefault("settings", {}).update(kwargs)
return wrapped
return decorator
def filter(value):
"""Modifier decorator to force the inclusion or exclusion of an attribute.
This only modifies the behaviour of the :func:`create_patches` function
and the :func:`patches` decorator, given that their parameter
``use_decorators`` is set to ``True``.
Parameters
----------
value : bool
``True`` to force inclusion, ``False`` to force exclusion, and ``None``
to inherit from the behaviour defined by :func:`create_patches` or
:func:`patches`.
Returns
-------
object
The decorated object.
"""
def decorator(wrapped):
data = get_decorator_data(_get_base(wrapped), set_default=True)
data.filter = value
return wrapped
return decorator
def find_patches(modules, recursive=True):
"""Find all the patches created through decorators.
Parameters
----------
modules : list of module
Modules and/or packages to search the patches in.
recursive : bool
``True`` to search recursively in subpackages.
Returns
-------
list of gorilla.Patch
Patches found.
Raises
------
TypeError
The input is not a valid package or module.
See Also
--------
:func:`patch`, :func:`patches`.
"""
out = []
modules = (
module for package in modules for module in _module_iterator(package, recursive=recursive)
)
for module in modules:
members = _get_members(module, filter=None)
for _, value in members:
base = _get_base(value)
decorator_data = get_decorator_data(base)
if decorator_data is None:
continue
out.extend(decorator_data.patches)
return out
def get_original_attribute(obj, name, bypass_descriptor_protocol=False):
"""Retrieve an overridden attribute that has been stored.
Parameters
----------
obj : object
Object to search the attribute in.
name : str
Name of the attribute.
bypass_descriptor_protocol: boolean
bypassing descriptor protocol if true. When storing original method during patching or
restoring original method during reverting patch, we need set bypass_descriptor_protocol
to be True to ensure get the raw attribute object.
Returns
-------
object
The attribute found.
Raises
------
AttributeError
The attribute couldn't be found.
Note
----
if setting store_hit=False, then after patch applied, this methods may return patched
attribute instead of original attribute in specific cases.
See Also
--------
:attr:`Settings.allow_hit`.
"""
original_name = _ORIGINAL_NAME % (name,)
curr_active_patch = _ACTIVE_PATCH % (name,)
def _get_attr(obj_, name_):
if bypass_descriptor_protocol:
return object.__getattribute__(obj_, name_)
else:
return getattr(obj_, name_)
no_original_stored_err = (
"Original attribute %s was not stored when patching, set store_hit=True will address this."
)
if inspect.isclass(obj):
# Search from children classes to parent classes, and check "original_name" attribute
# first. This will ensure get the correct original attribute in any cases, e.g.,
# the case some classes in the hierarchy haven't been patched, but some others are
# patched, this case the previous code is risky to get wrong original attribute.
for obj_ in inspect.getmro(obj):
if original_name in obj_.__dict__:
return _get_attr(obj_, original_name)
elif name in obj_.__dict__:
if curr_active_patch in obj_.__dict__:
patch = getattr(obj, curr_active_patch)
if patch.is_inplace_patch:
raise RuntimeError(no_original_stored_err % (f"{obj_.__name__}.{name}",))
else:
# non inplace patch, we can get original methods in parent classes.
# so go on checking parent classes
continue
return _get_attr(obj_, name)
else:
# go on checking parent classes
continue
raise AttributeError(f"'{type(obj)}' object has no attribute '{name}'")
else:
try:
return _get_attr(obj, original_name)
except AttributeError:
if curr_active_patch in obj.__dict__:
raise RuntimeError(no_original_stored_err % (f"{type(obj).__name__}.{name}",))
return _get_attr(obj, name)
def get_decorator_data(obj, set_default=False):
"""Retrieve any decorator data from an object.
Parameters
----------
obj : object
Object.
set_default : bool
If no data is found, a default one is set on the object and returned,
otherwise ``None`` is returned.
Returns
-------
gorilla.DecoratorData
The decorator data or ``None``.
"""
if inspect.isclass(obj):
datas = getattr(obj, _DECORATOR_DATA, {})
data = datas.setdefault(obj, None)
if data is None and set_default:
data = DecoratorData()
datas[obj] = data
setattr(obj, _DECORATOR_DATA, datas)
else:
data = getattr(obj, _DECORATOR_DATA, None)
if data is None and set_default:
data = DecoratorData()
setattr(obj, _DECORATOR_DATA, data)
return data
def _get_base(obj):
"""Unwrap decorators to retrieve the base object.
Parameters
----------
obj : object
Object.
Returns
-------
object
The base object found or the input object otherwise.
"""
if hasattr(obj, "__func__"):
obj = obj.__func__
elif isinstance(obj, property):
obj = obj.fget
elif isinstance(obj, (classmethod, staticmethod)):
# Fallback for Python < 2.7 back when no `__func__` attribute
# was defined for those descriptors.
obj = obj.__get__(None, object)
else:
return obj
return _get_base(obj)
def _get_members(obj, traverse_bases=True, filter=default_filter, recursive=True):
"""Retrieve the member attributes of a module or a class.
The descriptor protocol is bypassed.
Parameters
----------
obj : module or class
Object.
traverse_bases : bool
If the object is a class, the base classes are also traversed.
filter : function
Attributes for which the function returns ``False`` are skipped. The
function needs to define two parameters: ``name``, the attribute name,
and ``obj``, the attribute value. If ``None``, no attribute is skipped.
recursive : bool
``True`` to search recursively through subclasses.
Returns
------
list of (name, value)
A list of tuples each containing the name and the value of the
attribute.
"""
if filter is None:
filter = _true
out = []
stack = collections.deque((obj,))
while stack:
obj = stack.popleft()
if traverse_bases and inspect.isclass(obj):
roots = [base for base in inspect.getmro(obj) if base not in (type, object)]
else:
roots = [obj]
members = []
seen = set()
for root in roots:
for name, value in _iteritems(getattr(root, "__dict__", {})):
if name not in seen and filter(name, value):
members.append((name, value))
seen.add(name)
members = sorted(members)
for _, value in members:
if recursive and inspect.isclass(value):
stack.append(value)
out.extend(members)
return out
def _module_iterator(root, recursive=True):
"""Iterate over modules.
Parameters
----------
root : module
Root module or package to iterate from.
recursive : bool
``True`` to iterate within subpackages.
Yields
------
module
The modules found.
"""
yield root
stack = collections.deque((root,))
while stack:
package = stack.popleft()
# The '__path__' attribute of a package might return a list of paths if
# the package is referenced as a namespace.
paths = getattr(package, "__path__", [])
for path in paths:
modules = pkgutil.iter_modules([path])
for finder, name, is_package in modules:
module_name = f"{package.__name__}.{name}"
module = sys.modules.get(module_name, None)
if module is None:
# Import the module through the finder to support package
# namespaces.
module = _load_module(finder, module_name)
if is_package:
if recursive:
stack.append(module)
yield module
else:
yield module
def _true(*args, **kwargs):
"""Return ``True``."""
return True
| Patch |
python | ray-project__ray | rllib/evaluation/env_runner_v2.py | {
"start": 4634,
"end": 7313
} | class ____(defaultdict):
def __missing__(self, env_id):
ret = self[env_id] = self.default_factory(env_id)
return ret
@OldAPIStack
def _build_multi_agent_batch(
episode_id: int,
batch_builder: _PolicyCollectorGroup,
large_batch_threshold: int,
multiple_episodes_in_batch: bool,
) -> MultiAgentBatch:
"""Build MultiAgentBatch from a dict of _PolicyCollectors.
Args:
env_steps: total env steps.
policy_collectors: collected training SampleBatchs by policy.
Returns:
Always returns a sample batch in MultiAgentBatch format.
"""
ma_batch = {}
for pid, collector in batch_builder.policy_collectors.items():
if collector.agent_steps <= 0:
continue
if batch_builder.agent_steps > large_batch_threshold and log_once(
"large_batch_warning"
):
logger.warning(
"More than {} observations in {} env steps for "
"episode {} ".format(
batch_builder.agent_steps, batch_builder.env_steps, episode_id
)
+ "are buffered in the sampler. If this is more than you "
"expected, check that that you set a horizon on your "
"environment correctly and that it terminates at some "
"point. Note: In multi-agent environments, "
"`rollout_fragment_length` sets the batch size based on "
"(across-agents) environment steps, not the steps of "
"individual agents, which can result in unexpectedly "
"large batches."
+ (
"Also, you may be waiting for your Env to "
"terminate (batch_mode=`complete_episodes`). Make sure "
"it does at some point."
if not multiple_episodes_in_batch
else ""
)
)
batch = collector.build()
ma_batch[pid] = batch
# Create the multi agent batch.
return MultiAgentBatch(policy_batches=ma_batch, env_steps=batch_builder.env_steps)
@OldAPIStack
def _batch_inference_sample_batches(eval_data: List[SampleBatch]) -> SampleBatch:
"""Batch a list of input SampleBatches into a single SampleBatch.
Args:
eval_data: list of SampleBatches.
Returns:
single batched SampleBatch.
"""
inference_batch = concat_samples(eval_data)
if "state_in_0" in inference_batch:
batch_size = len(eval_data)
inference_batch[SampleBatch.SEQ_LENS] = np.ones(batch_size, dtype=np.int32)
return inference_batch
@OldAPIStack
| _NewDefaultDict |
python | kamyu104__LeetCode-Solutions | Python/find-all-duplicates-in-an-array.py | {
"start": 974,
"end": 1193
} | class ____(object):
def findDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return [elem for elem, count in Counter(nums).items() if count == 2]
| Solution3 |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_button06.py | {
"start": 315,
"end": 852
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("button05.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.insert_button("C2", {"macro": "my_macro", "width": 128, "height": 30})
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | django__django | django/contrib/gis/geos/error.py | {
"start": 0,
"end": 105
} | class ____(Exception):
"The base GEOS exception, indicates a GEOS-related error."
pass
| GEOSException |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_excel2003_style01.py | {
"start": 315,
"end": 785
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("excel2003_style01.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename, {"excel2003_style": True})
workbook.add_worksheet()
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | django__django | tests/generic_views/test_dates.py | {
"start": 531,
"end": 1479
} | class ____:
@classmethod
def setUpTestData(cls):
cls.artist1 = Artist.objects.create(name="Rene Magritte")
cls.author1 = Author.objects.create(
name="Roberto Bolaño", slug="roberto-bolano"
)
cls.author2 = Author.objects.create(
name="Scott Rosenberg", slug="scott-rosenberg"
)
cls.book1 = Book.objects.create(
name="2066", slug="2066", pages=800, pubdate=datetime.date(2008, 10, 1)
)
cls.book1.authors.add(cls.author1)
cls.book2 = Book.objects.create(
name="Dreaming in Code",
slug="dreaming-in-code",
pages=300,
pubdate=datetime.date(2006, 5, 1),
)
cls.page1 = Page.objects.create(
content="I was once bitten by a moose.",
template="generic_views/page_template.html",
)
@override_settings(ROOT_URLCONF="generic_views.urls")
| TestDataMixin |
python | astropy__astropy | astropy/units/tests/test_logarithmic.py | {
"start": 36704,
"end": 36981
} | class ____:
# TODO: add tests for all supported functions!
@log_quantity_parametrization
def test_ptp(self, mag):
res = np.ptp(mag)
assert np.all(res.value == np.ptp(mag._function_view).value)
assert res.unit == u.mag()
| TestLogQuantityFunctions |
python | kamyu104__LeetCode-Solutions | Python/maximum-elegance-of-a-k-length-subsequence.py | {
"start": 3321,
"end": 4106
} | class ____(object):
def findMaximumElegance(self, items, k):
"""
:type items: List[List[int]]
:type k: int
:rtype: int
"""
items.sort(reverse=True)
result = curr = 0
lookup = set()
stk = []
for i in xrange(k):
if items[i][1] in lookup:
stk.append(items[i][0])
curr += items[i][0]
lookup.add(items[i][1])
result = curr+len(lookup)**2
for i in xrange(k, len(items)):
if items[i][1] in lookup:
continue
if not stk:
break
curr += items[i][0]-stk.pop()
lookup.add(items[i][1])
result = max(result, curr+len(lookup)**2)
return result
| Solution3 |
python | gevent__gevent | src/greentest/3.14/test_urllib2_localnet.py | {
"start": 15430,
"end": 24739
} | class ____(unittest.TestCase):
"""Tests urllib.request.urlopen using the network.
These tests are not exhaustive. Assuming that testing using files does a
good job overall of some of the basic interface features. There are no
tests exercising the optional 'data' and 'proxies' arguments. No tests
for transparent redirection have been written.
"""
def setUp(self):
super(TestUrlopen, self).setUp()
# clear _opener global variable
self.addCleanup(urllib.request.urlcleanup)
# Ignore proxies for localhost tests.
def restore_environ(old_environ):
os.environ.clear()
os.environ.update(old_environ)
self.addCleanup(restore_environ, os.environ.copy())
os.environ['NO_PROXY'] = '*'
os.environ['no_proxy'] = '*'
def urlopen(self, url, data=None, **kwargs):
l = []
f = urllib.request.urlopen(url, data, **kwargs)
try:
# Exercise various methods
l.extend(f.readlines(200))
l.append(f.readline())
l.append(f.read(1024))
l.append(f.read())
finally:
f.close()
return b"".join(l)
def stop_server(self):
self.server.stop()
self.server = None
def start_server(self, responses=None):
if responses is None:
responses = [(200, [], b"we don't care")]
handler = GetRequestHandler(responses)
self.server = LoopbackHttpServerThread(handler)
self.addCleanup(self.stop_server)
self.server.start()
self.server.ready.wait()
port = self.server.port
handler.port = port
return handler
def start_https_server(self, responses=None, **kwargs):
if not hasattr(urllib.request, 'HTTPSHandler'):
self.skipTest('ssl support required')
from test.ssl_servers import make_https_server
if responses is None:
responses = [(200, [], b"we care a bit")]
handler = GetRequestHandler(responses)
server = make_https_server(self, handler_class=handler, **kwargs)
handler.port = server.port
return handler
def test_redirection(self):
expected_response = b"We got here..."
responses = [
(302, [("Location", "http://localhost:%(port)s/somewhere_else")],
""),
(200, [], expected_response)
]
handler = self.start_server(responses)
data = self.urlopen("http://localhost:%s/" % handler.port)
self.assertEqual(data, expected_response)
self.assertEqual(handler.requests, ["/", "/somewhere_else"])
def test_chunked(self):
expected_response = b"hello world"
chunked_start = (
b'a\r\n'
b'hello worl\r\n'
b'1\r\n'
b'd\r\n'
b'0\r\n'
)
response = [(200, [("Transfer-Encoding", "chunked")], chunked_start)]
handler = self.start_server(response)
data = self.urlopen("http://localhost:%s/" % handler.port)
self.assertEqual(data, expected_response)
def test_404(self):
expected_response = b"Bad bad bad..."
handler = self.start_server([(404, [], expected_response)])
try:
self.urlopen("http://localhost:%s/weeble" % handler.port)
except urllib.error.URLError as f:
data = f.read()
f.close()
else:
self.fail("404 should raise URLError")
self.assertEqual(data, expected_response)
self.assertEqual(handler.requests, ["/weeble"])
def test_200(self):
expected_response = b"pycon 2008..."
handler = self.start_server([(200, [], expected_response)])
data = self.urlopen("http://localhost:%s/bizarre" % handler.port)
self.assertEqual(data, expected_response)
self.assertEqual(handler.requests, ["/bizarre"])
def test_200_with_parameters(self):
expected_response = b"pycon 2008..."
handler = self.start_server([(200, [], expected_response)])
data = self.urlopen("http://localhost:%s/bizarre" % handler.port,
b"get=with_feeling")
self.assertEqual(data, expected_response)
self.assertEqual(handler.requests, ["/bizarre", b"get=with_feeling"])
def test_https(self):
handler = self.start_https_server()
context = ssl.create_default_context(cafile=CERT_localhost)
data = self.urlopen("https://localhost:%s/bizarre" % handler.port, context=context)
self.assertEqual(data, b"we care a bit")
def test_https_sni(self):
if ssl is None:
self.skipTest("ssl module required")
if not ssl.HAS_SNI:
self.skipTest("SNI support required in OpenSSL")
sni_name = None
def cb_sni(ssl_sock, server_name, initial_context):
nonlocal sni_name
sni_name = server_name
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.set_servername_callback(cb_sni)
handler = self.start_https_server(context=context, certfile=CERT_localhost)
context = ssl.create_default_context(cafile=CERT_localhost)
self.urlopen("https://localhost:%s" % handler.port, context=context)
self.assertEqual(sni_name, "localhost")
def test_sending_headers(self):
handler = self.start_server()
req = urllib.request.Request("http://localhost:%s/" % handler.port,
headers={"Range": "bytes=20-39"})
with urllib.request.urlopen(req):
pass
self.assertEqual(handler.headers_received["Range"], "bytes=20-39")
def test_sending_headers_camel(self):
handler = self.start_server()
req = urllib.request.Request("http://localhost:%s/" % handler.port,
headers={"X-SoMe-hEader": "foobar"})
with urllib.request.urlopen(req):
pass
self.assertIn("X-Some-Header", handler.headers_received.keys())
self.assertNotIn("X-SoMe-hEader", handler.headers_received.keys())
def test_basic(self):
handler = self.start_server()
with urllib.request.urlopen("http://localhost:%s" % handler.port) as open_url:
for attr in ("read", "close", "info", "geturl"):
self.assertHasAttr(open_url, attr)
self.assertTrue(open_url.read(), "calling 'read' failed")
def test_info(self):
handler = self.start_server()
open_url = urllib.request.urlopen(
"http://localhost:%s" % handler.port)
with open_url:
info_obj = open_url.info()
self.assertIsInstance(info_obj, email.message.Message,
"object returned by 'info' is not an "
"instance of email.message.Message")
self.assertEqual(info_obj.get_content_subtype(), "plain")
def test_geturl(self):
# Make sure same URL as opened is returned by geturl.
handler = self.start_server()
open_url = urllib.request.urlopen("http://localhost:%s" % handler.port)
with open_url:
url = open_url.geturl()
self.assertEqual(url, "http://localhost:%s" % handler.port)
def test_iteration(self):
expected_response = b"pycon 2008..."
handler = self.start_server([(200, [], expected_response)])
data = urllib.request.urlopen("http://localhost:%s" % handler.port)
for line in data:
self.assertEqual(line, expected_response)
def test_line_iteration(self):
lines = [b"We\n", b"got\n", b"here\n", b"verylong " * 8192 + b"\n"]
expected_response = b"".join(lines)
handler = self.start_server([(200, [], expected_response)])
data = urllib.request.urlopen("http://localhost:%s" % handler.port)
for index, line in enumerate(data):
self.assertEqual(line, lines[index],
"Fetched line number %s doesn't match expected:\n"
" Expected length was %s, got %s" %
(index, len(lines[index]), len(line)))
self.assertEqual(index + 1, len(lines))
def test_issue16464(self):
# See https://bugs.python.org/issue16464
# and https://bugs.python.org/issue46648
handler = self.start_server([
(200, [], b'any'),
(200, [], b'any'),
])
opener = urllib.request.build_opener()
request = urllib.request.Request("http://localhost:%s" % handler.port)
self.assertEqual(None, request.data)
opener.open(request, "1".encode("us-ascii"))
self.assertEqual(b"1", request.data)
self.assertEqual("1", request.get_header("Content-length"))
opener.open(request, "1234567890".encode("us-ascii"))
self.assertEqual(b"1234567890", request.data)
self.assertEqual("10", request.get_header("Content-length"))
def setUpModule():
thread_info = threading_helper.threading_setup()
unittest.addModuleCleanup(threading_helper.threading_cleanup, *thread_info)
if __name__ == "__main__":
unittest.main()
| TestUrlopen |
python | django__django | tests/migrations/migrations_test_apps/mutate_state_b/migrations/0002_add_field.py | {
"start": 43,
"end": 451
} | class ____(migrations.Migration):
dependencies = [
("mutate_state_b", "0001_initial"),
]
operations = [
migrations.SeparateDatabaseAndState(
[],
[
migrations.AddField(
model_name="B",
name="added",
field=models.TextField(),
),
],
)
]
| Migration |
python | doocs__leetcode | solution/1900-1999/1910.Remove All Occurrences of a Substring/Solution.py | {
"start": 0,
"end": 156
} | class ____:
def removeOccurrences(self, s: str, part: str) -> str:
while part in s:
s = s.replace(part, '', 1)
return s
| Solution |
python | pytorch__pytorch | benchmarks/operator_benchmark/pt/qembedding_bag_lookups_test.py | {
"start": 2127,
"end": 5942
} | class ____(op_bench.TorchBenchmarkBase):
def init(
self,
num_embeddings: int,
embedding_dim: int,
num_offsets: int,
enable_per_sample_weights: bool,
include_last_offset: bool,
is_pruned_weights: bool,
use_32bit_indices: bool,
use_32bit_offsets: bool,
op_func,
):
self.num_embeddings = num_embeddings
self.embedding_dim = embedding_dim
self.num_offsets = num_offsets
self.enable_per_sample_weights = enable_per_sample_weights
self.include_last_offset = include_last_offset
self.max_segment_length = 20
self.num_lengths = np.random.randint(1, num_offsets + 1)
self.lengths = np.random.randint(
0, self.max_segment_length + 1, size=self.num_lengths
).astype(np.int32)
self.num_indices = np.sum(self.lengths)
self.is_pruned_weights = is_pruned_weights
self.use_32bit_indices = use_32bit_indices
self.use_32bit_offsets = use_32bit_offsets
self.offsets = lengths_to_offsets(self.lengths)
self.indices = torch.from_numpy(
np.random.randint(
low=0, high=num_embeddings, size=self.num_indices, dtype=np.int64
)
)
self.indices = self.indices.int() if self.use_32bit_indices else self.indices
self.offsets = self.offsets.int() if self.use_32bit_offsets else self.offsets
if self.include_last_offset:
self.offsets = torch.cat(
(self.offsets, torch.tensor([self.indices.size(0)], dtype=torch.long)),
0,
)
self.weights = torch.from_numpy(
(
np.random.random_sample((self.num_embeddings, self.embedding_dim)) + 1
).astype(np.float32)
)
self.indices = torch.from_numpy(
np.random.randint(
low=0, high=self.num_embeddings, size=self.num_indices, dtype=np.int64
)
)
self.prepack_func = torch.ops.quantized.embedding_bag_4bit_prepack
self.prepacked_weights = self.prepack_func(self.weights)
self.per_sample_weights = (
torch.from_numpy(
np.random.uniform(low=0.01, high=0.5, size=[len(self.indices)]).astype(
np.float32
)
)
if self.enable_per_sample_weights
else None
)
self.compressed_indices = None
if self.is_pruned_weights:
(
self.prepacked_weights,
self.compressed_indices,
) = get_pruned_weights_and_mapping(self.prepacked_weights)
self.inputs = {
"prepacked_weights": self.prepacked_weights,
"indices": self.indices,
"offsets": self.offsets,
"mode": 0,
"per_sample_weights": self.per_sample_weights,
"include_last_offset": self.include_last_offset,
"is_pruned_weights": self.is_pruned_weights,
"compressed_indices": self.compressed_indices,
}
self.op_func = op_func
def forward(
self,
prepacked_weights,
indices,
offsets,
mode: int,
per_sample_weights: Optional[torch.Tensor],
include_last_offset: bool,
is_pruned_weights: bool,
compressed_indices: Optional[torch.Tensor],
):
return self.op_func(
prepacked_weights,
indices,
offsets,
mode=mode,
per_sample_weights=per_sample_weights,
include_last_offset=include_last_offset,
pruned_weights=is_pruned_weights,
compressed_indices_mapping=compressed_indices,
)
| EmbedddingBag4BitRowwiseOffsetsTest |
python | scipy__scipy | scipy/io/arff/tests/test_arffread.py | {
"start": 1499,
"end": 2866
} | class ____:
def test1(self):
# Parsing trivial file with nothing.
self._test(test4)
def test2(self):
# Parsing trivial file with some comments in the data section.
self._test(test5)
def test3(self):
# Parsing trivial file with nominal attribute of 1 character.
self._test(test6)
def test4(self):
# Parsing trivial file with trailing spaces in attribute declaration.
self._test(test11)
def _test(self, test_file):
data, meta = loadarff(test_file)
for i in range(len(data)):
for j in range(4):
assert_array_almost_equal(expect4_data[i][j], data[i][j])
assert_equal(meta.types(), expected_types)
def test_filelike(self):
# Test reading from file-like object (StringIO)
with open(test1) as f1:
data1, meta1 = loadarff(f1)
with open(test1) as f2:
data2, meta2 = loadarff(StringIO(f2.read()))
assert_(data1 == data2)
assert_(repr(meta1) == repr(meta2))
def test_path(self):
# Test reading from `pathlib.Path` object
from pathlib import Path
with open(test1) as f1:
data1, meta1 = loadarff(f1)
data2, meta2 = loadarff(Path(test1))
assert_(data1 == data2)
assert_(repr(meta1) == repr(meta2))
| TestData |
python | pydantic__pydantic | pydantic-core/tests/validators/test_int.py | {
"start": 18164,
"end": 19265
} | class ____(int):
pass
def test_int_subclass() -> None:
v = SchemaValidator(cs.int_schema())
v_lax = v.validate_python(IntSubclass(1))
assert v_lax == 1
assert type(v_lax) == int
v_strict = v.validate_python(IntSubclass(1), strict=True)
assert v_strict == 1
assert type(v_strict) == int
assert v.validate_python(IntSubclass(1136885225876639845)) == 1136885225876639845
assert v.validate_python(IntSubclass(i64_max + 7)) == i64_max + 7
assert v.validate_python(IntSubclass(1136885225876639845), strict=True) == 1136885225876639845
assert v.validate_python(IntSubclass(i64_max + 7), strict=True) == i64_max + 7
def test_int_subclass_constraint() -> None:
v = SchemaValidator(cs.int_schema(gt=0))
v_lax = v.validate_python(IntSubclass(1))
assert v_lax == 1
assert type(v_lax) == int
v_strict = v.validate_python(IntSubclass(1), strict=True)
assert v_strict == 1
assert type(v_strict) == int
with pytest.raises(ValidationError, match='Input should be greater than 0'):
v.validate_python(IntSubclass(0))
| IntSubclass |
python | Netflix__metaflow | metaflow/plugins/events_decorator.py | {
"start": 11145,
"end": 22704
} | class ____(FlowDecorator):
"""
Specifies the flow(s) that this flow depends on.
```
@trigger_on_finish(flow='FooFlow')
```
or
```
@trigger_on_finish(flows=['FooFlow', 'BarFlow'])
```
This decorator respects the @project decorator and triggers the flow
when upstream runs within the same namespace complete successfully
Additionally, you can specify project aware upstream flow dependencies
by specifying the fully qualified project_flow_name.
```
@trigger_on_finish(flow='my_project.branch.my_branch.FooFlow')
```
or
```
@trigger_on_finish(flows=['my_project.branch.my_branch.FooFlow', 'BarFlow'])
```
You can also specify just the project or project branch (other values will be
inferred from the current project or project branch):
```
@trigger_on_finish(flow={"name": "FooFlow", "project": "my_project", "project_branch": "branch"})
```
Note that `branch` is typically one of:
- `prod`
- `user.bob`
- `test.my_experiment`
- `prod.staging`
Parameters
----------
flow : Union[str, Dict[str, str]], optional, default None
Upstream flow dependency for this flow.
flows : List[Union[str, Dict[str, str]]], default []
Upstream flow dependencies for this flow.
options : Dict[str, Any], default {}
Backend-specific configuration for tuning eventing behavior.
MF Add To Current
-----------------
trigger -> metaflow.events.Trigger
Returns `Trigger` if the current run is triggered by an event
@@ Returns
-------
Trigger
`Trigger` if triggered by an event
"""
name = "trigger_on_finish"
options = {
"trigger": dict(
multiple=True,
default=None,
help="Specify run pathspec for testing @trigger_on_finish locally.",
),
}
defaults = {
"flow": None, # flow_name or project_flow_name
"flows": [], # flow_names or project_flow_names
"options": {},
# Re-enable if you want to support TL options directly in the decorator like
# for @project decorator
# **{k: v["default"] for k, v in options.items()},
}
def flow_init(
self,
flow_name,
graph,
environment,
flow_datastore,
metadata,
logger,
echo,
options,
):
self.triggers = []
if sum(map(bool, (self.attributes["flow"], self.attributes["flows"]))) > 1:
raise MetaflowException(
"Specify only one of *flow* or *flows* "
"attributes in *@trigger_on_finish* decorator."
)
elif self.attributes["flow"]:
# flow supports the format @trigger_on_finish(flow='FooFlow')
flow = self.attributes["flow"]
if callable(flow) and not isinstance(
self.attributes["flow"], DeployTimeField
):
trig = DeployTimeField(
"fq_name",
[str, dict],
None,
flow,
False,
print_representation=str(flow),
)
self.triggers.append(trig)
else:
self.triggers.extend(self._parse_static_triggers([flow]))
elif self.attributes["flows"]:
# flows attribute supports the following formats -
# 1. flows=['FooFlow', 'BarFlow']
flows = self.attributes["flows"]
if callable(flows) and not isinstance(flows, DeployTimeField):
trig = DeployTimeField(
"flows", list, None, flows, False, print_representation=str(flows)
)
self.triggers.append(trig)
elif isinstance(flows, list):
self.triggers.extend(self._parse_static_triggers(flows))
else:
raise MetaflowException(
"Incorrect type for *flows* attribute in *@trigger_on_finish* "
"decorator. Supported type is list - \n"
"@trigger_on_finish(flows=['FooFlow', 'BarFlow']"
)
if not self.triggers:
raise MetaflowException(
"No flow(s) specified in *@trigger_on_finish* decorator."
)
# Make triggers @project aware
for trigger in self.triggers:
if isinstance(trigger, DeployTimeField):
continue
self._parse_fq_name(trigger)
self.options = self.attributes["options"]
# Handle scenario for local testing using --trigger.
# Re-enable this code if you want to support passing trigger directly in the
# decorator in a way similar to how production and branch are passed in the
# project decorator.
# # This is overkill since default is None for all options but adding this code
# # to make it safe if other non None-default options are added in the future.
# for op in options:
# if (
# op in self._user_defined_attributes
# and options[op] != self.defaults[op]
# and self.attributes[op] != options[op]
# ):
# # Exception if:
# # - the user provides a value in the attributes field
# # - AND the user provided a value in the command line (non default)
# # - AND the values are different
# # Note that this won't raise an error if the user provided the default
# # value in the command line and provided one in attribute but although
# # slightly inconsistent, it is not incorrect.
# raise MetaflowException(
# "You cannot pass %s as both a command-line argument and an attribute "
# "of the @trigger_on_finish decorator." % op
# )
# if "trigger" in self._user_defined_attributes:
# trigger_option = self.attributes["trigger"]
# else:
trigger_option = options["trigger"]
self._option_values = options
if trigger_option:
from metaflow import Run
from metaflow.events import Trigger
run_objs = []
for run_pathspec in trigger_option:
if len(run_pathspec.split("/")) != 2:
raise MetaflowException(
"Incorrect format for run pathspec for *--trigger*. "
"Supported format is flow_name/run_id."
)
run_obj = Run(run_pathspec, _namespace_check=False)
if not run_obj.successful:
raise MetaflowException(
"*--trigger* does not support runs that are not successful yet."
)
run_objs.append(run_obj)
current._update_env({"trigger": Trigger.from_runs(run_objs)})
@staticmethod
def _parse_static_triggers(flows):
results = []
for flow in flows:
if is_stringish(flow):
results.append(
{
"fq_name": flow,
}
)
elif isinstance(flow, dict):
if "name" not in flow:
if len(flows) > 1:
raise MetaflowException(
"One or more flows in the *flows* attribute for "
"*@trigger_on_finish* is missing the "
"*name* key."
)
raise MetaflowException(
"The *flow* attribute for *@trigger_on_finish* is missing the "
"*name* key."
)
flow_name = flow["name"]
if not is_stringish(flow_name) or "." in flow_name:
raise MetaflowException(
f"The *name* attribute of the *flow* {flow_name} is not a valid string"
)
result = {"fq_name": flow_name}
if "project" in flow:
if is_stringish(flow["project"]):
result["project"] = flow["project"]
else:
raise MetaflowException(
f"The *project* attribute of the *flow* {flow_name} is not a string"
)
if "project_branch" in flow:
if is_stringish(flow["project_branch"]):
result["branch"] = flow["project_branch"]
else:
raise MetaflowException(
f"The *project_branch* attribute of the *flow* {flow_name} is not a string"
)
results.append(result)
else:
if len(flows) > 1:
raise MetaflowException(
"One or more flows in the *flows* attribute for "
"*@trigger_on_finish* decorator have an incorrect type. "
"Supported type is string or Dict[str, str]- \n"
"@trigger_on_finish(flows=['FooFlow', 'BarFlow']"
)
raise MetaflowException(
"Incorrect type for *flow* attribute in *@trigger_on_finish* "
" decorator. Supported type is string or Dict[str, str] - \n"
"@trigger_on_finish(flow='FooFlow') or "
"@trigger_on_finish(flow={'name':'FooFlow', 'project_branch': 'branch'})"
)
return results
def _parse_fq_name(self, trigger):
if trigger["fq_name"].count(".") == 0:
# fully qualified name is just the flow name
trigger["flow"] = trigger["fq_name"]
elif trigger["fq_name"].count(".") >= 2:
# fully qualified name is of the format - project.branch.flow_name
trigger["project"], tail = trigger["fq_name"].split(".", maxsplit=1)
trigger["branch"], trigger["flow"] = tail.rsplit(".", maxsplit=1)
else:
raise MetaflowException(
"Incorrect format for *flow* in *@trigger_on_finish* "
"decorator. Specify either just the *flow_name* or a fully "
"qualified name like *project_name.branch_name.flow_name*."
)
if not re.match(r"^[A-Za-z0-9_]+$", trigger["flow"]):
raise MetaflowException(
"Invalid flow name *%s* in *@trigger_on_finish* "
"decorator. Only alphanumeric characters and "
"underscores(_) are allowed." % trigger["flow"]
)
def format_deploytime_value(self):
if len(self.triggers) == 1 and isinstance(self.triggers[0], DeployTimeField):
deploy_value = deploy_time_eval(self.triggers[0])
if isinstance(deploy_value, list):
self.triggers = deploy_value
else:
self.triggers = [deploy_value]
triggers = self._parse_static_triggers(self.triggers)
for trigger in triggers:
self._parse_fq_name(trigger)
self.triggers = triggers
def get_top_level_options(self):
return list(self._option_values.items())
| TriggerOnFinishDecorator |
python | scipy__scipy | scipy/stats/_continuous_distns.py | {
"start": 67424,
"end": 69364
} | class ____(rv_continuous):
r"""An exponentiated Weibull continuous random variable.
%(before_notes)s
See Also
--------
weibull_min, numpy.random.Generator.weibull
Notes
-----
The probability density function for `exponweib` is:
.. math::
f(x, a, c) = a c [1-\exp(-x^c)]^{a-1} \exp(-x^c) x^{c-1}
and its cumulative distribution function is:
.. math::
F(x, a, c) = [1-\exp(-x^c)]^a
for :math:`x > 0`, :math:`a > 0`, :math:`c > 0`.
`exponweib` takes :math:`a` and :math:`c` as shape parameters:
* :math:`a` is the exponentiation parameter,
with the special case :math:`a=1` corresponding to the
(non-exponentiated) Weibull distribution `weibull_min`.
* :math:`c` is the shape parameter of the non-exponentiated Weibull law.
%(after_notes)s
References
----------
https://en.wikipedia.org/wiki/Exponentiated_Weibull_distribution
%(example)s
"""
def _shape_info(self):
ia = _ShapeInfo("a", False, (0, np.inf), (False, False))
ic = _ShapeInfo("c", False, (0, np.inf), (False, False))
return [ia, ic]
def _pdf(self, x, a, c):
# exponweib.pdf(x, a, c) =
# a * c * (1-exp(-x**c))**(a-1) * exp(-x**c)*x**(c-1)
return np.exp(self._logpdf(x, a, c))
def _logpdf(self, x, a, c):
negxc = -x**c
exm1c = -sc.expm1(negxc)
logp = (np.log(a) + np.log(c) + sc.xlogy(a - 1.0, exm1c) +
negxc + sc.xlogy(c - 1.0, x))
return logp
def _cdf(self, x, a, c):
exm1c = -sc.expm1(-x**c)
return exm1c**a
def _ppf(self, q, a, c):
return (-sc.log1p(-q**(1.0/a)))**np.asarray(1.0/c)
def _sf(self, x, a, c):
return -_pow1pm1(-np.exp(-x**c), a)
def _isf(self, p, a, c):
return (-np.log(-_pow1pm1(-p, 1/a)))**(1/c)
exponweib = exponweib_gen(a=0.0, name='exponweib')
| exponweib_gen |
python | pandas-dev__pandas | asv_bench/benchmarks/index_object.py | {
"start": 3193,
"end": 4163
} | class ____:
def setup(self):
N = 10_000
self.range_idx = RangeIndex(0, 100)
self.int_idx = self.range_idx.astype(int)
self.obj_idx = self.int_idx.astype(str)
self.range_idxs = []
self.int_idxs = []
self.object_idxs = []
for i in range(1, N):
r_idx = RangeIndex(i * 100, (i + 1) * 100)
self.range_idxs.append(r_idx)
i_idx = r_idx.astype(int)
self.int_idxs.append(i_idx)
o_idx = i_idx.astype(str)
self.object_idxs.append(o_idx)
self.same_range_idx = [self.range_idx] * N
def time_append_range_list(self):
self.range_idx.append(self.range_idxs)
def time_append_range_list_same(self):
self.range_idx.append(self.same_range_idx)
def time_append_int_list(self):
self.int_idx.append(self.int_idxs)
def time_append_obj_list(self):
self.obj_idx.append(self.object_idxs)
| IndexAppend |
python | pytest-dev__pytest-xdist | testing/acceptance_test.py | {
"start": 45354,
"end": 51545
} | class ____:
def test_by_module(self, pytester: pytest.Pytester) -> None:
test_file = """
import pytest
class TestA:
@pytest.mark.xdist_group(name="xdist_group")
@pytest.mark.parametrize('i', range(5))
def test(self, i):
pass
"""
pytester.makepyfile(test_a=test_file, test_b=test_file)
result = pytester.runpytest("-n2", "--dist=loadgroup", "-v")
test_a_workers_and_test_count = get_workers_and_test_count_by_prefix(
"test_a.py::TestA", result.outlines
)
test_b_workers_and_test_count = get_workers_and_test_count_by_prefix(
"test_b.py::TestA", result.outlines
)
assert test_a_workers_and_test_count in (
{"gw0": 5},
{"gw1": 0},
) or test_a_workers_and_test_count in ({"gw0": 0}, {"gw1": 5})
assert test_b_workers_and_test_count in (
{"gw0": 5},
{"gw1": 0},
) or test_b_workers_and_test_count in ({"gw0": 0}, {"gw1": 5})
assert (
test_a_workers_and_test_count.items()
== test_b_workers_and_test_count.items()
)
def test_by_class(self, pytester: pytest.Pytester) -> None:
pytester.makepyfile(
test_a="""
import pytest
class TestA:
@pytest.mark.xdist_group(name="xdist_group")
@pytest.mark.parametrize('i', range(10))
def test(self, i):
pass
class TestB:
@pytest.mark.xdist_group(name="xdist_group")
@pytest.mark.parametrize('i', range(10))
def test(self, i):
pass
"""
)
result = pytester.runpytest("-n2", "--dist=loadgroup", "-v")
test_a_workers_and_test_count = get_workers_and_test_count_by_prefix(
"test_a.py::TestA", result.outlines
)
test_b_workers_and_test_count = get_workers_and_test_count_by_prefix(
"test_a.py::TestB", result.outlines
)
assert test_a_workers_and_test_count in (
{"gw0": 10},
{"gw1": 0},
) or test_a_workers_and_test_count in ({"gw0": 0}, {"gw1": 10})
assert test_b_workers_and_test_count in (
{"gw0": 10},
{"gw1": 0},
) or test_b_workers_and_test_count in ({"gw0": 0}, {"gw1": 10})
assert (
test_a_workers_and_test_count.items()
== test_b_workers_and_test_count.items()
)
def test_module_single_start(self, pytester: pytest.Pytester) -> None:
test_file1 = """
import pytest
@pytest.mark.xdist_group(name="xdist_group")
def test():
pass
"""
test_file2 = """
import pytest
def test_1():
pass
@pytest.mark.xdist_group(name="xdist_group")
def test_2():
pass
"""
pytester.makepyfile(test_a=test_file1, test_b=test_file1, test_c=test_file2)
result = pytester.runpytest("-n2", "--dist=loadgroup", "-v")
a = get_workers_and_test_count_by_prefix("test_a.py::test", result.outlines)
b = get_workers_and_test_count_by_prefix("test_b.py::test", result.outlines)
c = get_workers_and_test_count_by_prefix("test_c.py::test_2", result.outlines)
assert a.keys() == b.keys() and b.keys() == c.keys()
def test_with_two_group_names(self, pytester: pytest.Pytester) -> None:
test_file = """
import pytest
@pytest.mark.xdist_group(name="group1")
def test_1():
pass
@pytest.mark.xdist_group("group2")
def test_2():
pass
"""
pytester.makepyfile(test_a=test_file, test_b=test_file)
result = pytester.runpytest("-n2", "--dist=loadgroup", "-v")
a_1 = get_workers_and_test_count_by_prefix("test_a.py::test_1", result.outlines)
a_2 = get_workers_and_test_count_by_prefix("test_a.py::test_2", result.outlines)
b_1 = get_workers_and_test_count_by_prefix("test_b.py::test_1", result.outlines)
b_2 = get_workers_and_test_count_by_prefix("test_b.py::test_2", result.outlines)
assert a_1.keys() == b_1.keys() and a_2.keys() == b_2.keys()
def test_multiple_group_marks(self, pytester: pytest.Pytester) -> None:
test_file = """
import pytest
@pytest.mark.xdist_group(name="group1")
@pytest.mark.xdist_group(name="group2")
def test_1():
pass
"""
pytester.makepyfile(test_a=test_file, test_b=test_file)
result = pytester.runpytest("-n2", "--dist=loadgroup", "-v")
res = parse_tests_and_workers_from_output(result.outlines)
assert len(res) == 2
# get test names
a_1 = next(t[2] for t in res if "test_a.py::test_1" in t[2])
b_1 = next(t[2] for t in res if "test_b.py::test_1" in t[2])
# check groups
assert a_1.split("@")[1] == b_1.split("@")[1] == "group1_group2"
def test_multiple_group_order(self, pytester: pytest.Pytester) -> None:
test_file = """
import pytest
@pytest.mark.xdist_group(name="b")
@pytest.mark.xdist_group(name="d")
@pytest.mark.xdist_group(name="c")
@pytest.mark.xdist_group(name="c2")
@pytest.mark.xdist_group(name="a")
@pytest.mark.xdist_group(name="aa")
def test_1():
pass
"""
pytester.makepyfile(test_a=test_file, test_b=test_file)
result = pytester.runpytest("-n2", "--dist=loadgroup", "-v")
res = parse_tests_and_workers_from_output(result.outlines)
assert len(res) == 2
# get test names
a_1 = next(t[2] for t in res if "test_a.py::test_1" in t[2])
b_1 = next(t[2] for t in res if "test_b.py::test_1" in t[2])
# check groups, order should be sorted
assert a_1.split("@")[1] == b_1.split("@")[1] == "a_aa_b_c_c2_d"
| TestGroupScope |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/spec_cache.py | {
"start": 712,
"end": 2282
} | class ____:
docker_repository: str
docker_image_tag: str
spec_cache_path: str
registry: Registries
def __str__(self) -> str:
return self.spec_cache_path
def get_spec_file_name(registry: Registries) -> str:
return SPEC_FILE_NAMES[registry]
def get_registry_from_spec_cache_path(spec_cache_path: str) -> Registries:
"""Returns the registry from the spec cache path."""
for registry in Registries:
file_name = get_spec_file_name(registry)
if file_name in spec_cache_path:
return registry
raise Exception(f"Could not find any registry file name in spec cache path: {spec_cache_path}")
def get_docker_info_from_spec_cache_path(spec_cache_path: str) -> CachedSpec:
"""Returns the docker repository and tag from the spec cache path."""
registry = get_registry_from_spec_cache_path(spec_cache_path)
registry_file_name = get_spec_file_name(registry)
# remove the leading "specs/" from the path using CACHE_FOLDER
without_folder = spec_cache_path.replace(f"{CACHE_FOLDER}/", "")
without_file = without_folder.replace(f"/{registry_file_name}", "")
# split on only the last "/" to get the docker repository and tag
# this is because the docker repository can have "/" in it
docker_image_tag = without_file.split("/")[-1]
docker_repository = without_file.replace(f"/{docker_image_tag}", "")
return CachedSpec(
docker_repository=docker_repository, docker_image_tag=docker_image_tag, spec_cache_path=spec_cache_path, registry=registry
)
| CachedSpec |
python | pytorch__pytorch | torch/distributed/checkpoint/metadata.py | {
"start": 3785,
"end": 4427
} | class ____:
"""This class represents the metadata of the checkpoint."""
# Keys are the same from the `state_dict` used.
state_dict_metadata: dict[str, STORAGE_TYPES]
# It is the responsibility of the planner and storage plugins to ensure
# backward compatibility of the planner_data and storage_data. DCP will
# also ensure the backward compatibility of the metadata in this file and
# the metadata of the built-in planner and storage plugins.
planner_data: Any = None
storage_data: Any = None
storage_meta: Optional[StorageMeta] = None
version: Optional[str] = None
@dataclass(frozen=True)
| Metadata |
python | pytorch__pytorch | torch/fx/graph.py | {
"start": 42002,
"end": 43846
} | class ____(_PyTreeCodeGen):
def __init__(
self,
pytree_info: _PyTreeInfo,
in_shuffle_graph: "GraphModule",
out_shuffle_graph: "GraphModule",
tree_leaf_names: list[str],
root: Optional[torch.nn.Module],
):
super().__init__(pytree_info)
self.in_shuffle_graph = in_shuffle_graph
self.out_shuffle_graph = out_shuffle_graph
self.tree_leaf_names = tree_leaf_names
self.root = root
def process_inputs(self, *inputs: Any) -> Any:
flat_args = super().process_inputs(*inputs)
if self.root is not None:
flat_args = (self.root, *flat_args)
self.flat_args = flat_args
return self.in_shuffle_graph(*flat_args)
def process_outputs(self, out: Any) -> Any:
flat_outs = self.out_shuffle_graph(*self.flat_args, *out)
del self.flat_args
ret = super().process_outputs(flat_outs)
return ret
def gen_fn_def(self, *args, **kwargs) -> str:
fn_def = super().gen_fn_def(*args, **kwargs)
return fn_def
def gen_var_bindings(self, fn_args, free_vars, expanded_def) -> str:
without_annotation = [x.split(":")[0].split("#")[0] for x in free_vars]
fn_signature: str = f"{', '.join(fn_args)}"
if self.root is not None:
fn_signature = f"self, {fn_signature}"
return f"""
{", ".join(self.tree_leaf_names)}, = pytree.tree_leaves(({fn_signature},))
{", ".join(without_annotation)}, = self._in_shuffle_graph({", ".join(self.tree_leaf_names)})"""
def generate_output(self, output_args, *args, **kwargs) -> str:
output = f"self._out_shuffle_graph({', '.join(self.tree_leaf_names)}, {', '.join([str(a) for a in output_args])})"
return f"return pytree.tree_unflatten({output}, self._out_spec)"
| _ExportCodeGen |
python | kamyu104__LeetCode-Solutions | Python/card-flipping-game.py | {
"start": 48,
"end": 488
} | class ____(object):
def flipgame(self, fronts, backs):
"""
:type fronts: List[int]
:type backs: List[int]
:rtype: int
"""
same = {n for i, n in enumerate(fronts) if n == backs[i]}
result = float("inf")
for n in itertools.chain(fronts, backs):
if n not in same:
result = min(result, n)
return result if result < float("inf") else 0
| Solution |
python | networkx__networkx | networkx/classes/tests/test_graphviews.py | {
"start": 1471,
"end": 2790
} | class ____:
def setup_method(self):
self.G = nx.path_graph(9, create_using=nx.MultiDiGraph())
self.G.add_edge(4, 5)
self.rv = nx.reverse_view(self.G)
def test_pickle(self):
import pickle
rv = self.rv
prv = pickle.loads(pickle.dumps(rv, -1))
assert rv._node == prv._node
assert rv._adj == prv._adj
assert rv.graph == prv.graph
def test_contains(self):
assert (2, 3, 0) in self.G.edges
assert (3, 2, 0) not in self.G.edges
assert (2, 3, 0) not in self.rv.edges
assert (3, 2, 0) in self.rv.edges
assert (5, 4, 1) in self.rv.edges
assert (4, 5, 1) not in self.rv.edges
def test_iter(self):
expected = sorted((v, u, k) for u, v, k in self.G.edges)
assert sorted(self.rv.edges) == expected
def test_exceptions(self):
MG = nx.MultiGraph(self.G)
pytest.raises(nx.NetworkXNotImplemented, nx.reverse_view, MG)
def test_generic_multitype():
nxg = nx.graphviews
G = nx.DiGraph([(1, 2)])
with pytest.raises(nx.NetworkXError):
nxg.generic_graph_view(G, create_using=nx.MultiGraph)
G = nx.MultiDiGraph([(1, 2)])
with pytest.raises(nx.NetworkXError):
nxg.generic_graph_view(G, create_using=nx.DiGraph)
| TestMultiReverseView |
python | getsentry__sentry | tests/sentry/sentry_apps/services/test_hook_service.py | {
"start": 13712,
"end": 22149
} | class ____(TestCase):
def setUp(self) -> None:
self.user = self.create_user()
self.org = self.create_organization(owner=self.user, region="us")
self.project = self.create_project(name="foo", organization=self.org)
self.sentry_app = self.create_sentry_app(
organization_id=self.org.id, events=["issue.created"]
)
def test_bulk_create_service_hooks_for_app_success(self) -> None:
# Create some installations and organizations
installation1 = self.create_sentry_app_installation(
slug=self.sentry_app.slug, organization=self.org, user=self.user
)
org2 = self.create_organization(name="Test Org 2", region="us")
installation2 = self.create_sentry_app_installation(
slug=self.sentry_app.slug, organization=org2, user=self.user
)
# Delete existing hooks to test bulk creation
with assume_test_silo_mode(SiloMode.REGION):
ServiceHook.objects.filter(application_id=self.sentry_app.application.id).delete()
# Prepare installation-organization pairs
installation_org_pairs = [
RpcInstallationOrganizationPair(
installation_id=installation1.id, organization_id=self.org.id
),
RpcInstallationOrganizationPair(
installation_id=installation2.id, organization_id=org2.id
),
]
result = hook_service.bulk_create_service_hooks_for_app(
region_name="us",
application_id=self.sentry_app.application.id,
events=["issue.created", "error.created"],
installation_organization_ids=installation_org_pairs,
url="https://example.com/webhook",
)
# Verify hooks were created in database
with assume_test_silo_mode(SiloMode.REGION):
hooks = ServiceHook.objects.filter(
application_id=self.sentry_app.application.id
).order_by("id")
assert hooks.count() == 2
assert len(result) == 2
assert hooks[0].organization_id == result[0].organization_id
assert hooks[1].organization_id == result[1].organization_id
assert hooks[0].installation_id == result[0].installation_id
assert hooks[1].installation_id == result[1].installation_id
assert hooks[0].url == result[0].url
assert hooks[0].events == result[0].events
assert hooks[1].url == result[1].url
assert hooks[1].events == result[1].events
assert result[0].id == hooks[0].id
assert result[1].id == hooks[1].id
def test_bulk_create_service_hooks_for_app_with_event_expansion(self) -> None:
installation = self.create_sentry_app_installation(
slug=self.sentry_app.slug, organization=self.org, user=self.user
)
# Delete existing hook
with assume_test_silo_mode(SiloMode.REGION):
ServiceHook.objects.filter(application_id=self.sentry_app.application.id).delete()
# Call bulk create with expandable events
result = hook_service.bulk_create_service_hooks_for_app(
region_name="us",
application_id=self.sentry_app.application.id,
events=["issue", "comment"], # These should expand
installation_organization_ids=[
RpcInstallationOrganizationPair(
installation_id=installation.id, organization_id=self.org.id
)
],
url="https://example.com/webhook",
)
assert len(result) == 1
# Verify events were expanded
with assume_test_silo_mode(SiloMode.REGION):
hook = ServiceHook.objects.get(installation_id=installation.id)
expected_events = expand_events(["issue", "comment"])
assert hook.events == expected_events
def test_bulk_create_service_hooks_for_app_empty_list(self) -> None:
# Call with empty installation list
result = hook_service.bulk_create_service_hooks_for_app(
region_name="us",
application_id=self.sentry_app.application.id,
events=["issue.created"],
installation_organization_ids=[],
url="https://example.com/webhook",
)
# Should return empty list
assert result == []
# Verify no hooks were created
with assume_test_silo_mode(SiloMode.REGION):
hooks_count = ServiceHook.objects.filter(
application_id=self.sentry_app.application.id
).count()
# Should still have the hooks from setUp (if any)
assert hooks_count >= 0
def test_bulk_create_service_hooks_for_app_ignore_conflicts(self) -> None:
installation = self.create_sentry_app_installation(
slug=self.sentry_app.slug, organization=self.org, user=self.user
)
# Verify hook already exists from installation creation
with assume_test_silo_mode(SiloMode.REGION):
existing_hook = ServiceHook.objects.get(
installation_id=installation.id, application_id=self.sentry_app.application.id
)
initial_count = ServiceHook.objects.filter(
application_id=self.sentry_app.application.id
).count()
# Try to bulk create hook for same installation should not create duplicate
result = hook_service.bulk_create_service_hooks_for_app(
region_name="us",
application_id=self.sentry_app.application.id,
events=["error.created"],
installation_organization_ids=[
RpcInstallationOrganizationPair(
installation_id=installation.id, organization_id=self.org.id
)
],
url="https://different-url.com/webhook",
)
assert result == []
# Verify no duplicate hooks were created
with assume_test_silo_mode(SiloMode.REGION):
final_count = ServiceHook.objects.filter(
application_id=self.sentry_app.application.id
).count()
assert final_count == initial_count
# Original hook should be unchanged
existing_hook.refresh_from_db()
assert existing_hook.url != "https://different-url.com/webhook"
def test_bulk_create_service_hooks_for_app_large_batch(self) -> None:
# Test with many installation-org pairs
installation_org_pairs = []
orgs = []
# Create multiple organizations and installations
for i in range(5):
org = self.create_organization(name=f"Bulk Test Org {i}")
orgs.append(org)
installation = self.create_sentry_app_installation(
slug=self.sentry_app.slug, organization=org, user=self.user
)
installation_org_pairs.append(
RpcInstallationOrganizationPair(
installation_id=installation.id, organization_id=org.id
)
)
# Delete existing hooks to test clean bulk creation
with assume_test_silo_mode(SiloMode.REGION):
ServiceHook.objects.filter(
installation_id__in=[pair.installation_id for pair in installation_org_pairs]
).delete()
# Call bulk create
result = hook_service.bulk_create_service_hooks_for_app(
region_name="us",
application_id=self.sentry_app.application.id,
events=["issue.created"],
installation_organization_ids=installation_org_pairs,
url="https://bulk-test.com/webhook",
)
# Should create all hooks
assert len(result) == 5
# Verify all hooks were created correctly
with assume_test_silo_mode(SiloMode.REGION):
for pair in installation_org_pairs:
installation_id = pair.installation_id
org_id = pair.organization_id
hook = ServiceHook.objects.get(
installation_id=installation_id, application_id=self.sentry_app.application.id
)
assert hook.organization_id == org_id
assert hook.url == "https://bulk-test.com/webhook"
assert hook.events == ["issue.created"]
| TestHookServiceBulkCreate |
python | doocs__leetcode | solution/3000-3099/3021.Alice and Bob Playing Flower Game/Solution2.py | {
"start": 0,
"end": 93
} | class ____:
def flowerGame(self, n: int, m: int) -> int:
return (n * m) // 2
| Solution |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 171306,
"end": 173965
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[3, 3, 3]"):
l_x_ = L_x_
y: "f32[3]" = torch.randn(3)
_saved_tensors_hooks_disable = torch._C._autograd._saved_tensors_hooks_disable("torch.func.{grad, vjp, jacrev, hessian} don't yet support saved tensor hooks. Please open an issue with your use case."); _saved_tensors_hooks_disable = None
_grad_increment_nesting = torch._C._functorch._grad_increment_nesting(); _grad_increment_nesting = None
diff_args: "f32[3, 3, 3]" = torch._C._functorch._wrap_for_grad(l_x_, 1); l_x_ = None
set_inplace_requires_grad_allowed = torch._C._functorch.set_inplace_requires_grad_allowed(True); set_inplace_requires_grad_allowed = None
_set_tensor_requires_grad: "f32[3, 3, 3]" = torch._functorch.eager_transforms._set_tensor_requires_grad(diff_args); _set_tensor_requires_grad = None
set_inplace_requires_grad_allowed_1 = torch._C._functorch.set_inplace_requires_grad_allowed(False); set_inplace_requires_grad_allowed_1 = None
sin: "f32[3, 3, 3]" = diff_args.sin()
add: "f32[3, 3, 3]" = sin + y; sin = y = None
output: "f32[]" = add.sum(); add = None
_autograd_grad = torch._functorch.eager_transforms._autograd_grad((output,), [diff_args], create_graph = True); diff_args = None
grad_input: "f32[3, 3, 3]" = _autograd_grad[0]; _autograd_grad = None
grad_input_1: "f32[3, 3, 3]" = torch._C._functorch._unwrap_for_grad(grad_input, 1); grad_input = None
output_1: "f32[]" = torch._C._functorch._unwrap_for_grad(output, 1); output = output_1 = None
_grad_decrement_nesting = torch._C._functorch._grad_decrement_nesting(); _grad_decrement_nesting = None
_saved_tensors_hooks_enable = torch._C._autograd._saved_tensors_hooks_enable(); _saved_tensors_hooks_enable = None
return (grad_input_1,)
""",
)
def test_grad_closure_scalar(self):
counters.clear()
def wrapper_fn(x):
y = 3.14
def fn(x):
return (x.sin() + y).sum()
return torch.func.grad(fn)(x)
x = torch.randn(3, 3, 3)
# Graph break because dynamo is unable to get source `fn` and
# functools.wraps in `grad` leads to graph-break
wrapped_gm = self._compile_check(wrapper_fn, (x,), fullgraph=False)
# Dynamic shapes produce a slightly different graph.
if check_dynamic_shape_capture():
return
actual = normalize_gm(wrapped_gm.print_readable(print_output=False))
self.assertExpectedInline(
actual,
"""\
| GraphModule |
python | huggingface__transformers | src/transformers/models/dinat/modeling_dinat.py | {
"start": 22219,
"end": 22409
} | class ____(PreTrainedModel):
config: DinatConfig
base_model_prefix = "dinat"
main_input_name = "pixel_values"
input_modalities = ("image",)
@auto_docstring
| DinatPreTrainedModel |
python | PrefectHQ__prefect | src/prefect/server/services/base.py | {
"start": 4813,
"end": 11979
} | class ____(Service, abc.ABC):
"""
Loop services are relatively lightweight maintenance routines that need to run
periodically.
This class makes it straightforward to design and integrate them. Users only need to
define the `run_once` coroutine to describe the behavior of the service on each
loop.
"""
loop_seconds = 60
def __init__(
self, loop_seconds: Optional[float] = None, handle_signals: bool = False
):
"""
Args:
loop_seconds (float): if provided, overrides the loop interval
otherwise specified as a class variable
handle_signals (bool): if True, SIGINT and SIGTERM are
gracefully intercepted and shut down the running service.
"""
super().__init__()
if loop_seconds:
self.loop_seconds: float = loop_seconds # seconds between runs
self._should_stop: bool = (
False # flag for whether the service should stop running
)
self._is_running: bool = False # flag for whether the service is running
if handle_signals:
_register_signal(signal.SIGINT, self._stop)
_register_signal(signal.SIGTERM, self._stop)
async def _on_start(self) -> None:
"""
Called prior to running the service
"""
self._should_stop = False
self._is_running = True
self.logger.debug(f"Starting {self.name}")
async def _on_stop(self) -> None:
"""
Called after running the service
"""
self._is_running = False
self.logger.debug(f"Stopped {self.name}")
@overload
async def start(self, loops: None = None) -> NoReturn:
"""
Run the service indefinitely.
"""
...
@overload
async def start(self, loops: int) -> None:
"""
Run the service `loops` time.
Args:
loops (int): the number of loops to run before exiting.
"""
...
async def start(self, loops: int | None = None) -> None | NoReturn:
"""
Run the service `loops` time. Pass loops=None to run forever.
Args:
loops (int, optional): the number of loops to run before exiting.
"""
await self._on_start()
i = 0
while not self._should_stop:
start_time = now("UTC")
try:
self.logger.debug(f"About to run {self.name}...")
await self.run_once()
except asyncio.CancelledError:
self.logger.info(f"Received cancellation signal for {self.name}")
raise
except Exception as exc:
# avoid circular import
from prefect.server.api.server import is_client_retryable_exception
retryable_error = is_client_retryable_exception(exc)
if not retryable_error or (
retryable_error and PREFECT_API_LOG_RETRYABLE_ERRORS.value()
):
self.logger.error(
f"Unexpected error in: {repr(exc)}", exc_info=True
)
end_time = now("UTC")
# if service took longer than its loop interval, log a warning
# that the interval might be too short
if (end_time - start_time).total_seconds() > self.loop_seconds:
self.logger.warning(
f"{self.name} took {(end_time - start_time).total_seconds()} seconds"
" to run, which is longer than its loop interval of"
f" {self.loop_seconds} seconds."
)
# check if early stopping was requested
i += 1
if loops is not None and i == loops:
self.logger.debug(f"{self.name} exiting after {loops} loop(s).")
await self.stop(block=False)
# next run is every "loop seconds" after each previous run *started*.
# note that if the loop took unexpectedly long, the "next_run" time
# might be in the past, which will result in an instant start
next_run = max(
start_time + timedelta(seconds=self.loop_seconds), now("UTC")
)
self.logger.debug(f"Finished running {self.name}. Next run at {next_run}")
# check the `_should_stop` flag every 1 seconds until the next run time is reached
while now("UTC") < next_run and not self._should_stop:
await asyncio.sleep(min(1, (next_run - now("UTC")).total_seconds()))
await self._on_stop()
async def stop(self, block: bool = True) -> None:
"""
Gracefully stops a running LoopService and optionally blocks until the
service stops.
Args:
block (bool): if True, blocks until the service is
finished running. Otherwise it requests a stop and returns but
the service may still be running a final loop.
"""
self.logger.debug(f"Stopping {self.name}...")
self._stop()
if block:
# if block=True, sleep until the service stops running,
# but no more than `loop_seconds` to avoid a deadlock
with anyio.move_on_after(self.loop_seconds):
while self._is_running:
await asyncio.sleep(0.1)
# if the service is still running after `loop_seconds`, something's wrong
if self._is_running:
self.logger.warning(
f"`stop(block=True)` was called on {self.name} but more than one"
f" loop interval ({self.loop_seconds} seconds) has passed. This"
" usually means something is wrong. If `stop()` was called from"
" inside the loop service, use `stop(block=False)` instead."
)
def _stop(self, *_: Any) -> None:
"""
Private, synchronous method for setting the `_should_stop` flag. Takes arbitrary
arguments so it can be used as a signal handler.
"""
self._should_stop = True
@abstractmethod
async def run_once(self) -> None:
"""
Represents one loop of the service.
Subclasses must override this method.
To actually run the service once, call `LoopService().start(loops=1)`
instead of `LoopService().run_once()`, because this method will not invoke setup
and teardown methods properly.
"""
...
async def run_multiple_services(loop_services: List[LoopService]) -> NoReturn:
"""
Only one signal handler can be active at a time, so this function takes a list
of loop services and runs all of them with a global signal handler.
"""
def stop_all_services(*_: Any) -> None:
for service in loop_services:
stop = methodcaller("_stop")
stop(service)
signal.signal(signal.SIGINT, stop_all_services)
signal.signal(signal.SIGTERM, stop_all_services)
await asyncio.gather(*[service.start() for service in loop_services])
| LoopService |
python | conda__conda | conda/common/configuration.py | {
"start": 3011,
"end": 3302
} | class ____(ConfigurationError):
def __init__(self, parameter_name, parameter_value, source, msg=None, **kwargs):
self.parameter_name = parameter_name
self.parameter_value = parameter_value
self.source = source
super().__init__(msg, **kwargs)
| ValidationError |
python | pypa__pip | src/pip/_internal/resolution/resolvelib/requirements.py | {
"start": 395,
"end": 1513
} | class ____(Requirement):
def __init__(self, candidate: Candidate) -> None:
self.candidate = candidate
def __str__(self) -> str:
return str(self.candidate)
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.candidate!r})"
def __hash__(self) -> int:
return hash(self.candidate)
def __eq__(self, other: Any) -> bool:
if not isinstance(other, ExplicitRequirement):
return False
return self.candidate == other.candidate
@property
def project_name(self) -> NormalizedName:
# No need to canonicalize - the candidate did this
return self.candidate.project_name
@property
def name(self) -> str:
# No need to canonicalize - the candidate did this
return self.candidate.name
def format_for_error(self) -> str:
return self.candidate.format_for_error()
def get_candidate_lookup(self) -> CandidateLookup:
return self.candidate, None
def is_satisfied_by(self, candidate: Candidate) -> bool:
return candidate == self.candidate
| ExplicitRequirement |
python | huggingface__transformers | src/transformers/models/trocr/modeling_trocr.py | {
"start": 28636,
"end": 29046
} | class ____(TrOCRPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.decoder = TrOCRDecoder(config)
def forward(self, *args, **kwargs):
return self.decoder(*args, **kwargs)
@auto_docstring(
custom_intro="""
The TrOCR Decoder with a language modeling head. Can be used as the decoder part of [`EncoderDecoderModel`] and
"""
)
| TrOCRDecoderWrapper |
python | langchain-ai__langchain | libs/text-splitters/langchain_text_splitters/nltk.py | {
"start": 230,
"end": 1973
} | class ____(TextSplitter):
"""Splitting text using NLTK package."""
def __init__(
self,
separator: str = "\n\n",
language: str = "english",
*,
use_span_tokenize: bool = False,
**kwargs: Any,
) -> None:
"""Initialize the NLTK splitter."""
super().__init__(**kwargs)
self._separator = separator
self._language = language
self._use_span_tokenize = use_span_tokenize
if self._use_span_tokenize and self._separator:
msg = "When use_span_tokenize is True, separator should be ''"
raise ValueError(msg)
if not _HAS_NLTK:
msg = "NLTK is not installed, please install it with `pip install nltk`."
raise ImportError(msg)
if self._use_span_tokenize:
self._tokenizer = nltk.tokenize._get_punkt_tokenizer(self._language) # noqa: SLF001
else:
self._tokenizer = nltk.tokenize.sent_tokenize
def split_text(self, text: str) -> list[str]:
"""Split incoming text and return chunks."""
# First we naively split the large input into a bunch of smaller ones.
if self._use_span_tokenize:
spans = list(self._tokenizer.span_tokenize(text))
splits = []
for i, (start, end) in enumerate(spans):
if i > 0:
prev_end = spans[i - 1][1]
sentence = text[prev_end:start] + text[start:end]
else:
sentence = text[start:end]
splits.append(sentence)
else:
splits = self._tokenizer(text, language=self._language)
return self._merge_splits(splits, self._separator)
| NLTKTextSplitter |
python | joblib__joblib | joblib/externals/loky/backend/synchronize.py | {
"start": 1654,
"end": 4268
} | class ____:
_rand = tempfile._RandomNameSequence()
def __init__(self, kind, value, maxvalue, name=None):
# unlink_now is only used on win32 or when we are using fork.
unlink_now = False
if name is None:
# Try to find an unused name for the SemLock instance.
for _ in range(100):
try:
self._semlock = _SemLock(
kind, value, maxvalue, SemLock._make_name(), unlink_now
)
except FileExistsError: # pragma: no cover
pass
else:
break
else: # pragma: no cover
raise FileExistsError("cannot find name for semaphore")
else:
self._semlock = _SemLock(kind, value, maxvalue, name, unlink_now)
self.name = name
util.debug(
f"created semlock with handle {self._semlock.handle} and name "
f'"{self.name}"'
)
self._make_methods()
def _after_fork(obj):
obj._semlock._after_fork()
util.register_after_fork(self, _after_fork)
# When the object is garbage collected or the
# process shuts down we unlink the semaphore name
resource_tracker.register(self._semlock.name, "semlock")
util.Finalize(
self, SemLock._cleanup, (self._semlock.name,), exitpriority=0
)
@staticmethod
def _cleanup(name):
try:
sem_unlink(name)
except FileNotFoundError:
# Already unlinked, possibly by user code: ignore and make sure to
# unregister the semaphore from the resource tracker.
pass
finally:
resource_tracker.unregister(name, "semlock")
def _make_methods(self):
self.acquire = self._semlock.acquire
self.release = self._semlock.release
def __enter__(self):
return self._semlock.acquire()
def __exit__(self, *args):
return self._semlock.release()
def __getstate__(self):
assert_spawning(self)
sl = self._semlock
h = sl.handle
return (h, sl.kind, sl.maxvalue, sl.name)
def __setstate__(self, state):
self._semlock = _SemLock._rebuild(*state)
util.debug(
f'recreated blocker with handle {state[0]!r} and name "{state[3]}"'
)
self._make_methods()
@staticmethod
def _make_name():
# OSX does not support long names for semaphores
return f"/loky-{os.getpid()}-{next(SemLock._rand)}"
#
# Semaphore
#
| SemLock |
python | bokeh__bokeh | src/bokeh/models/annotations/dimensional.py | {
"start": 4462,
"end": 4762
} | class ____(Metric):
""" Metric units of length measurement.
"""
# explicit __init__ to support Init signatures
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
base_unit = Override(default="m")
exclude = Override(default=["dm", "hm"])
| MetricLength |
python | getsentry__sentry | src/sentry/preprod/analytics.py | {
"start": 2195,
"end": 2468
} | class ____(analytics.Event):
organization_id: int
project_id: int
user_id: int | None = None
head_artifact_id: str
base_artifact_id: str
@analytics.eventclass("preprod_artifact.api.size_analysis_compare.post")
| PreprodArtifactApiSizeAnalysisCompareGetEvent |
python | getlogbook__logbook | src/logbook/queues.py | {
"start": 7979,
"end": 9097
} | class ____:
"""A helper class used by queue subscribers to control the background
thread. This is usually created and started in one go by
:meth:`~logbook.queues.ZeroMQSubscriber.dispatch_in_background` or
a comparable function.
"""
def __init__(self, subscriber, setup=None):
self.setup = setup
self.subscriber = subscriber
self.running = False
self._thread = None
def start(self):
"""Starts the task thread."""
self.running = True
self._thread = Thread(target=self._target)
self._thread.daemon = True
self._thread.start()
def stop(self):
"""Stops the task thread."""
if self.running:
self.running = False
self._thread.join()
self._thread = None
def _target(self):
if self.setup is not None:
self.setup.push_thread()
try:
while self.running:
self.subscriber.dispatch_once(timeout=0.05)
finally:
if self.setup is not None:
self.setup.pop_thread()
| ThreadController |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/ext/mutable.py | {
"start": 3868,
"end": 9443
} | class ____ associates a listener that will detect all future mappings
of this type, applying event listening instrumentation to the mapped
attribute. Such as, with classical table metadata::
from sqlalchemy import Table, Column, Integer
my_data = Table(
"my_data",
metadata,
Column("id", Integer, primary_key=True),
Column("data", MutableDict.as_mutable(JSONEncodedDict)),
)
Above, :meth:`~.Mutable.as_mutable` returns an instance of ``JSONEncodedDict``
(if the type object was not an instance already), which will intercept any
attributes which are mapped against this type. Below we establish a simple
mapping against the ``my_data`` table::
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
class Base(DeclarativeBase):
pass
class MyDataClass(Base):
__tablename__ = "my_data"
id: Mapped[int] = mapped_column(primary_key=True)
data: Mapped[dict[str, str]] = mapped_column(
MutableDict.as_mutable(JSONEncodedDict)
)
The ``MyDataClass.data`` member will now be notified of in place changes
to its value.
Any in-place changes to the ``MyDataClass.data`` member
will flag the attribute as "dirty" on the parent object::
>>> from sqlalchemy.orm import Session
>>> sess = Session(some_engine)
>>> m1 = MyDataClass(data={"value1": "foo"})
>>> sess.add(m1)
>>> sess.commit()
>>> m1.data["value1"] = "bar"
>>> assert m1 in sess.dirty
True
The ``MutableDict`` can be associated with all future instances
of ``JSONEncodedDict`` in one step, using
:meth:`~.Mutable.associate_with`. This is similar to
:meth:`~.Mutable.as_mutable` except it will intercept all occurrences
of ``MutableDict`` in all mappings unconditionally, without
the need to declare it individually::
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
MutableDict.associate_with(JSONEncodedDict)
class Base(DeclarativeBase):
pass
class MyDataClass(Base):
__tablename__ = "my_data"
id: Mapped[int] = mapped_column(primary_key=True)
data: Mapped[dict[str, str]] = mapped_column(JSONEncodedDict)
Supporting Pickling
--------------------
The key to the :mod:`sqlalchemy.ext.mutable` extension relies upon the
placement of a ``weakref.WeakKeyDictionary`` upon the value object, which
stores a mapping of parent mapped objects keyed to the attribute name under
which they are associated with this value. ``WeakKeyDictionary`` objects are
not picklable, due to the fact that they contain weakrefs and function
callbacks. In our case, this is a good thing, since if this dictionary were
picklable, it could lead to an excessively large pickle size for our value
objects that are pickled by themselves outside of the context of the parent.
The developer responsibility here is only to provide a ``__getstate__`` method
that excludes the :meth:`~MutableBase._parents` collection from the pickle
stream::
class MyMutableType(Mutable):
def __getstate__(self):
d = self.__dict__.copy()
d.pop("_parents", None)
return d
With our dictionary example, we need to return the contents of the dict itself
(and also restore them on __setstate__)::
class MutableDict(Mutable, dict):
# ....
def __getstate__(self):
return dict(self)
def __setstate__(self, state):
self.update(state)
In the case that our mutable value object is pickled as it is attached to one
or more parent objects that are also part of the pickle, the :class:`.Mutable`
mixin will re-establish the :attr:`.Mutable._parents` collection on each value
object as the owning parents themselves are unpickled.
Receiving Events
----------------
The :meth:`.AttributeEvents.modified` event handler may be used to receive
an event when a mutable scalar emits a change event. This event handler
is called when the :func:`.attributes.flag_modified` function is called
from within the mutable extension::
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy import event
class Base(DeclarativeBase):
pass
class MyDataClass(Base):
__tablename__ = "my_data"
id: Mapped[int] = mapped_column(primary_key=True)
data: Mapped[dict[str, str]] = mapped_column(
MutableDict.as_mutable(JSONEncodedDict)
)
@event.listens_for(MyDataClass.data, "modified")
def modified_json(instance, initiator):
print("json value modified:", instance.data)
.. _mutable_composites:
Establishing Mutability on Composites
=====================================
Composites are a special ORM feature which allow a single scalar attribute to
be assigned an object value which represents information "composed" from one
or more columns from the underlying mapped table. The usual example is that of
a geometric "point", and is introduced in :ref:`mapper_composite`.
As is the case with :class:`.Mutable`, the user-defined composite class
subclasses :class:`.MutableComposite` as a mixin, and detects and delivers
change events to its parents via the :meth:`.MutableComposite.changed` method.
In the case of a composite class, the detection is usually via the usage of the
special Python method ``__setattr__()``. In the example below, we expand upon the ``Point``
| and |
python | getsentry__sentry | src/sentry/utils/snuba.py | {
"start": 13678,
"end": 13788
} | class ____(SnubaError):
"""
Exception raised when a query failed to execute.
"""
| QueryExecutionError |
python | pytorch__pytorch | torch/distributed/pipelining/schedules.py | {
"start": 102479,
"end": 107909
} | class ____(_PipelineScheduleRuntime):
"""
The Interleaved 1F1B schedule.
See https://arxiv.org/pdf/2104.04473 for details.
Will perform one forward and one backward on the microbatches in steady
state and supports multiple stages per rank. When microbatches are ready for
multiple local stages, Interleaved 1F1B prioritizes the earlier microbatch
(also called "depth first").
This schedule is mostly similar to the original paper.
It differs by being relaxing the requirement of num_microbatch % pp_size == 0.
Using the flex_pp schedule, we will have num_rounds = max(1, n_microbatches // pp_group_size) and
it works as long as n_microbatches % num_rounds is 0. As a few examples, support
1. pp_group_size = 4, n_microbatches = 10. We will have num_rounds = 2 and n_microbatches % 2 is 0.
2. pp_group_size = 4, n_microbatches = 3. We will have num_rounds = 1 and n_microbatches % 1 is 0.
"""
def __init__(
self,
stages: list[_PipelineStageBase],
n_microbatches: int,
loss_fn: Callable | None = None,
args_chunk_spec: tuple[TensorChunkSpec, ...] | None = None,
kwargs_chunk_spec: dict[str, TensorChunkSpec] | None = None,
output_merge_spec: dict[str, Any] | tuple[Any] | None = None,
scale_grads: bool = True,
backward_requires_autograd: bool = True,
):
self.pp_group_size = stages[0].group_size
super().__init__(
stages=stages,
n_microbatches=n_microbatches,
loss_fn=loss_fn,
args_chunk_spec=args_chunk_spec,
kwargs_chunk_spec=kwargs_chunk_spec,
output_merge_spec=output_merge_spec,
scale_grads=scale_grads,
backward_requires_autograd=backward_requires_autograd,
)
self.n_local_stages = len(stages)
self.rank = stages[0].group_rank
self.number_of_rounds = max(1, n_microbatches // self.pp_group_size)
self.microbatches_per_round = n_microbatches // self.number_of_rounds
if n_microbatches % self.number_of_rounds != 0:
raise ValueError(
"Interleaved 1F1B requires the number of microbatches to be a "
f"multiple of the number of rounds ({self.number_of_rounds}), "
f"but got {n_microbatches}."
)
# 1. Create the pipeline_order (all ranks do this calculation)
# This will be used to keep track of the current state of the entire pipeline
# pipeline_order[rank] = [Action(computation_type, microbatch_index, stage_index), ...]
self.pipeline_order: dict[int, list[_Action | None]] = {}
for rank in range(self.pp_group_size):
rank_ops = self._calculate_single_rank_operations(rank)
self.pipeline_order[rank] = rank_ops
# Initialize the pipeline order with communication necessary to run with _PipelineScheduleRuntime
self._prepare_schedule_with_comms(self.pipeline_order)
def _calculate_single_rank_operations(self, rank) -> list[_Action | None]:
def get_rank_warmup_ops(rank):
# Warms up operations for last stage
warmups_ops_last_stage = (
self.n_local_stages - 1
) * self.microbatches_per_round
# Increment warmup operations by 2 for each hop away from the last stage
multiply_factor = 2
warmup_ops = warmups_ops_last_stage + multiply_factor * (
(self.pp_group_size - 1) - rank
)
# We cannot have more warmup operations than there are number of microbatches, so cap it there
return min(warmup_ops, self._n_microbatches * self.n_local_stages)
warmup_ops = get_rank_warmup_ops(rank)
microbatch_ops = self.n_local_stages * self._n_microbatches
# fwd_bwd_ops should encompass the remaining forwards
fwd_bwd_ops = microbatch_ops - warmup_ops
# cooldown_ops should encompass the remaining backwards
cooldown_ops = microbatch_ops - fwd_bwd_ops
# total ops encompass both forward and backward ops
total_ops = warmup_ops + fwd_bwd_ops + cooldown_ops
# warmup_ops + fwd_bwd_ops * 2 + cooldown_ops == microbatch_ops * 2
logger.debug(
"rank %s, warmup_ops %s, 1f1b %s, cooldown_ops %s total_ops %s",
rank,
warmup_ops,
fwd_bwd_ops,
cooldown_ops,
total_ops,
)
# Calculates the stage index based on step and pp_group_size
def forward_stage_index(step):
# Get the local index from 0 to n_local_stages-1
local_index = (step // self.microbatches_per_round) % self.n_local_stages
return (local_index * self.pp_group_size) + rank
def backward_stage_index(step):
local_index = (
self.n_local_stages
- 1
- ((step - warmup_ops) // self.microbatches_per_round)
% self.n_local_stages
)
return (local_index * self.pp_group_size) + rank
return _get_1f1b_rank_ops(
self.n_local_stages,
self.pp_group_size,
warmup_ops,
fwd_bwd_ops,
cooldown_ops,
rank,
forward_stage_index,
backward_stage_index,
)
| ScheduleInterleaved1F1B |
python | joke2k__faker | faker/providers/passport/ru_RU/__init__.py | {
"start": 412,
"end": 892
} | class ____(BaseProvider):
passport_number_formats: ElementsType = (
"## ## ######",
"#### ######",
)
def passport_owner(self, gender: SexLiteral = "M") -> Tuple[str, str]:
generator_string = GENDER_TO_GENERATOR[gender]
last_name, first_name, middle_name = self.generator.parse(generator_string).split()
first_name_united_with_middle = first_name + " " + middle_name
return last_name, first_name_united_with_middle
| Provider |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 21893,
"end": 22318
} | class ____(Pix2SkyProjection, Cylindrical):
r"""
Plate carrée projection - pixel to sky.
Corresponds to the ``CAR`` projection in FITS WCS.
.. math::
\phi &= x \\
\theta &= y
"""
@staticmethod
def evaluate(x, y):
# The intermediate variables are only used here for clarity
phi = np.array(x)
theta = np.array(y)
return phi, theta
| Pix2Sky_PlateCarree |
python | numpy__numpy | tools/swig/test/testVector.py | {
"start": 11428,
"end": 11695
} | class ____(VectorTestCase):
def __init__(self, methodName="runTest"):
VectorTestCase.__init__(self, methodName)
self.typeStr = "ushort"
self.typeCode = "H"
######################################################################
| ushortTestCase |
python | scikit-learn__scikit-learn | sklearn/model_selection/_plot.py | {
"start": 19725,
"end": 34606
} | class ____(_BaseCurveDisplay):
"""Validation Curve visualization.
It is recommended to use
:meth:`~sklearn.model_selection.ValidationCurveDisplay.from_estimator` to
create a :class:`~sklearn.model_selection.ValidationCurveDisplay` instance.
All parameters are stored as attributes.
Read more in the :ref:`User Guide <visualizations>` for general information
about the visualization API and :ref:`detailed documentation
<validation_curve>` regarding the validation curve visualization.
.. versionadded:: 1.3
Parameters
----------
param_name : str
Name of the parameter that has been varied.
param_range : array-like of shape (n_ticks,)
The values of the parameter that have been evaluated.
train_scores : ndarray of shape (n_ticks, n_cv_folds)
Scores on training sets.
test_scores : ndarray of shape (n_ticks, n_cv_folds)
Scores on test set.
score_name : str, default=None
The name of the score used in `validation_curve`. It will override the name
inferred from the `scoring` parameter. If `score` is `None`, we use `"Score"` if
`negate_score` is `False` and `"Negative score"` otherwise. If `scoring` is a
string or a callable, we infer the name. We replace `_` by spaces and capitalize
the first letter. We remove `neg_` and replace it by `"Negative"` if
`negate_score` is `False` or just remove it otherwise.
Attributes
----------
ax_ : matplotlib Axes
Axes with the validation curve.
figure_ : matplotlib Figure
Figure containing the validation curve.
errorbar_ : list of matplotlib Artist or None
When the `std_display_style` is `"errorbar"`, this is a list of
`matplotlib.container.ErrorbarContainer` objects. If another style is
used, `errorbar_` is `None`.
lines_ : list of matplotlib Artist or None
When the `std_display_style` is `"fill_between"`, this is a list of
`matplotlib.lines.Line2D` objects corresponding to the mean train and
test scores. If another style is used, `line_` is `None`.
fill_between_ : list of matplotlib Artist or None
When the `std_display_style` is `"fill_between"`, this is a list of
`matplotlib.collections.PolyCollection` objects. If another style is
used, `fill_between_` is `None`.
See Also
--------
sklearn.model_selection.validation_curve : Compute the validation curve.
Examples
--------
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from sklearn.datasets import make_classification
>>> from sklearn.model_selection import ValidationCurveDisplay, validation_curve
>>> from sklearn.linear_model import LogisticRegression
>>> X, y = make_classification(n_samples=1_000, random_state=0)
>>> logistic_regression = LogisticRegression()
>>> param_name, param_range = "C", np.logspace(-8, 3, 10)
>>> train_scores, test_scores = validation_curve(
... logistic_regression, X, y, param_name=param_name, param_range=param_range
... )
>>> display = ValidationCurveDisplay(
... param_name=param_name, param_range=param_range,
... train_scores=train_scores, test_scores=test_scores, score_name="Score"
... )
>>> display.plot()
<...>
>>> plt.show()
"""
def __init__(
self, *, param_name, param_range, train_scores, test_scores, score_name=None
):
self.param_name = param_name
self.param_range = param_range
self.train_scores = train_scores
self.test_scores = test_scores
self.score_name = score_name
def plot(
self,
ax=None,
*,
negate_score=False,
score_name=None,
score_type="both",
std_display_style="fill_between",
line_kw=None,
fill_between_kw=None,
errorbar_kw=None,
):
"""Plot visualization.
Parameters
----------
ax : matplotlib Axes, default=None
Axes object to plot on. If `None`, a new figure and axes is
created.
negate_score : bool, default=False
Whether or not to negate the scores obtained through
:func:`~sklearn.model_selection.validation_curve`. This is
particularly useful when using the error denoted by `neg_*` in
`scikit-learn`.
score_name : str, default=None
The name of the score used to decorate the y-axis of the plot. It will
override the name inferred from the `scoring` parameter. If `score` is
`None`, we use `"Score"` if `negate_score` is `False` and `"Negative score"`
otherwise. If `scoring` is a string or a callable, we infer the name. We
replace `_` by spaces and capitalize the first letter. We remove `neg_` and
replace it by `"Negative"` if `negate_score` is
`False` or just remove it otherwise.
score_type : {"test", "train", "both"}, default="both"
The type of score to plot. Can be one of `"test"`, `"train"`, or
`"both"`.
std_display_style : {"errorbar", "fill_between"} or None, default="fill_between"
The style used to display the score standard deviation around the
mean score. If None, no standard deviation representation is
displayed.
line_kw : dict, default=None
Additional keyword arguments passed to the `plt.plot` used to draw
the mean score.
fill_between_kw : dict, default=None
Additional keyword arguments passed to the `plt.fill_between` used
to draw the score standard deviation.
errorbar_kw : dict, default=None
Additional keyword arguments passed to the `plt.errorbar` used to
draw mean score and standard deviation score.
Returns
-------
display : :class:`~sklearn.model_selection.ValidationCurveDisplay`
Object that stores computed values.
"""
self._plot_curve(
self.param_range,
ax=ax,
negate_score=negate_score,
score_name=score_name,
score_type=score_type,
std_display_style=std_display_style,
line_kw=line_kw,
fill_between_kw=fill_between_kw,
errorbar_kw=errorbar_kw,
)
self.ax_.set_xlabel(f"{self.param_name}")
return self
@classmethod
def from_estimator(
cls,
estimator,
X,
y,
*,
param_name,
param_range,
groups=None,
cv=None,
scoring=None,
n_jobs=None,
pre_dispatch="all",
verbose=0,
error_score=np.nan,
fit_params=None,
ax=None,
negate_score=False,
score_name=None,
score_type="both",
std_display_style="fill_between",
line_kw=None,
fill_between_kw=None,
errorbar_kw=None,
):
"""Create a validation curve display from an estimator.
Read more in the :ref:`User Guide <visualizations>` for general
information about the visualization API and :ref:`detailed
documentation <validation_curve>` regarding the validation curve
visualization.
Parameters
----------
estimator : object type that implements the "fit" and "predict" methods
An object of that type which is cloned for each validation.
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples and
`n_features` is the number of features.
y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None
Target relative to X for classification or regression;
None for unsupervised learning.
param_name : str
Name of the parameter that will be varied.
param_range : array-like of shape (n_values,)
The values of the parameter that will be evaluated.
groups : array-like of shape (n_samples,), default=None
Group labels for the samples used while splitting the dataset into
train/test set. Only used in conjunction with a "Group" :term:`cv`
instance (e.g., :class:`GroupKFold`).
cv : int, cross-validation generator or an iterable, default=None
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 5-fold cross validation,
- int, to specify the number of folds in a `(Stratified)KFold`,
- :term:`CV splitter`,
- An iterable yielding (train, test) splits as arrays of indices.
For int/None inputs, if the estimator is a classifier and `y` is
either binary or multiclass,
:class:`~sklearn.model_selection.StratifiedKFold` is used. In all
other cases, :class:`~sklearn.model_selection.KFold` is used. These
splitters are instantiated with `shuffle=False` so the splits will
be the same across calls.
Refer :ref:`User Guide <cross_validation>` for the various
cross-validation strategies that can be used here.
scoring : str or callable, default=None
Scoring method to use when computing the validation curve. Options:
- str: see :ref:`scoring_string_names` for options.
- callable: a scorer callable object (e.g., function) with signature
``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details.
- `None`: the `estimator`'s
:ref:`default evaluation criterion <scoring_api_overview>` is used.
n_jobs : int, default=None
Number of jobs to run in parallel. Training the estimator and
computing the score are parallelized over the different training
and test sets. `None` means 1 unless in a
:obj:`joblib.parallel_backend` context. `-1` means using all
processors. See :term:`Glossary <n_jobs>` for more details.
pre_dispatch : int or str, default='all'
Number of predispatched jobs for parallel execution (default is
all). The option can reduce the allocated memory. The str can
be an expression like '2*n_jobs'.
verbose : int, default=0
Controls the verbosity: the higher, the more messages.
error_score : 'raise' or numeric, default=np.nan
Value to assign to the score if an error occurs in estimator
fitting. If set to 'raise', the error is raised. If a numeric value
is given, FitFailedWarning is raised.
fit_params : dict, default=None
Parameters to pass to the fit method of the estimator.
ax : matplotlib Axes, default=None
Axes object to plot on. If `None`, a new figure and axes is
created.
negate_score : bool, default=False
Whether or not to negate the scores obtained through
:func:`~sklearn.model_selection.validation_curve`. This is
particularly useful when using the error denoted by `neg_*` in
`scikit-learn`.
score_name : str, default=None
The name of the score used to decorate the y-axis of the plot. It will
override the name inferred from the `scoring` parameter. If `score` is
`None`, we use `"Score"` if `negate_score` is `False` and `"Negative score"`
otherwise. If `scoring` is a string or a callable, we infer the name. We
replace `_` by spaces and capitalize the first letter. We remove `neg_` and
replace it by `"Negative"` if `negate_score` is
`False` or just remove it otherwise.
score_type : {"test", "train", "both"}, default="both"
The type of score to plot. Can be one of `"test"`, `"train"`, or
`"both"`.
std_display_style : {"errorbar", "fill_between"} or None, default="fill_between"
The style used to display the score standard deviation around the
mean score. If `None`, no representation of the standard deviation
is displayed.
line_kw : dict, default=None
Additional keyword arguments passed to the `plt.plot` used to draw
the mean score.
fill_between_kw : dict, default=None
Additional keyword arguments passed to the `plt.fill_between` used
to draw the score standard deviation.
errorbar_kw : dict, default=None
Additional keyword arguments passed to the `plt.errorbar` used to
draw mean score and standard deviation score.
Returns
-------
display : :class:`~sklearn.model_selection.ValidationCurveDisplay`
Object that stores computed values.
Examples
--------
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from sklearn.datasets import make_classification
>>> from sklearn.model_selection import ValidationCurveDisplay
>>> from sklearn.linear_model import LogisticRegression
>>> X, y = make_classification(n_samples=1_000, random_state=0)
>>> logistic_regression = LogisticRegression()
>>> param_name, param_range = "C", np.logspace(-8, 3, 10)
>>> ValidationCurveDisplay.from_estimator(
... logistic_regression, X, y, param_name=param_name,
... param_range=param_range,
... )
<...>
>>> plt.show()
"""
check_matplotlib_support(f"{cls.__name__}.from_estimator")
score_name = _validate_score_name(score_name, scoring, negate_score)
train_scores, test_scores = validation_curve(
estimator,
X,
y,
param_name=param_name,
param_range=param_range,
groups=groups,
cv=cv,
scoring=scoring,
n_jobs=n_jobs,
pre_dispatch=pre_dispatch,
verbose=verbose,
error_score=error_score,
params=fit_params,
)
viz = cls(
param_name=param_name,
param_range=np.asarray(param_range),
train_scores=train_scores,
test_scores=test_scores,
score_name=score_name,
)
return viz.plot(
ax=ax,
negate_score=negate_score,
score_type=score_type,
std_display_style=std_display_style,
line_kw=line_kw,
fill_between_kw=fill_between_kw,
errorbar_kw=errorbar_kw,
)
| ValidationCurveDisplay |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/partitions_schedules_sensors/partitioned_config_test.py | {
"start": 1525,
"end": 2663
} | class ____(dg.Config):
start: str
end: str
@op
def process_data(context: dg.OpExecutionContext, config: ProcessDataConfig):
s = config.start
e = config.end
context.log.info(f"processing data for {s} - {e}")
@job(config=my_offset_partitioned_config)
def do_more_stuff_partitioned():
process_data()
# end_partition_keys
# start_partition_keys_test
def test_my_offset_partitioned_config():
# test that the partition keys are what you expect
keys = my_offset_partitioned_config.get_partition_keys()
assert keys[0] == "2020-01-01"
assert keys[1] == "2020-01-02"
# test that the run_config for a partition is valid for partitioned_op_job
run_config = my_offset_partitioned_config.get_run_config_for_partition_key(keys[0])
assert dg.validate_run_config(do_more_stuff_partitioned, run_config)
# test that the contents of run_config are what you expect
assert run_config == {
"ops": {
"process_data": {
"config": {"start": "2020-01-01-00:15", "end": "2020-01-02-00:15"}
}
}
}
# end_partition_keys_test
| ProcessDataConfig |
python | huggingface__transformers | tests/models/gemma2/test_modeling_gemma2.py | {
"start": 1706,
"end": 1907
} | class ____(CausalLMModelTest, unittest.TestCase):
_is_stateful = True
model_split_percents = [0.5, 0.6]
model_tester_class = Gemma2ModelTester
@slow
@require_torch_accelerator
| Gemma2ModelTest |
python | ansible__ansible | test/units/plugins/cache/test_cache.py | {
"start": 4620,
"end": 5454
} | class ____(TestJsonFileCache):
cache_prefix = 'special_'
def test_keys(self):
# For caches with a prefix only files that match the prefix are
# considered. The prefix is removed from the key name.
cache_writer = self.get_cache('')
cache_writer["no_prefix"] = dict(a=1)
cache_writer.update_cache_if_changed()
cache_writer = self.get_cache(self.cache_prefix)
cache_writer["test"] = dict(b=2)
cache_writer.update_cache_if_changed()
# The plugin does not know the CachePluginAdjudicator entries.
assert sorted(self.cache._plugin.keys()) == ['test']
assert 'no_prefix' not in self.cache
assert 'special_test' not in self.cache
assert 'test' in self.cache
assert self.cache['test'] == dict(b=2)
| TestJsonFileCachePrefix |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.