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 | kamyu104__LeetCode-Solutions | Python/maximum-profitable-triplets-with-increasing-prices-i.py | {
"start": 145,
"end": 1337
} | class ____(object):
def maxProfit(self, prices, profits):
"""
:type prices: List[int]
:type profits: List[int]
:rtype: int
"""
NEG_INF = float("-inf")
def query(sl, k):
j = sl.bisect_left((k,))
return sl[j-1][1] if j-1 >= 0 else NEG_INF
def update(sl, k, v):
j = sl.bisect_left((k,))
if j < len(sl) and sl[j][0] == k:
if not (sl[j][1] < v):
return
del sl[j]
elif not (j-1 < 0 or sl[j-1][1] < v):
return
sl.add((k, v))
while j+1 < len(sl) and sl[j+1][1] <= sl[j][1]:
del sl[j+1]
result = NEG_INF
sl1, sl2 = SortedList(), SortedList()
for price, profit in itertools.izip(prices, profits):
result = max(result, query(sl2, price)+profit)
update(sl1, price, profit)
update(sl2, price, query(sl1, price)+profit)
return result if result != NEG_INF else -1
# Time: O(nlogn)
# Space: O(n)
from sortedcontainers import SortedList
# prefix sum, sorted list, binary search, mono stack
| Solution |
python | getsentry__sentry | src/sentry/utils/snuba.py | {
"start": 15729,
"end": 16197
} | class ____(QueryExecutionError):
"""
The connection to clickhouse has failed, and so the query cannot be run
"""
clickhouse_error_codes_map = {
10: QueryMissingColumn,
43: QueryIllegalTypeOfArgument,
47: QueryMissingColumn,
62: QuerySizeExceeded,
160: QueryExecutionTimeMaximum,
202: QueryTooManySimultaneous,
241: QueryMemoryLimitExceeded,
271: DatasetSelectionError,
279: QueryConnectionFailed,
}
| QueryConnectionFailed |
python | py-pdf__pypdf | pypdf/_page.py | {
"start": 13591,
"end": 15734
} | class ____(Sequence[ImageFile]):
"""
Provides access to images referenced within a page.
Only one copy will be returned if the usage is used on the same page multiple times.
See :func:`PageObject.images` for more details.
"""
def __init__(
self,
ids_function: Callable[[], list[Union[str, list[str]]]],
get_function: Callable[[Union[str, list[str], tuple[str]]], ImageFile],
) -> None:
self.ids_function = ids_function
self.get_function = get_function
self.current = -1
def __len__(self) -> int:
return len(self.ids_function())
def keys(self) -> list[Union[str, list[str]]]:
return self.ids_function()
def items(self) -> list[tuple[Union[str, list[str]], ImageFile]]:
return [(x, self[x]) for x in self.ids_function()]
@overload
def __getitem__(self, index: Union[int, str, list[str]]) -> ImageFile:
...
@overload
def __getitem__(self, index: slice) -> Sequence[ImageFile]:
...
def __getitem__(
self, index: Union[int, slice, str, list[str], tuple[str]]
) -> Union[ImageFile, Sequence[ImageFile]]:
lst = self.ids_function()
if isinstance(index, slice):
indices = range(*index.indices(len(self)))
lst = [lst[x] for x in indices]
cls = type(self)
return cls((lambda: lst), self.get_function)
if isinstance(index, (str, list, tuple)):
return self.get_function(index)
if not isinstance(index, int):
raise TypeError("Invalid sequence indices type")
len_self = len(lst)
if index < 0:
# support negative indexes
index += len_self
if not (0 <= index < len_self):
raise IndexError("Sequence index out of range")
return self.get_function(lst[index])
def __iter__(self) -> Iterator[ImageFile]:
for i in range(len(self)):
yield self[i]
def __str__(self) -> str:
p = [f"Image_{i}={n}" for i, n in enumerate(self.ids_function())]
return f"[{', '.join(p)}]"
| VirtualListImages |
python | Netflix__metaflow | test/core/tests/param_names.py | {
"start": 48,
"end": 604
} | class ____(MetaflowTest):
PRIORITY = 1
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_foreach",
"recursive_switch",
"recursive_switch_inside_foreach",
]
PARAMETERS = {"foo": {"default": 1}}
@steps(0, ["all"])
def step_all(self):
from metaflow import current
assert_equals(len(current.parameter_names), 1)
assert_equals(current.parameter_names[0], "foo")
| ParameterNameTest |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/check_ops_test.py | {
"start": 87293,
"end": 89836
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_assert_same_float_dtype(self):
self.assertIs(dtypes.float32,
check_ops.assert_same_float_dtype(None, None))
self.assertIs(dtypes.float32, check_ops.assert_same_float_dtype([], None))
self.assertIs(dtypes.float32,
check_ops.assert_same_float_dtype([], dtypes.float32))
self.assertIs(dtypes.float32,
check_ops.assert_same_float_dtype(None, dtypes.float32))
self.assertIs(dtypes.float32,
check_ops.assert_same_float_dtype([None, None], None))
self.assertIs(
dtypes.float32,
check_ops.assert_same_float_dtype([None, None], dtypes.float32))
const_float = constant_op.constant(3.0, dtype=dtypes.float32)
self.assertIs(
dtypes.float32,
check_ops.assert_same_float_dtype([const_float], dtypes.float32))
self.assertRaises(ValueError, check_ops.assert_same_float_dtype,
[const_float], dtypes.int32)
sparse_float = sparse_tensor.SparseTensor(
constant_op.constant([[111], [232]], dtypes.int64),
constant_op.constant([23.4, -43.2], dtypes.float32),
constant_op.constant([500], dtypes.int64))
self.assertIs(dtypes.float32,
check_ops.assert_same_float_dtype([sparse_float],
dtypes.float32))
self.assertRaises(ValueError, check_ops.assert_same_float_dtype,
[sparse_float], dtypes.int32)
self.assertRaises(ValueError, check_ops.assert_same_float_dtype,
[const_float, None, sparse_float], dtypes.float64)
self.assertIs(dtypes.float32,
check_ops.assert_same_float_dtype(
[const_float, sparse_float]))
self.assertIs(dtypes.float32,
check_ops.assert_same_float_dtype(
[const_float, sparse_float], dtypes.float32))
const_int = constant_op.constant(3, dtype=dtypes.int32)
self.assertRaises(ValueError, check_ops.assert_same_float_dtype,
[sparse_float, const_int])
self.assertRaises(ValueError, check_ops.assert_same_float_dtype,
[sparse_float, const_int], dtypes.int32)
self.assertRaises(ValueError, check_ops.assert_same_float_dtype,
[sparse_float, const_int], dtypes.float32)
self.assertRaises(ValueError, check_ops.assert_same_float_dtype,
[const_int])
| FloatDTypeTest |
python | keras-team__keras | keras/src/layers/preprocessing/image_preprocessing/random_erasing.py | {
"start": 280,
"end": 11233
} | class ____(BaseImagePreprocessingLayer):
"""Random Erasing data augmentation technique.
Random Erasing is a data augmentation method where random patches of
an image are erased (replaced by a constant value or noise)
during training to improve generalization.
**Note:** This layer is safe to use inside a `tf.data` or `grain` pipeline
(independently of which backend you're using).
References:
- [Random Erasing paper](https://arxiv.org/abs/1708.04896).
Args:
factor: A single float or a tuple of two floats.
`factor` controls the probability of applying the transformation.
- `factor=0.0` ensures no erasing is applied.
- `factor=1.0` means erasing is always applied.
- If a tuple `(min, max)` is provided, a probability value
is sampled between `min` and `max` for each image.
- If a single float is provided, a probability is sampled
between `0.0` and the given float.
Default is 1.0.
scale: A tuple of two floats representing the aspect ratio range of
the erased patch. This defines the width-to-height ratio of
the patch to be erased. It can help control the rw shape of
the erased region. Default is (0.02, 0.33).
fill_value: A value to fill the erased region with. This can be set to
a constant value or `None` to sample a random value
from a normal distribution. Default is `None`.
value_range: the range of values the incoming images will have.
Represented as a two-number tuple written `[low, high]`. This is
typically either `[0, 1]` or `[0, 255]` depending on how your
preprocessing pipeline is set up.
seed: Integer. Used to create a random seed.
"""
_USE_BASE_FACTOR = False
_FACTOR_BOUNDS = (0, 1)
def __init__(
self,
factor=1.0,
scale=(0.02, 0.33),
fill_value=None,
value_range=(0, 255),
seed=None,
data_format=None,
**kwargs,
):
super().__init__(data_format=data_format, **kwargs)
self._set_factor(factor)
self.scale = self._set_factor_by_name(scale, "scale")
self.fill_value = fill_value
self.value_range = value_range
self.seed = seed
self.generator = SeedGenerator(seed)
if self.data_format == "channels_first":
self.height_axis = -2
self.width_axis = -1
self.channel_axis = -3
else:
self.height_axis = -3
self.width_axis = -2
self.channel_axis = -1
def _set_factor_by_name(self, factor, name):
error_msg = (
f"The `{name}` argument should be a number "
"(or a list of two numbers) "
"in the range "
f"[{self._FACTOR_BOUNDS[0]}, {self._FACTOR_BOUNDS[1]}]. "
f"Received: factor={factor}"
)
if isinstance(factor, (tuple, list)):
if len(factor) != 2:
raise ValueError(error_msg)
if (
factor[0] > self._FACTOR_BOUNDS[1]
or factor[1] < self._FACTOR_BOUNDS[0]
):
raise ValueError(error_msg)
lower, upper = sorted(factor)
elif isinstance(factor, (int, float)):
if (
factor < self._FACTOR_BOUNDS[0]
or factor > self._FACTOR_BOUNDS[1]
):
raise ValueError(error_msg)
factor = abs(factor)
lower, upper = [max(-factor, self._FACTOR_BOUNDS[0]), factor]
else:
raise ValueError(error_msg)
return lower, upper
def _compute_crop_bounds(self, batch_size, image_length, crop_ratio, seed):
crop_length = self.backend.cast(
crop_ratio * image_length, dtype=self.compute_dtype
)
start_pos = self.backend.random.uniform(
shape=[batch_size],
minval=0,
maxval=1,
dtype=self.compute_dtype,
seed=seed,
) * (image_length - crop_length)
end_pos = start_pos + crop_length
return start_pos, end_pos
def _generate_batch_mask(self, images_shape, box_corners):
def _generate_grid_xy(image_height, image_width):
grid_y, grid_x = self.backend.numpy.meshgrid(
self.backend.numpy.arange(
image_height, dtype=self.compute_dtype
),
self.backend.numpy.arange(
image_width, dtype=self.compute_dtype
),
indexing="ij",
)
if self.data_format == "channels_last":
grid_y = self.backend.cast(
grid_y[None, :, :, None], dtype=self.compute_dtype
)
grid_x = self.backend.cast(
grid_x[None, :, :, None], dtype=self.compute_dtype
)
else:
grid_y = self.backend.cast(
grid_y[None, None, :, :], dtype=self.compute_dtype
)
grid_x = self.backend.cast(
grid_x[None, None, :, :], dtype=self.compute_dtype
)
return grid_x, grid_y
image_height, image_width = (
images_shape[self.height_axis],
images_shape[self.width_axis],
)
grid_x, grid_y = _generate_grid_xy(image_height, image_width)
x0, x1, y0, y1 = box_corners
x0 = x0[:, None, None, None]
y0 = y0[:, None, None, None]
x1 = x1[:, None, None, None]
y1 = y1[:, None, None, None]
batch_masks = (
(grid_x >= x0) & (grid_x < x1) & (grid_y >= y0) & (grid_y < y1)
)
batch_masks = self.backend.numpy.repeat(
batch_masks, images_shape[self.channel_axis], axis=self.channel_axis
)
return batch_masks
def _get_fill_value(self, images, images_shape, seed):
fill_value = self.fill_value
if fill_value is None:
fill_value = (
self.backend.random.normal(
images_shape,
dtype=self.compute_dtype,
seed=seed,
)
* self.value_range[1]
)
else:
error_msg = (
"The `fill_value` argument should be a number "
"(or a list of three numbers) "
)
if isinstance(fill_value, (tuple, list)):
if len(fill_value) != 3:
raise ValueError(error_msg)
fill_value = self.backend.numpy.full_like(
images, fill_value, dtype=self.compute_dtype
)
elif isinstance(fill_value, (int, float)):
fill_value = (
self.backend.numpy.ones(
images_shape, dtype=self.compute_dtype
)
* fill_value
)
else:
raise ValueError(error_msg)
fill_value = self.backend.numpy.clip(
fill_value, self.value_range[0], self.value_range[1]
)
return fill_value
def get_random_transformation(self, data, training=True, seed=None):
if not training:
return None
if isinstance(data, dict):
images = data["images"]
else:
images = data
images_shape = self.backend.shape(images)
rank = len(images_shape)
if rank == 3:
batch_size = 1
elif rank == 4:
batch_size = images_shape[0]
else:
raise ValueError(
"Expected the input image to be rank 3 or 4. Received "
f"inputs.shape={images_shape}"
)
image_height = images_shape[self.height_axis]
image_width = images_shape[self.width_axis]
seed = seed or self._get_seed_generator(self.backend._backend)
mix_weight = self.backend.random.uniform(
shape=(batch_size, 2),
minval=self.scale[0],
maxval=self.scale[1],
dtype=self.compute_dtype,
seed=seed,
)
mix_weight = self.backend.numpy.sqrt(mix_weight)
x0, x1 = self._compute_crop_bounds(
batch_size, image_width, mix_weight[:, 0], seed
)
y0, y1 = self._compute_crop_bounds(
batch_size, image_height, mix_weight[:, 1], seed
)
batch_masks = self._generate_batch_mask(
images_shape,
(x0, x1, y0, y1),
)
erase_probability = self.backend.random.uniform(
shape=(batch_size,),
minval=self.factor[0],
maxval=self.factor[1],
seed=seed,
)
random_threshold = self.backend.random.uniform(
shape=(batch_size,),
minval=0.0,
maxval=1.0,
seed=seed,
)
apply_erasing = random_threshold < erase_probability
fill_value = self._get_fill_value(images, images_shape, seed)
return {
"apply_erasing": apply_erasing,
"batch_masks": batch_masks,
"fill_value": fill_value,
}
def transform_images(self, images, transformation=None, training=True):
if training:
images = self.backend.cast(images, self.compute_dtype)
batch_masks = transformation["batch_masks"]
apply_erasing = transformation["apply_erasing"]
fill_value = transformation["fill_value"]
erased_images = self.backend.numpy.where(
batch_masks,
fill_value,
images,
)
images = self.backend.numpy.where(
apply_erasing[:, None, None, None],
erased_images,
images,
)
images = self.backend.cast(images, self.compute_dtype)
return images
def transform_labels(self, labels, transformation, training=True):
return labels
def transform_bounding_boxes(
self,
bounding_boxes,
transformation,
training=True,
):
return bounding_boxes
def transform_segmentation_masks(
self, segmentation_masks, transformation, training=True
):
return segmentation_masks
def compute_output_shape(self, input_shape):
return input_shape
def get_config(self):
config = {
"factor": self.factor,
"scale": self.scale,
"fill_value": self.fill_value,
"value_range": self.value_range,
"seed": self.seed,
}
base_config = super().get_config()
return {**base_config, **config}
| RandomErasing |
python | pypa__hatch | tests/backend/metadata/test_core.py | {
"start": 7034,
"end": 12164
} | class ____:
def test_dynamic(self, isolation):
metadata = ProjectMetadata(str(isolation), None, {"project": {"version": 9000, "dynamic": ["version"]}})
with pytest.raises(
ValueError,
match="Metadata field `version` cannot be both statically defined and listed in field `project.dynamic`",
):
_ = metadata.core.version
def test_static_missing(self, isolation):
metadata = ProjectMetadata(str(isolation), None, {"project": {}})
with pytest.raises(
ValueError,
match="Field `project.version` can only be resolved dynamically if `version` is in field `project.dynamic`",
):
_ = metadata.version
def test_static_not_string(self, isolation):
metadata = ProjectMetadata(str(isolation), None, {"project": {"version": 9000}})
with pytest.raises(TypeError, match="Field `project.version` must be a string"):
_ = metadata.version
def test_static_invalid(self, isolation):
metadata = ProjectMetadata(str(isolation), None, {"project": {"version": "0..0"}})
with pytest.raises(
ValueError,
match="Invalid version `0..0` from field `project.version`, see https://peps.python.org/pep-0440/",
):
_ = metadata.version
def test_static_normalization(self, isolation):
metadata = ProjectMetadata(str(isolation), None, {"project": {"version": "0.1.0.0-rc.1"}})
assert metadata.version == metadata.version == "0.1.0.0rc1"
assert metadata.core.version == metadata.core.version == "0.1.0.0-rc.1"
def test_dynamic_missing(self, isolation):
metadata = ProjectMetadata(str(isolation), None, {"project": {"dynamic": ["version"]}, "tool": {"hatch": {}}})
with pytest.raises(ValueError, match="Missing `tool.hatch.version` configuration"):
_ = metadata.version
def test_dynamic_not_table(self, isolation):
metadata = ProjectMetadata(
str(isolation), None, {"project": {"dynamic": ["version"]}, "tool": {"hatch": {"version": "1.0"}}}
)
with pytest.raises(TypeError, match="Field `tool.hatch.version` must be a table"):
_ = metadata.version
def test_dynamic_source_empty(self, isolation):
metadata = ProjectMetadata(
str(isolation), None, {"project": {"dynamic": ["version"]}, "tool": {"hatch": {"version": {"source": ""}}}}
)
with pytest.raises(
ValueError, match="The `source` option under the `tool.hatch.version` table must not be empty if defined"
):
_ = metadata.version.cached
def test_dynamic_source_not_string(self, isolation):
metadata = ProjectMetadata(
str(isolation), None, {"project": {"dynamic": ["version"]}, "tool": {"hatch": {"version": {"source": 42}}}}
)
with pytest.raises(TypeError, match="Field `tool.hatch.version.source` must be a string"):
_ = metadata.version.cached
def test_dynamic_unknown_source(self, isolation):
metadata = ProjectMetadata(
str(isolation),
PluginManager(),
{"project": {"dynamic": ["version"]}, "tool": {"hatch": {"version": {"source": "foo"}}}},
)
with pytest.raises(ValueError, match="Unknown version source: foo"):
_ = metadata.version.cached
def test_dynamic_source_regex(self, temp_dir):
metadata = ProjectMetadata(
str(temp_dir),
PluginManager(),
{"project": {"dynamic": ["version"]}, "tool": {"hatch": {"version": {"source": "regex", "path": "a/b"}}}},
)
file_path = temp_dir / "a" / "b"
file_path.ensure_parent_dir_exists()
file_path.write_text('__version__ = "0.0.1"')
assert metadata.hatch.version.source is metadata.hatch.version.source
assert isinstance(metadata.hatch.version.source, RegexSource)
assert metadata.hatch.version.cached == metadata.hatch.version.cached == "0.0.1"
def test_dynamic_source_regex_invalid(self, temp_dir):
metadata = ProjectMetadata(
str(temp_dir),
PluginManager(),
{"project": {"dynamic": ["version"]}, "tool": {"hatch": {"version": {"source": "regex", "path": "a/b"}}}},
)
file_path = temp_dir / "a" / "b"
file_path.ensure_parent_dir_exists()
file_path.write_text('__version__ = "0..0"')
with pytest.raises(
ValueError, match="Invalid version `0..0` from source `regex`, see https://peps.python.org/pep-0440/"
):
_ = metadata.version
def test_dynamic_error(self, isolation):
metadata = ProjectMetadata(
str(isolation),
PluginManager(),
{"project": {"dynamic": ["version"]}, "tool": {"hatch": {"version": {"source": "regex"}}}},
)
with pytest.raises(
ValueError, match="Error getting the version from source `regex`: option `path` must be specified"
):
_ = metadata.version.cached
| TestVersion |
python | matplotlib__matplotlib | lib/matplotlib/transforms.py | {
"start": 43498,
"end": 59113
} | class ____(TransformNode):
"""
The base class of all `TransformNode` instances that
actually perform a transformation.
All non-affine transformations should be subclasses of this class.
New affine transformations should be subclasses of `Affine2D`.
Subclasses of this class should override the following members (at
minimum):
- :attr:`input_dims`
- :attr:`output_dims`
- :meth:`transform`
- :meth:`inverted` (if an inverse exists)
The following attributes may be overridden if the default is unsuitable:
- :attr:`is_separable` (defaults to True for 1D -> 1D transforms, False
otherwise)
- :attr:`has_inverse` (defaults to True if :meth:`inverted` is overridden,
False otherwise)
If the transform needs to do something non-standard with
`matplotlib.path.Path` objects, such as adding curves
where there were once line segments, it should override:
- :meth:`transform_path`
"""
input_dims = None
"""
The number of input dimensions of this transform.
Must be overridden (with integers) in the subclass.
"""
output_dims = None
"""
The number of output dimensions of this transform.
Must be overridden (with integers) in the subclass.
"""
is_separable = False
"""True if this transform is separable in the x- and y- dimensions."""
has_inverse = False
"""True if this transform has a corresponding inverse transform."""
def __init_subclass__(cls):
# 1d transforms are always separable; we assume higher-dimensional ones
# are not but subclasses can also directly set is_separable -- this is
# verified by checking whether "is_separable" appears more than once in
# the class's MRO (it appears once in Transform).
if (sum("is_separable" in vars(parent) for parent in cls.__mro__) == 1
and cls.input_dims == cls.output_dims == 1):
cls.is_separable = True
# Transform.inverted raises NotImplementedError; we assume that if this
# is overridden then the transform is invertible but subclass can also
# directly set has_inverse.
if (sum("has_inverse" in vars(parent) for parent in cls.__mro__) == 1
and hasattr(cls, "inverted")
and cls.inverted is not Transform.inverted):
cls.has_inverse = True
def __add__(self, other):
"""
Compose two transforms together so that *self* is followed by *other*.
``A + B`` returns a transform ``C`` so that
``C.transform(x) == B.transform(A.transform(x))``.
"""
return (composite_transform_factory(self, other)
if isinstance(other, Transform) else
NotImplemented)
# Equality is based on object identity for `Transform`s (so we don't
# override `__eq__`), but some subclasses, such as TransformWrapper &
# AffineBase, override this behavior.
def _iter_break_from_left_to_right(self):
"""
Return an iterator breaking down this transform stack from left to
right recursively. If self == ((A, N), A) then the result will be an
iterator which yields I : ((A, N), A), followed by A : (N, A),
followed by (A, N) : (A), but not ((A, N), A) : I.
This is equivalent to flattening the stack then yielding
``flat_stack[:i], flat_stack[i:]`` where i=0..(n-1).
"""
yield IdentityTransform(), self
@property
def depth(self):
"""
Return the number of transforms which have been chained
together to form this Transform instance.
.. note::
For the special case of a Composite transform, the maximum depth
of the two is returned.
"""
return 1
def contains_branch(self, other):
"""
Return whether the given transform is a sub-tree of this transform.
This routine uses transform equality to identify sub-trees, therefore
in many situations it is object id which will be used.
For the case where the given transform represents the whole
of this transform, returns True.
"""
if self.depth < other.depth:
return False
# check that a subtree is equal to other (starting from self)
for _, sub_tree in self._iter_break_from_left_to_right():
if sub_tree == other:
return True
return False
def contains_branch_separately(self, other_transform):
"""
Return whether the given branch is a sub-tree of this transform on
each separate dimension.
A common use for this method is to identify if a transform is a blended
transform containing an Axes' data transform. e.g.::
x_isdata, y_isdata = trans.contains_branch_separately(ax.transData)
"""
if self.output_dims != 2:
raise ValueError('contains_branch_separately only supports '
'transforms with 2 output dimensions')
# for a non-blended transform each separate dimension is the same, so
# just return the appropriate shape.
return (self.contains_branch(other_transform), ) * 2
# Permanent alias for backwards compatibility (historical typo)
def contains_branch_seperately(self, other_transform):
""":meta private:"""
return self.contains_branch_separately(other_transform)
def __sub__(self, other):
"""
Compose *self* with the inverse of *other*, cancelling identical terms
if any::
# In general:
A - B == A + B.inverted()
# (but see note regarding frozen transforms below).
# If A "ends with" B (i.e. A == A' + B for some A') we can cancel
# out B:
(A' + B) - B == A'
# Likewise, if B "starts with" A (B = A + B'), we can cancel out A:
A - (A + B') == B'.inverted() == B'^-1
Cancellation (rather than naively returning ``A + B.inverted()``) is
important for multiple reasons:
- It avoids floating-point inaccuracies when computing the inverse of
B: ``B - B`` is guaranteed to cancel out exactly (resulting in the
identity transform), whereas ``B + B.inverted()`` may differ by a
small epsilon.
- ``B.inverted()`` always returns a frozen transform: if one computes
``A + B + B.inverted()`` and later mutates ``B``, then
``B.inverted()`` won't be updated and the last two terms won't cancel
out anymore; on the other hand, ``A + B - B`` will always be equal to
``A`` even if ``B`` is mutated.
"""
# we only know how to do this operation if other is a Transform.
if not isinstance(other, Transform):
return NotImplemented
for remainder, sub_tree in self._iter_break_from_left_to_right():
if sub_tree == other:
return remainder
for remainder, sub_tree in other._iter_break_from_left_to_right():
if sub_tree == self:
if not remainder.has_inverse:
raise ValueError(
"The shortcut cannot be computed since 'other' "
"includes a non-invertible component")
return remainder.inverted()
# if we have got this far, then there was no shortcut possible
if other.has_inverse:
return self + other.inverted()
else:
raise ValueError('It is not possible to compute transA - transB '
'since transB cannot be inverted and there is no '
'shortcut possible.')
def __array__(self, *args, **kwargs):
"""Array interface to get at this Transform's affine matrix."""
return self.get_affine().get_matrix()
def transform(self, values):
"""
Apply this transformation on the given array of *values*.
Parameters
----------
values : array-like
The input values as an array of length :attr:`~Transform.input_dims` or
shape (N, :attr:`~Transform.input_dims`).
Returns
-------
array
The output values as an array of length :attr:`~Transform.output_dims` or
shape (N, :attr:`~Transform.output_dims`), depending on the input.
"""
# Ensure that values is a 2d array (but remember whether
# we started with a 1d or 2d array).
values = np.asanyarray(values)
ndim = values.ndim
values = values.reshape((-1, self.input_dims))
# Transform the values
res = self.transform_affine(self.transform_non_affine(values))
# Convert the result back to the shape of the input values.
if ndim == 0:
assert not np.ma.is_masked(res) # just to be on the safe side
return res[0, 0]
if ndim == 1:
return res.reshape(-1)
elif ndim == 2:
return res
raise ValueError(
"Input values must have shape (N, {dims}) or ({dims},)"
.format(dims=self.input_dims))
def transform_affine(self, values):
"""
Apply only the affine part of this transformation on the
given array of values.
``transform(values)`` is always equivalent to
``transform_affine(transform_non_affine(values))``.
In non-affine transformations, this is generally a no-op. In
affine transformations, this is equivalent to
``transform(values)``.
Parameters
----------
values : array
The input values as an array of length :attr:`~Transform.input_dims` or
shape (N, :attr:`~Transform.input_dims`).
Returns
-------
array
The output values as an array of length :attr:`~Transform.output_dims` or
shape (N, :attr:`~Transform.output_dims`), depending on the input.
"""
return self.get_affine().transform(values)
def transform_non_affine(self, values):
"""
Apply only the non-affine part of this transformation.
``transform(values)`` is always equivalent to
``transform_affine(transform_non_affine(values))``.
In non-affine transformations, this is generally equivalent to
``transform(values)``. In affine transformations, this is
always a no-op.
Parameters
----------
values : array
The input values as an array of length
:attr:`~matplotlib.transforms.Transform.input_dims` or
shape (N, :attr:`~matplotlib.transforms.Transform.input_dims`).
Returns
-------
array
The output values as an array of length
:attr:`~matplotlib.transforms.Transform.output_dims` or shape
(N, :attr:`~matplotlib.transforms.Transform.output_dims`),
depending on the input.
"""
return values
def transform_bbox(self, bbox):
"""
Transform the given bounding box.
For smarter transforms including caching (a common requirement in
Matplotlib), see `TransformedBbox`.
"""
return Bbox(self.transform(bbox.get_points()))
def get_affine(self):
"""Get the affine part of this transform."""
return IdentityTransform()
def get_matrix(self):
"""Get the matrix for the affine part of this transform."""
return self.get_affine().get_matrix()
def transform_point(self, point):
"""
Return a transformed point.
This function is only kept for backcompatibility; the more general
`.transform` method is capable of transforming both a list of points
and a single point.
The point is given as a sequence of length :attr:`input_dims`.
The transformed point is returned as a sequence of length
:attr:`output_dims`.
"""
if len(point) != self.input_dims:
raise ValueError("The length of 'point' must be 'self.input_dims'")
return self.transform(point)
def transform_path(self, path):
"""
Apply the transform to `.Path` *path*, returning a new `.Path`.
In some cases, this transform may insert curves into the path
that began as line segments.
"""
return self.transform_path_affine(self.transform_path_non_affine(path))
def transform_path_affine(self, path):
"""
Apply the affine part of this transform to `.Path` *path*, returning a
new `.Path`.
``transform_path(path)`` is equivalent to
``transform_path_affine(transform_path_non_affine(values))``.
"""
return self.get_affine().transform_path_affine(path)
def transform_path_non_affine(self, path):
"""
Apply the non-affine part of this transform to `.Path` *path*,
returning a new `.Path`.
``transform_path(path)`` is equivalent to
``transform_path_affine(transform_path_non_affine(values))``.
"""
x = self.transform_non_affine(path.vertices)
return Path._fast_from_codes_and_verts(x, path.codes, path)
def transform_angles(self, angles, pts, radians=False, pushoff=1e-5):
"""
Transform a set of angles anchored at specific locations.
Parameters
----------
angles : (N,) array-like
The angles to transform.
pts : (N, 2) array-like
The points where the angles are anchored.
radians : bool, default: False
Whether *angles* are radians or degrees.
pushoff : float
For each point in *pts* and angle in *angles*, the transformed
angle is computed by transforming a segment of length *pushoff*
starting at that point and making that angle relative to the
horizontal axis, and measuring the angle between the horizontal
axis and the transformed segment.
Returns
-------
(N,) array
"""
# Must be 2D
if self.input_dims != 2 or self.output_dims != 2:
raise NotImplementedError('Only defined in 2D')
angles = np.asarray(angles)
pts = np.asarray(pts)
_api.check_shape((None, 2), pts=pts)
_api.check_shape((None,), angles=angles)
if len(angles) != len(pts):
raise ValueError("There must be as many 'angles' as 'pts'")
# Convert to radians if desired
if not radians:
angles = np.deg2rad(angles)
# Move a short distance away
pts2 = pts + pushoff * np.column_stack([np.cos(angles),
np.sin(angles)])
# Transform both sets of points
tpts = self.transform(pts)
tpts2 = self.transform(pts2)
# Calculate transformed angles
d = tpts2 - tpts
a = np.arctan2(d[:, 1], d[:, 0])
# Convert back to degrees if desired
if not radians:
a = np.rad2deg(a)
return a
def inverted(self):
"""
Return the corresponding inverse transformation.
It holds ``x == self.inverted().transform(self.transform(x))``.
The return value of this method should be treated as
temporary. An update to *self* does not cause a corresponding
update to its inverted copy.
"""
raise NotImplementedError()
| Transform |
python | docker__docker-py | tests/unit/fake_api_client.py | {
"start": 135,
"end": 2496
} | class ____(mock.MagicMock):
"""
A MagicMock which deep copies every return value.
"""
def _mock_call(self, *args, **kwargs):
ret = super()._mock_call(*args, **kwargs)
if isinstance(ret, (dict, list)):
ret = copy.deepcopy(ret)
return ret
def make_fake_api_client(overrides=None):
"""
Returns non-complete fake APIClient.
This returns most of the default cases correctly, but most arguments that
change behaviour will not work.
"""
if overrides is None:
overrides = {}
api_client = docker.APIClient(version=DEFAULT_DOCKER_API_VERSION)
mock_attrs = {
'build.return_value': fake_api.FAKE_IMAGE_ID,
'commit.return_value': fake_api.post_fake_commit()[1],
'containers.return_value': fake_api.get_fake_containers()[1],
'create_container.return_value':
fake_api.post_fake_create_container()[1],
'create_host_config.side_effect': api_client.create_host_config,
'create_network.return_value': fake_api.post_fake_network()[1],
'create_secret.return_value': fake_api.post_fake_secret()[1],
'create_config.return_value': fake_api.post_fake_config()[1],
'exec_create.return_value': fake_api.post_fake_exec_create()[1],
'exec_start.return_value': fake_api.post_fake_exec_start()[1],
'images.return_value': fake_api.get_fake_images()[1],
'inspect_container.return_value':
fake_api.get_fake_inspect_container()[1],
'inspect_image.return_value': fake_api.get_fake_inspect_image()[1],
'inspect_network.return_value': fake_api.get_fake_network()[1],
'logs.return_value': [b'hello world\n'],
'networks.return_value': fake_api.get_fake_network_list()[1],
'start.return_value': None,
'wait.return_value': {'StatusCode': 0},
'version.return_value': fake_api.get_fake_version()
}
mock_attrs.update(overrides)
mock_client = CopyReturnMagicMock(**mock_attrs)
mock_client._version = docker.constants.DEFAULT_DOCKER_API_VERSION
return mock_client
def make_fake_client(overrides=None):
"""
Returns a Client with a fake APIClient.
"""
client = docker.DockerClient(version=DEFAULT_DOCKER_API_VERSION)
client.api = make_fake_api_client(overrides)
return client
| CopyReturnMagicMock |
python | pypa__setuptools | pkg_resources/__init__.py | {
"start": 76671,
"end": 80748
} | class ____(ZipProvider):
"""Metadata provider for .egg files"""
def __init__(self, importer: zipimport.zipimporter) -> None:
"""Create a metadata provider from a zipimporter"""
self.zip_pre = importer.archive + os.sep
self.loader = importer
if importer.prefix:
self.module_path = os.path.join(importer.archive, importer.prefix)
else:
self.module_path = importer.archive
self._setup_prefix()
_distribution_finders: dict[type, _DistFinderType[Any]] = _declare_state(
'dict', '_distribution_finders', {}
)
def register_finder(
importer_type: type[_T], distribution_finder: _DistFinderType[_T]
) -> None:
"""Register `distribution_finder` to find distributions in sys.path items
`importer_type` is the type or class of a PEP 302 "Importer" (sys.path item
handler), and `distribution_finder` is a callable that, passed a path
item and the importer instance, yields ``Distribution`` instances found on
that path item. See ``pkg_resources.find_on_path`` for an example."""
_distribution_finders[importer_type] = distribution_finder
def find_distributions(path_item: str, only: bool = False) -> Iterable[Distribution]:
"""Yield distributions accessible via `path_item`"""
importer = get_importer(path_item)
finder = _find_adapter(_distribution_finders, importer)
return finder(importer, path_item, only)
def find_eggs_in_zip(
importer: zipimport.zipimporter, path_item: str, only: bool = False
) -> Iterator[Distribution]:
"""
Find eggs in zip files; possibly multiple nested eggs.
"""
if importer.archive.endswith('.whl'):
# wheels are not supported with this finder
# they don't have PKG-INFO metadata, and won't ever contain eggs
return
metadata = EggMetadata(importer)
if metadata.has_metadata('PKG-INFO'):
yield Distribution.from_filename(path_item, metadata=metadata)
if only:
# don't yield nested distros
return
for subitem in metadata.resource_listdir(''):
if _is_egg_path(subitem):
subpath = os.path.join(path_item, subitem)
dists = find_eggs_in_zip(zipimport.zipimporter(subpath), subpath)
yield from dists
elif subitem.lower().endswith(('.dist-info', '.egg-info')):
subpath = os.path.join(path_item, subitem)
submeta = EggMetadata(zipimport.zipimporter(subpath))
submeta.egg_info = subpath
yield Distribution.from_location(path_item, subitem, submeta)
register_finder(zipimport.zipimporter, find_eggs_in_zip)
def find_nothing(
importer: object | None, path_item: str | None, only: bool | None = False
):
return ()
register_finder(object, find_nothing)
def find_on_path(importer: object | None, path_item, only=False):
"""Yield distributions accessible on a sys.path directory"""
path_item = _normalize_cached(path_item)
if _is_unpacked_egg(path_item):
yield Distribution.from_filename(
path_item,
metadata=PathMetadata(path_item, os.path.join(path_item, 'EGG-INFO')),
)
return
entries = (os.path.join(path_item, child) for child in safe_listdir(path_item))
# scan for .egg and .egg-info in directory
for entry in sorted(entries):
fullpath = os.path.join(path_item, entry)
factory = dist_factory(path_item, entry, only)
yield from factory(fullpath)
def dist_factory(path_item, entry, only):
"""Return a dist_factory for the given entry."""
lower = entry.lower()
is_egg_info = lower.endswith('.egg-info')
is_dist_info = lower.endswith('.dist-info') and os.path.isdir(
os.path.join(path_item, entry)
)
is_meta = is_egg_info or is_dist_info
return (
distributions_from_metadata
if is_meta
else find_distributions
if not only and _is_egg_path(entry)
else resolve_egg_link
if not only and lower.endswith('.egg-link')
else NoDists()
)
| EggMetadata |
python | pypa__hatch | src/hatch/python/core.py | {
"start": 350,
"end": 1285
} | class ____:
def __init__(self, path: Path, distribution: Distribution, metadata: dict[str, Any]) -> None:
self.__path = path
self.__current_dist = distribution
self.__metadata = metadata
@property
def path(self) -> Path:
return self.__path
@property
def name(self) -> str:
return self.__current_dist.name
@property
def python_path(self) -> Path:
return self.path / self.__current_dist.python_path
@property
def version(self) -> str:
return self.__current_dist.version.base_version
@property
def metadata(self) -> dict[str, Any]:
return self.__metadata
def needs_update(self) -> bool:
new_dist = get_distribution(self.__current_dist.name)
return new_dist.version > self.__current_dist.version
@classmethod
def metadata_filename(cls) -> str:
return "hatch-dist.json"
| InstalledDistribution |
python | pyqtgraph__pyqtgraph | pyqtgraph/graphicsItems/ButtonItem.py | {
"start": 100,
"end": 1813
} | class ____(GraphicsObject):
"""Button graphicsItem displaying an image."""
clicked = QtCore.Signal(object)
def __init__(self, imageFile=None, width=None, parentItem=None, pixmap=None):
self.enabled = True
GraphicsObject.__init__(self)
if imageFile is not None:
self.setImageFile(imageFile)
elif pixmap is not None:
self.setPixmap(pixmap)
self._width = width
if self._width is None:
self._width = self.pixmap.width() / self.pixmap.devicePixelRatio()
if parentItem is not None:
self.setParentItem(parentItem)
self.setOpacity(0.7)
def setImageFile(self, imageFile):
self.setPixmap(QtGui.QPixmap(imageFile))
def setPixmap(self, pixmap):
self.pixmap = pixmap
self.update()
def mouseClickEvent(self, ev):
if self.enabled:
self.clicked.emit(self)
def hoverEvent(self, ev):
if not self.enabled:
return
if ev.isEnter():
self.setOpacity(1.0)
elif ev.isExit():
self.setOpacity(0.7)
def disable(self):
self.enabled = False
self.setOpacity(0.4)
def enable(self):
self.enabled = True
self.setOpacity(0.7)
def paint(self, p, *args):
p.setRenderHint(p.RenderHint.Antialiasing)
tgtRect = QtCore.QRectF(0, 0, self._width, self._width)
srcRect = QtCore.QRectF(self.pixmap.rect())
p.drawPixmap(tgtRect, self.pixmap, srcRect)
def boundingRect(self):
return QtCore.QRectF(0, 0, self._width, self._width)
| ButtonItem |
python | PrefectHQ__prefect | tests/cli/test_work_queues.py | {
"start": 5315,
"end": 8016
} | class ____:
async def test_clear_concurrency_limit(self, prefect_client, work_queue):
await run_sync_in_worker_thread(
invoke_and_assert,
command=f"work-queue set-concurrency-limit {work_queue.name} 5",
)
await run_sync_in_worker_thread(
invoke_and_assert,
command=f"work-queue clear-concurrency-limit {work_queue.name}",
expected_code=0,
)
q = await read_queue(prefect_client, work_queue.name)
assert q.concurrency_limit is None
async def test_clear_concurrency_limit_by_id(self, prefect_client, work_queue):
await run_sync_in_worker_thread(
invoke_and_assert,
command=f"work-queue set-concurrency-limit {work_queue.name} 5",
)
await run_sync_in_worker_thread(
invoke_and_assert,
command=f"work-queue clear-concurrency-limit {work_queue.id}",
expected_code=0,
)
q = await read_queue(prefect_client, work_queue.name)
assert q.concurrency_limit is None
async def test_clear_concurrency_limit_with_pool(
self,
prefect_client,
work_queue_1,
):
pool_name = work_queue_1.work_pool.name
await prefect_client.update_work_queue(id=work_queue_1.id, concurrency_limit=5)
work_pool_queue = await read_queue(
prefect_client,
name=work_queue_1.name,
pool=pool_name,
)
assert work_pool_queue.concurrency_limit == 5
cmd = (
f"work-queue clear-concurrency-limit {work_pool_queue.name} -p {pool_name}"
)
await run_sync_in_worker_thread(
invoke_and_assert,
command=cmd,
expected_code=0,
)
q = await read_queue(prefect_client, work_queue_1.name, pool=pool_name)
assert q.concurrency_limit is None
# Tests for all of the above, but with bad inputs
def test_clear_concurrency_limit_bad_queue_name(self):
invoke_and_assert(
command="work-queue clear-concurrency-limit bad-name",
expected_code=1,
)
def test_clear_concurrency_limit_bad_queue_id(self):
invoke_and_assert(
command=(
"work-queue clear-concurrency-limit"
" 00000000-0000-0000-0000-000000000000"
),
expected_code=1,
)
def test_clear_concurrency_limit_bad_pool_name(
self,
work_queue,
):
invoke_and_assert(
command=f"work-queue clear-concurrency-limit {work_queue.name} -p bad-pool",
expected_code=1,
)
| TestClearConcurrencyLimit |
python | getsentry__sentry | tests/sentry/notifications/platform/test_target.py | {
"start": 1745,
"end": 4877
} | class ____(TestCase):
def test_prepare_targets_invalid_integration(self) -> None:
self.create_integration(
organization=self.organization, provider="slack", external_id="ext-123"
)
integration_target = IntegrationNotificationTarget(
provider_key=NotificationProviderKey.SLACK,
resource_type=NotificationTargetResourceType.CHANNEL,
resource_id="C01234567890",
integration_id=99999,
organization_id=self.organization.id,
)
with pytest.raises(NotificationTargetError, match="Integration 99999 not found"):
PreparedIntegrationNotificationTarget[SlackIntegration](
target=integration_target,
installation_cls=SlackIntegration,
).integration
def test_prepare_targets_invalid_organization_integration(self) -> None:
self.create_integration(
organization=self.organization, provider="slack", external_id="ext-123"
)
integration_target = IntegrationNotificationTarget(
provider_key=NotificationProviderKey.SLACK,
resource_type=NotificationTargetResourceType.CHANNEL,
resource_id="C01234567890",
integration_id=self.integration.id,
organization_id=self.organization.id,
)
with assume_test_silo_mode(SiloMode.CONTROL):
organization_integration = OrganizationIntegration.objects.get(
integration_id=self.integration.id,
organization_id=self.organization.id,
)
organization_integration.delete()
with pytest.raises(
NotificationTargetError,
match=f"Organization integration for integration {self.integration.id} and organization {self.organization.id} not found",
):
PreparedIntegrationNotificationTarget[SlackIntegration](
target=integration_target,
installation_cls=SlackIntegration,
).organization_integration
@patch("sentry.integrations.slack.integration.SlackSdkClient.chat_postMessage")
def test_prepare_targets_valid_installation_cls(self, mock_slack_client: MagicMock) -> None:
integration_target = IntegrationNotificationTarget(
provider_key=NotificationProviderKey.SLACK,
resource_type=NotificationTargetResourceType.CHANNEL,
resource_id="C01234567890",
integration_id=self.integration.id,
organization_id=self.organization.id,
)
prepared_integration_target = PreparedIntegrationNotificationTarget[SlackIntegration](
target=integration_target,
installation_cls=SlackIntegration,
)
assert prepared_integration_target.integration_installation is not None
prepared_integration_target.integration_installation.send_message(
channel_id="C01234567890",
message="Hello, world!",
)
mock_slack_client.assert_called_once_with(channel="C01234567890", text="Hello, world!")
| PreparedIntegrationNotificationTargetTest |
python | mahmoud__boltons | tests/test_funcutils.py | {
"start": 284,
"end": 655
} | class ____:
def __init__(self, greeting):
self.greeting = greeting
def greet(self, excitement='.'):
return self.greeting.capitalize() + excitement
partial_greet = InstancePartial(greet, excitement='!')
cached_partial_greet = CachedInstancePartial(greet, excitement='...')
def native_greet(self):
return self.greet(';')
| Greeter |
python | falconry__falcon | falcon/media/base.py | {
"start": 7938,
"end": 9262
} | class ____(metaclass=abc.ABCMeta):
"""Abstract Base Class for a WebSocket BINARY media handler."""
def serialize(self, media: object) -> bytes | bytearray | memoryview:
"""Serialize the media object to a byte string.
By default, this method raises an instance of
:class:`NotImplementedError`. Therefore, it must be
overridden if the child class wishes to support
serialization to BINARY (0x02) message payloads.
Args:
media (object): A serializable object.
Returns:
bytes: The resulting serialized byte string from the input
object. May be an instance of :class:`bytes`,
:class:`bytearray`, or :class:`memoryview`.
"""
raise NotImplementedError()
def deserialize(self, payload: bytes) -> object:
"""Deserialize BINARY payloads from a byte string.
By default, this method raises an instance of
:class:`NotImplementedError`. Therefore, it must be
overridden if the child class wishes to support
deserialization from BINARY (0x02) message payloads.
Args:
payload (bytes): Message payload to deserialize.
Returns:
object: A deserialized object.
"""
raise NotImplementedError()
| BinaryBaseHandlerWS |
python | doocs__leetcode | solution/3200-3299/3248.Snake in Matrix/Solution.py | {
"start": 0,
"end": 394
} | class ____:
def finalPositionOfSnake(self, n: int, commands: List[str]) -> int:
x = y = 0
for c in commands:
match c[0]:
case "U":
x -= 1
case "D":
x += 1
case "L":
y -= 1
case "R":
y += 1
return x * n + y
| Solution |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/subprocess_env_manager.py | {
"start": 1981,
"end": 2126
} | class ____(NamedTuple):
all_step_result: AllStepResult
timer_root: Optional[TimerNode]
environment_stats: EnvironmentStats
| StepResponse |
python | pytorch__pytorch | torch/optim/lr_scheduler.py | {
"start": 47074,
"end": 50777
} | class ____(LRScheduler):
"""Decays the learning rate of each parameter group using a polynomial function in the given total_iters.
When last_epoch=-1, sets initial lr as lr.
Args:
optimizer (Optimizer): Wrapped optimizer.
total_iters (int): The number of steps that the scheduler decays the learning rate. Default: 5.
power (float): The power of the polynomial. Default: 1.0.
Example:
>>> # xdoctest: +SKIP("undefined vars")
>>> # Assuming optimizer uses lr = 0.05 for all groups
>>> # lr = 0.0490 if epoch == 0
>>> # lr = 0.0481 if epoch == 1
>>> # lr = 0.0472 if epoch == 2
>>> # ...
>>> # lr = 0.0 if epoch >= 50
>>> scheduler = PolynomialLR(optimizer, total_iters=50, power=0.9)
>>> for epoch in range(100):
>>> train(...)
>>> validate(...)
>>> scheduler.step()
.. image:: ../scripts/lr_scheduler_images/PolynomialLR.png
"""
def __init__(
self,
optimizer: Optimizer,
total_iters: int = 5,
power: float = 1.0,
last_epoch: int = -1,
) -> None: # noqa: D107
self.total_iters = total_iters
self.power = power
super().__init__(optimizer, last_epoch)
@override
def get_lr(self) -> list[float | Tensor]:
r"""Compute the next learning rate for each of the optimizer's
:attr:`~torch.optim.Optimizer.param_groups`.
Scales the ``group["lr"]``\s in the optimizer's
:attr:`~torch.optim.Optimizer.param_groups` such that the learning rates
follow
.. math::
\texttt{base\_lr} \cdot \left(1 - \frac{\texttt{last\_epoch}}
{\texttt{total\_iters}} \right)^\texttt{power}
Returns the current learning rates unchanged after :attr:`total_iters`
is reached.
Returns:
list[float | Tensor]: A :class:`list` of learning rates for each of
the optimizer's :attr:`~torch.optim.Optimizer.param_groups` with the
same types as their current ``group["lr"]``\s.
.. note::
If you're trying to inspect the most recent learning rate, use
:meth:`get_last_lr()` instead.
.. note::
The returned :class:`~torch.Tensor`\s are copies, and never alias
the optimizer's ``group["lr"]``\s.
"""
_warn_get_lr_called_within_step(self)
if self._is_initial or self.last_epoch > self.total_iters:
return _param_groups_val_list(self.optimizer, "lr")
decay_factor = (
(1.0 - self.last_epoch / self.total_iters)
/ (1.0 - (self.last_epoch - 1) / self.total_iters)
) ** self.power
return [group["lr"] * decay_factor for group in self.optimizer.param_groups]
def _get_closed_form_lr(self) -> list[float | Tensor]:
r"""Compute learning rates for each of the optimizer's
:attr:`~torch.optim.Optimizer.param_groups` at :attr:`last_epoch` using
a closed-form formula.
Uses :attr:`base_lrs` to compute learning rates. This method is called
when an epoch is passed to :meth:`step`.
Returns:
list[float | Tensor]: A :class:`list` of learning rates for each of
the optimizer's :attr:`~torch.optim.Optimizer.param_groups` with the
same types as their current ``group["lr"]``\s.
"""
return [
(
base_lr
* (1.0 - min(self.total_iters, self.last_epoch) / self.total_iters)
** self.power
)
for base_lr in self.base_lrs
]
| PolynomialLR |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 16281,
"end": 16561
} | class ____(ChainedSource):
def reconstruct(self, codegen: "PyCodegen") -> None:
self.base.reconstruct(codegen)
def guard_source(self) -> GuardSource:
return self.base.guard_source()
def name(self) -> str:
return self.base.name()
| SkipGuardSource |
python | ipython__ipython | IPython/extensions/tests/test_deduperreload.py | {
"start": 545,
"end": 2261
} | class ____(DeduperReloader):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.exceptions_raised: list[Exception] = []
def _patch_namespace(
self, module: ModuleType | type, prefixes: list[str] | None = None
) -> bool:
try:
assert super()._patch_namespace(module, prefixes)
return True
except Exception as e:
self.exceptions_raised.append(e)
return False
def is_nonempty_file(fname: str) -> bool:
return len(fname) > 0
def squish_text(text: str) -> str:
"""
Turns text like this:
''' def foo():
return "bar"
def baz():
return "bat"
def bam():
return "bat"
'''
into this:
'''def foo():
return "bar"
def baz():
return "bat"
def bam():
return "bat"
'''
The former is common when we are trying to use string templates
whose parameters are multiline and unaware of the existing indentation.
:param text: a string with messed up indentation
:return: `text` but with indentation fixed
"""
prev_indentation = 0
transformed_text_lines = []
for line in text.strip("\n").splitlines():
line_without_indentation = line.lstrip()
indentation = len(line) - len(line_without_indentation)
if indentation == 0:
indentation = prev_indentation
else:
prev_indentation = indentation
transformed_text_lines.append(
textwrap.indent(line_without_indentation, " " * indentation)
)
return textwrap.dedent("\n".join(transformed_text_lines))
| DeduperTestReloader |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/partition_keys.py | {
"start": 539,
"end": 769
} | class ____(graphene.ObjectType):
message = graphene.NonNull(graphene.String)
class Meta:
interfaces = (GrapheneError,)
name = "PartitionSubsetDeserializationError"
| GraphenePartitionSubsetDeserializationError |
python | Textualize__textual | docs/examples/styles/padding_all.py | {
"start": 106,
"end": 703
} | class ____(App):
CSS_PATH = "padding_all.tcss"
def compose(self):
yield Grid(
Placeholder("no padding", id="p1"),
Placeholder("padding: 1", id="p2"),
Placeholder("padding: 1 5", id="p3"),
Placeholder("padding: 1 1 2 6", id="p4"),
Placeholder("padding-top: 4", id="p5"),
Placeholder("padding-right: 3", id="p6"),
Placeholder("padding-bottom: 4", id="p7"),
Placeholder("padding-left: 3", id="p8"),
)
if __name__ == "__main__":
app = PaddingAllApp()
app.run()
| PaddingAllApp |
python | bokeh__bokeh | src/bokeh/models/annotations/dimensional.py | {
"start": 5705,
"end": 6695
} | class ____(CustomDimensional):
""" Units of angular measurement.
"""
# explicit __init__ to support Init signatures
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
basis = Override(default={
"°": (1, "^\\circ", "degree"),
"'": (1/60, "^\\prime", "minute"),
"''": (1/3600, "^{\\prime\\prime}", "second"),
})
ticks = Override(default=[1, 3, 6, 12, 60, 120, 240, 360])
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| Angular |
python | pypa__pip | tests/unit/test_options.py | {
"start": 19673,
"end": 21196
} | class ____:
def test_venv_config_file_found(self, monkeypatch: pytest.MonkeyPatch) -> None:
# strict limit on the global config files list
monkeypatch.setattr(
pip._internal.utils.appdirs, "site_config_dirs", lambda _: ["/a/place"]
)
cp = pip._internal.configuration.Configuration(isolated=False)
files = []
for _, val in cp.iter_config_files():
files.extend(val)
assert len(files) == 4
@pytest.mark.parametrize(
"args, expect",
[
([], None),
(["--global"], "global"),
(["--site"], "site"),
(["--user"], "user"),
(["--global", "--user"], PipError),
(["--global", "--site"], PipError),
(["--global", "--site", "--user"], PipError),
],
)
def test_config_file_options(
self,
monkeypatch: pytest.MonkeyPatch,
args: list[str],
expect: None | str | type[PipError],
) -> None:
cmd = cast(ConfigurationCommand, create_command("config"))
# Replace a handler with a no-op to avoid side effects
monkeypatch.setattr(cmd, "get_name", lambda *a: None)
options, args = cmd.parser.parse_args(args + ["get", "name"])
if expect is PipError:
with pytest.raises(PipError):
cmd._determine_file(options, need_value=False)
else:
assert expect == cmd._determine_file(options, need_value=False)
| TestOptionsConfigFiles |
python | Netflix__metaflow | metaflow/metaflow_environment.py | {
"start": 363,
"end": 461
} | class ____(MetaflowException):
headline = "Incompatible environment"
| InvalidEnvironmentException |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constrainedTypeVar18.py | {
"start": 479,
"end": 782
} | class ____(Generic[T2]):
def __init__(self, client: T2):
self._client = client
def method1(self):
return self._client.fn(7)
a1 = A(Async())
r1 = a1.method1()
reveal_type(r1, expected_text="Awaitable[int]*")
a2 = A(Sync())
r2 = a2.method1()
reveal_type(r2, expected_text="int*")
| A |
python | getsentry__sentry | src/sentry/integrations/messaging/metrics.py | {
"start": 2745,
"end": 3151
} | class ____(StrEnum):
"""Common reasons why a messaging command may halt without success/failure."""
# Identity Linking
ALREADY_LINKED = "already_linked"
NOT_LINKED = "not_linked"
# Team Linking
LINK_FROM_CHANNEL = "link_from_channel"
LINK_USER_FIRST = "link_user_first"
TEAM_NOT_LINKED = "team_not_linked"
INSUFFICIENT_ROLE = "insufficient_role"
| MessageCommandHaltReason |
python | tensorflow__tensorflow | tensorflow/python/framework/test_util_test.py | {
"start": 42256,
"end": 43110
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
@parameterized.named_parameters(
[("_RunEagerly", True), ("_RunGraph", False)])
def test_run_functions_eagerly(self, run_eagerly): # pylint: disable=g-wrong-blank-lines
results = []
@def_function.function
def add_two(x):
for _ in range(5):
x += 2
results.append(x)
return x
with test_util.run_functions_eagerly(run_eagerly):
add_two(constant_op.constant(2.))
if context.executing_eagerly():
if run_eagerly:
self.assertTrue(isinstance(t, ops.EagerTensor) for t in results)
else:
self.assertTrue(isinstance(t, tensor.Tensor) for t in results)
else:
self.assertTrue(isinstance(t, tensor.Tensor) for t in results)
| RunFunctionsEagerlyInV2Test |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/actions.py | {
"start": 786,
"end": 1104
} | class ____(CompositeAction):
"""Composite action parser for the controller when delegation is supported."""
def create_parser(self) -> NamespaceParser:
"""Return a namespace parser to parse the argument associated with this action."""
return DelegatedControllerParser()
| DelegatedControllerAction |
python | langchain-ai__langchain | libs/langchain/langchain_classic/output_parsers/regex_dict.py | {
"start": 108,
"end": 1626
} | class ____(BaseOutputParser[dict[str, str]]):
"""Parse the output of an LLM call into a Dictionary using a regex."""
regex_pattern: str = r"{}:\s?([^.'\n']*)\.?"
"""The regex pattern to use to parse the output."""
output_key_to_format: dict[str, str]
"""The keys to use for the output."""
no_update_value: str | None = None
"""The default key to use for the output."""
@property
def _type(self) -> str:
"""Return the type key."""
return "regex_dict_parser"
def parse(self, text: str) -> dict[str, str]:
"""Parse the output of an LLM call."""
result = {}
for output_key, expected_format in self.output_key_to_format.items():
specific_regex = self.regex_pattern.format(re.escape(expected_format))
matches = re.findall(specific_regex, text)
if not matches:
msg = (
f"No match found for output key: {output_key} with expected format \
{expected_format} on text {text}"
)
raise ValueError(msg)
if len(matches) > 1:
msg = f"Multiple matches found for output key: {output_key} with \
expected format {expected_format} on text {text}"
raise ValueError(msg)
if self.no_update_value is not None and matches[0] == self.no_update_value:
continue
result[output_key] = matches[0]
return result
| RegexDictParser |
python | getsentry__sentry | src/sentry/issues/endpoints/group_events.py | {
"start": 1938,
"end": 6739
} | class ____(GroupEndpoint):
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
}
owner = ApiOwner.ISSUES
@extend_schema(
operation_id="List an Issue's Events",
parameters=[
GlobalParams.ORG_ID_OR_SLUG,
IssueParams.ISSUES_OR_GROUPS,
IssueParams.ISSUE_ID,
GlobalParams.START,
GlobalParams.END,
GlobalParams.STATS_PERIOD,
GlobalParams.ENVIRONMENT,
EventParams.FULL_PAYLOAD,
EventParams.SAMPLE,
EventParams.QUERY,
],
responses={
200: inline_sentry_response_serializer(
"GroupEventsResponseDict", list[SimpleEventSerializerResponse]
),
400: RESPONSE_BAD_REQUEST,
401: RESPONSE_UNAUTHORIZED,
403: RESPONSE_FORBIDDEN,
404: RESPONSE_NOT_FOUND,
},
examples=EventExamples.GROUP_EVENTS_SIMPLE,
)
def get(self, request: Request, group: Group) -> Response:
"""
Return a list of error events bound to an issue
"""
try:
environments = get_environments(request, group.project.organization)
query = self._get_search_query(request, group, environments)
except InvalidQuery as exc:
return Response({"detail": str(exc)}, status=400)
except (NoResults, ResourceDoesNotExist):
return Response([])
try:
start, end = get_date_range_from_params(request.GET, optional=True)
except InvalidParams as e:
raise ParseError(detail=str(e))
try:
return self._get_events_snuba(request, group, environments, query, start, end)
except GroupEventsError as exc:
raise ParseError(detail=str(exc))
def _get_events_snuba(
self,
request: Request,
group: Group,
environments: Sequence[Environment],
query: str | None,
start: datetime | None,
end: datetime | None,
) -> Response:
default_end = timezone.now()
default_start = default_end - timedelta(days=90)
params: ParamsType = {
"project_id": [group.project_id],
"organization_id": group.project.organization_id,
"start": start if start else default_start,
"end": end if end else default_end,
}
referrer = f"api.group-events.{group.issue_category.name.lower()}"
direct_hit_resp = get_direct_hit_response(
request, query, params, f"{referrer}.direct-hit", group
)
if direct_hit_resp:
return direct_hit_resp
if environments:
params["environment"] = [env.name for env in environments]
full = request.GET.get("full") in ("1", "true")
sample = request.GET.get("sample") in ("1", "true")
if sample:
orderby = "sample"
else:
orderby = None
def data_fn(offset: int, limit: int) -> Any:
try:
snuba_query = get_query_builder_for_group(
request.GET.get("query", ""),
params,
group,
limit=limit,
offset=offset,
orderby=orderby,
)
except InvalidSearchQuery as e:
raise ParseError(detail=str(e))
results = snuba_query.run_query(referrer=referrer)
results = [
Event(
event_id=evt["id"],
project_id=evt["project.id"],
snuba_data={
"event_id": evt["id"],
"group_id": evt["issue.id"],
"project_id": evt["project.id"],
"timestamp": evt["timestamp"],
},
)
for evt in results["data"]
]
if full:
eventstore.backend.bind_nodes(results)
return results
serializer = EventSerializer() if full else SimpleEventSerializer()
return self.paginate(
request=request,
on_results=lambda results: serialize(results, request.user, serializer),
paginator=GenericOffsetPaginator(data_fn=data_fn),
)
def _get_search_query(
self, request: Request, group: Group, environments: Sequence[Environment]
) -> str | None:
raw_query = request.GET.get("query")
if raw_query:
query_kwargs = parse_query([group.project], raw_query, request.user, environments)
query = query_kwargs.pop("query", None)
else:
query = None
return query
| GroupEventsEndpoint |
python | huggingface__transformers | src/transformers/models/falcon/configuration_falcon.py | {
"start": 876,
"end": 8599
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`FalconModel`]. It is used to instantiate a Falcon
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configuration to that of the
[tiiuae/falcon-7b](https://huggingface.co/tiiuae/falcon-7b) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 65024):
Vocabulary size of the Falcon model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`FalconModel`]
hidden_size (`int`, *optional*, defaults to 4544):
Dimension of the hidden representations.
num_hidden_layers (`int`, *optional*, defaults to 32):
Number of hidden layers in the Transformer decoder.
num_attention_heads (`int`, *optional*, defaults to 71):
Number of attention heads for each attention layer in the Transformer encoder.
num_ln_in_parallel_attn (`int`, *optional*):
Set to 2 if separate layer norms are to be used for the MLP and the attention output when using parallel
attention, otherwise, 1.
layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
The epsilon used by the layer normalization layers.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
use_cache (`bool`, *optional*, defaults to `True`):
Whether the model should return the last key/values attentions (not used by all models). Only relevant if
`config.is_decoder=True`.
hidden_dropout (`float`, *optional*, defaults to 0.0):
The dropout probability for MLP layers.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout probability for attention layers.
num_kv_heads (`int`, *optional*):
Number of key-value heads to use per attention layer. If unset, defaults to the same value as
`num_attention_heads`.
alibi (`bool`, *optional*, defaults to `False`):
Whether to use ALiBi positional biases during self-attention.
new_decoder_architecture (`bool`, *optional*, defaults to `False`):
Whether to use the new (Falcon-40B) decoder architecture. If `True`, the `multi_query` and `parallel_attn`
arguments are ignored, as the new decoder always uses parallel attention.
multi_query (`bool`, *optional*, defaults to `True`):
Whether to use multi-query attention in the decoder. Ignored when `new_decoder_architecture` is `True`.
parallel_attn (`bool`, *optional*, defaults to `True`):
Whether to compute attention in parallel with the feedforward layer. If False, they are consecutive
instead, as in the original Transformer architecture. Ignored when `new_decoder_architecture` is `True`.
bias (`bool`, *optional*, defaults to `False`):
Whether to use bias on Linear layers.
max_position_embeddings (`int`, *optional*, defaults to 2048):
The maximum sequence length that this model might ever be used with, when `alibi` is `False`. Pretrained
Falcon models with RoPE support up to 2048 tokens.
rope_parameters (`RopeParameters`, *optional*):
Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
with longer `max_position_embeddings`.
bos_token_id (`int`, *optional*, defaults to 11):
The id of the "beginning-of-sequence" token.
eos_token_id (`int`, *optional*, defaults to 11):
The id of the "end-of-sequence" token.
ffn_hidden_size (`int`, *optional*):
The hidden size of the feedforward layer in the Transformer decoder.
defaults to 4x hidden dim
activation (`str`, *optional*, defaults to `"gelu"`):
The activation function used in the feedforward layer.
Example:
```python
>>> from transformers import FalconModel, FalconConfig
>>> # Initializing a small (2-layer) Falcon configuration
>>> configuration = FalconConfig(num_hidden_layers=2)
>>> # Initializing a model from the small configuration
>>> model = FalconModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "falcon"
keys_to_ignore_at_inference = ["past_key_values"]
def __init__(
self,
vocab_size: Optional[int] = 65024,
hidden_size: Optional[int] = 4544,
num_hidden_layers: Optional[int] = 32,
num_attention_heads: Optional[int] = 71,
num_ln_in_parallel_attn: Optional[int] = None,
layer_norm_epsilon: Optional[int] = 1e-5,
initializer_range: Optional[float] = 0.02,
use_cache: Optional[bool] = True,
hidden_dropout: Optional[float] = 0.0,
attention_dropout: Optional[float] = 0.0,
num_kv_heads: Optional[int] = None,
alibi: Optional[bool] = False,
new_decoder_architecture: Optional[bool] = False,
multi_query: Optional[bool] = True,
parallel_attn: Optional[bool] = True,
bias: Optional[bool] = False,
max_position_embeddings: Optional[int] = 2048,
rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None,
bos_token_id: Optional[int] = 11,
eos_token_id: Optional[int] = 11,
ffn_hidden_size: Optional[int] = None,
activation: Optional[str] = "gelu",
**kwargs,
):
self.vocab_size = vocab_size
# Backward compatibility with n_embed kwarg
n_embed = kwargs.pop("n_embed", None)
self.hidden_size = hidden_size if n_embed is None else n_embed
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.layer_norm_epsilon = layer_norm_epsilon
self.initializer_range = initializer_range
self.use_cache = use_cache
self.hidden_dropout = hidden_dropout
self.attention_dropout = attention_dropout
self.bos_token_id = bos_token_id
self.eos_token_id = eos_token_id
self.num_kv_heads = num_attention_heads if num_kv_heads is None else num_kv_heads
self.alibi = alibi
self.new_decoder_architecture = new_decoder_architecture
self.multi_query = multi_query # Ignored when new_decoder_architecture is True
self.parallel_attn = parallel_attn
self.bias = bias
self.num_ln_in_parallel_attn = num_ln_in_parallel_attn
self.max_position_embeddings = max_position_embeddings
self.activation = activation
if ffn_hidden_size is None:
self.ffn_hidden_size = hidden_size * 4
else:
self.ffn_hidden_size = ffn_hidden_size
self.rope_parameters = rope_parameters
super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
@property
def head_dim(self):
return self.hidden_size // self.num_attention_heads
@property
def rotary(self):
return not self.alibi
__all__ = ["FalconConfig"]
| FalconConfig |
python | wandb__wandb | wandb/sdk/artifacts/_generated/artifact_type.py | {
"start": 376,
"end": 513
} | class ____(GQLResult):
artifact_type: ArtifactTypeProjectArtifactArtifactType = Field(alias="artifactType")
| ArtifactTypeProjectArtifact |
python | run-llama__llama_index | llama-index-integrations/llms/llama-index-llms-novita/llama_index/llms/novita/base.py | {
"start": 540,
"end": 5179
} | class ____(OpenAILike):
"""
NovitaAI LLM.
Novita AI & LlamaIndex Integration Guide
Effortlessly integrate Novita AI with LlamaIndex to build intelligent, data-powered applications.
Designed for optimal indexing and retrieval, LlamaIndex excels in delivering high efficiency for applications requiring precise and fast data access. By combining [Novita AI](https://novita.ai/) with LlamaIndex, you will unlock key benefits such as superior data retrieval accuracy, unmatched scalability, and cost-effective performance.
This guide will walk you through how to use LlamaIndex with Novita AI based on the OpenAl APl, offering smarter, scalable, and highly efficient AI solutions that drive innovation and deliver exceptional results for developers.
How to Integrate Novita AI API with LlamaIndex
Step 1: Visit [Model Library](https://novita.ai/llm-api) on Novita AI and select a model of interest.

Step 2: Navigate to the demo page of the chosen model and click the `Code` button on the right.

Step 3: Copy the model’s name and make a note of it.

Step 4: [Log in ](https://novita.ai/user/login)to the Novita platform.

Step 5: After logging in, go to the platform’s [settings page](https://novita.ai/settings).

Step 6: Create a new [API key](https://novita.ai/settings/key-management) and copy it for service authentication.

Step 7: Install `llama_index` and related Python libraries by running:

Step 8: Write Python code and set the model name and API key as parameters in the NovitaAI class.

Step 9: Run the code to get the output.

For more examples, refer to the documentation: [llama_index/llama-index-integrations/llms/llama-index-llms-novita at main · run-llama/llama_index](https://github.com/run-llama/llama_index/tree/main/llama-index-integrations/llms/llama-index-llms-novita).
"""
def __init__(
self,
model: str = DEFAULT_MODEL,
api_key: Optional[str] = None,
temperature: float = 0.95,
max_tokens: int = 1024,
is_chat_model: bool = True,
additional_kwargs: Optional[Dict[str, Any]] = None,
**kwargs: Any,
) -> None:
additional_kwargs = additional_kwargs or {}
api_base = get_from_param_or_env(
"api_base", DEFAULT_API_BASE, "NOVITA_API_BASE"
)
api_key = get_from_param_or_env("api_key", api_key, "NOVITA_API_KEY")
super().__init__(
api_base=api_base,
api_key=api_key,
model=model,
temperature=temperature,
max_tokens=max_tokens,
is_chat_model=is_chat_model,
is_function_calling_model=is_function_calling_model(model),
additional_kwargs=additional_kwargs,
**kwargs,
)
@classmethod
def class_name(cls) -> str:
"""Get class name."""
return "NovitaAI"
| NovitaAI |
python | realpython__materials | python-f-string/person.py | {
"start": 0,
"end": 287
} | class ____:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"I'm {self.name}, and I'm {self.age} years old."
def __repr__(self):
return f"{type(self).__name__}(name='{self.name}', age={self.age})"
| Person |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 24478,
"end": 25419
} | class ____(TestCase):
"""Tests for ``unique_to_each()``"""
def test_all_unique(self):
"""When all the input iterables are unique the output should match
the input."""
iterables = [[1, 2], [3, 4, 5], [6, 7, 8]]
self.assertEqual(mi.unique_to_each(*iterables), iterables)
def test_duplicates(self):
"""When there are duplicates in any of the input iterables that aren't
in the rest, those duplicates should be emitted."""
iterables = ["mississippi", "missouri"]
self.assertEqual(
mi.unique_to_each(*iterables), [['p', 'p'], ['o', 'u', 'r']]
)
def test_mixed(self):
"""When the input iterables contain different types the function should
still behave properly"""
iterables = ['x', (i for i in range(3)), [1, 2, 3], tuple()]
self.assertEqual(mi.unique_to_each(*iterables), [['x'], [0], [3], []])
| UniqueToEachTests |
python | getsentry__sentry | src/sentry/replays/lib/http.py | {
"start": 175,
"end": 481
} | class ____(Protocol):
def make_range(self, last_index: int) -> tuple[int, int]: ...
def read_range(self, bytes: io.BytesIO) -> bytes:
"""Return a byte range from a reader.
The rules governing the range are derived from the implementation class.
"""
...
| RangeProtocol |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-baiduvectordb/llama_index/vector_stores/baiduvectordb/base.py | {
"start": 4057,
"end": 24143
} | class ____(BasePydanticVectorStore):
"""
Baidu VectorDB as a vector store.
In order to use this you need to have a database instance.
See the following documentation for details:
https://cloud.baidu.com/doc/VDB/index.html
Args:
endpoint (Optional[str]): endpoint of Baidu VectorDB
account (Optional[str]): The account for Baidu VectorDB. Default value is "root"
api_key (Optional[str]): The Api-Key for Baidu VectorDB
database_name(Optional[str]): The database name for Baidu VectorDB
table_params (Optional[TableParams]): The table parameters for BaiduVectorDB
"""
user_defined_fields: List[TableField] = Field(default_factory=list)
batch_size: int
_vdb_client: Any = PrivateAttr()
_database: Any = PrivateAttr()
_table: Any = PrivateAttr()
def __init__(
self,
endpoint: str,
api_key: str,
account: str = DEFAULT_ACCOUNT,
database_name: str = DEFAULT_DATABASE_NAME,
table_params: TableParams = TableParams(dimension=1536),
batch_size: int = 1000,
stores_text: bool = True,
**kwargs: Any,
):
"""Init params."""
super().__init__(
user_defined_fields=table_params.filter_fields,
batch_size=batch_size,
stores_text=stores_text,
**kwargs,
)
self._init_client(endpoint, account, api_key)
self._create_database_if_not_exists(database_name)
self._create_table(table_params)
@classmethod
def class_name(cls) -> str:
return "BaiduVectorDB"
@classmethod
def from_params(
cls,
endpoint: str,
api_key: str,
account: str = DEFAULT_ACCOUNT,
database_name: str = DEFAULT_DATABASE_NAME,
table_params: TableParams = TableParams(dimension=1536),
batch_size: int = 1000,
**kwargs: Any,
) -> "BaiduVectorDB":
_try_import()
return cls(
endpoint=endpoint,
account=account,
api_key=api_key,
database_name=database_name,
table_params=table_params,
batch_size=batch_size,
**kwargs,
)
def _init_client(self, endpoint: str, account: str, api_key: str) -> None:
import pymochow
from pymochow.configuration import Configuration
from pymochow.auth.bce_credentials import BceCredentials
logger.debug("Connecting to Baidu VectorDB...")
config = Configuration(
credentials=BceCredentials(account, api_key),
endpoint=endpoint,
connection_timeout_in_mills=DEFAULT_TIMEOUT_IN_MILLS,
)
self._vdb_client = pymochow.MochowClient(config)
logger.debug("Baidu VectorDB client initialized.")
def _create_database_if_not_exists(self, database_name: str) -> None:
db_list = self._vdb_client.list_databases()
if database_name in [db.database_name for db in db_list]:
logger.debug(f"Database '{database_name}' already exists.")
self._database = self._vdb_client.database(database_name)
else:
logger.debug(f"Creating database '{database_name}'.")
self._database = self._vdb_client.create_database(database_name)
logger.debug(f"Database '{database_name}' created.")
def _create_table(self, table_params: TableParams) -> None:
import pymochow
if table_params is None:
raise ValueError(VALUE_NONE_ERROR.format("table_params"))
try:
self._table = self._database.describe_table(table_params.table_name)
logger.debug(f"Table '{table_params.table_name}' already exists.")
if table_params.drop_exists:
logger.debug(f"Dropping table '{table_params.table_name}'.")
self._database.drop_table(table_params.table_name)
# wait for table to be fully dropped
start_time = time.time()
loop_count = 0
while time.time() - start_time < DEFAULT_WAIT_TIMEOUT:
loop_count += 1
logger.debug(
f"Waiting for table {table_params.table_name} to be dropped,"
f" attempt {loop_count}"
)
time.sleep(1)
tables = self._database.list_table()
table_names = {table.table_name for table in tables}
if table_params.table_name not in table_names:
logger.debug(f"Table '{table_params.table_name}' dropped.")
break
else:
raise TimeoutError(
f"Table {table_params.table_name} was not dropped within"
f" {DEFAULT_WAIT_TIMEOUT} seconds"
)
self._create_table_in_db(table_params)
except pymochow.exception.ServerError:
self._create_table_in_db(table_params)
def _create_table_in_db(
self,
table_params: TableParams,
) -> None:
from pymochow.model.enum import FieldType, TableState
from pymochow.model.schema import Field, Schema, SecondaryIndex, VectorIndex
from pymochow.model.table import Partition
logger.debug(f"Creating table '{table_params.table_name}'.")
index_type = self._get_index_type(table_params.index_type)
metric_type = self._get_metric_type(table_params.metric_type)
vector_params = self._get_index_params(index_type, table_params)
fields = []
fields.append(
Field(
FIELD_ID,
FieldType.STRING,
primary_key=True,
partition_key=True,
auto_increment=False,
not_null=True,
)
)
fields.append(Field(DEFAULT_DOC_ID_KEY, FieldType.STRING))
fields.append(Field(FIELD_METADATA, FieldType.STRING))
fields.append(Field(DEFAULT_TEXT_KEY, FieldType.STRING))
fields.append(
Field(
FIELD_VECTOR, FieldType.FLOAT_VECTOR, dimension=table_params.dimension
)
)
for field in table_params.filter_fields:
fields.append(Field(field.name, FieldType(field.data_type), not_null=True))
indexes = []
indexes.append(
VectorIndex(
index_name=INDEX_VECTOR,
index_type=index_type,
field=FIELD_VECTOR,
metric_type=metric_type,
params=vector_params,
)
)
for field in table_params.filter_fields:
index_name = field.name + INDEX_SUFFIX
indexes.append(SecondaryIndex(index_name=index_name, field=field.name))
schema = Schema(fields=fields, indexes=indexes)
self._table = self._database.create_table(
table_name=table_params.table_name,
replication=table_params.replication,
partition=Partition(partition_num=table_params.partition),
schema=schema,
enable_dynamic_field=True,
)
# wait for table to be ready
start_time = time.time()
loop_count = 0
while time.time() - start_time < DEFAULT_WAIT_TIMEOUT:
loop_count += 1
logger.debug(
f"Waiting for table {table_params.table_name} to become ready,"
f" attempt {loop_count}"
)
time.sleep(1)
table = self._database.describe_table(table_params.table_name)
if table.state == TableState.NORMAL:
logger.debug(f"Table '{table_params.table_name}' is ready.")
break
else:
raise TimeoutError(
f"Table {table_params.table_name} did not become ready within"
f" {DEFAULT_WAIT_TIMEOUT} seconds"
)
@staticmethod
def _get_index_params(index_type: Any, table_params: TableParams) -> None:
from pymochow.model.enum import IndexType
from pymochow.model.schema import HNSWParams
vector_params = (
{} if table_params.vector_params is None else table_params.vector_params
)
if index_type == IndexType.HNSW:
return HNSWParams(
m=vector_params.get("M", DEFAULT_HNSW_M),
efconstruction=vector_params.get(
"efConstruction", DEFAULT_HNSW_EF_CONSTRUCTION
),
)
return None
@staticmethod
def _get_index_type(index_type_value: str) -> Any:
from pymochow.model.enum import IndexType
index_type_value = index_type_value or IndexType.HNSW
try:
return IndexType(index_type_value)
except ValueError:
support_index_types = [d.value for d in IndexType.__members__.values()]
raise ValueError(
NOT_SUPPORT_INDEX_TYPE_ERROR.format(
index_type_value, support_index_types
)
)
@staticmethod
def _get_metric_type(metric_type_value: str) -> Any:
from pymochow.model.enum import MetricType
metric_type_value = metric_type_value or MetricType.L2
try:
return MetricType(metric_type_value.upper())
except ValueError:
support_metric_types = [d.value for d in MetricType.__members__.values()]
raise ValueError(
NOT_SUPPORT_METRIC_TYPE_ERROR.format(
metric_type_value, support_metric_types
)
)
@property
def client(self) -> Any:
"""Get client."""
return self._vdb_client
def clear(self) -> None:
"""
Clear all nodes from Baidu VectorDB table.
This method deletes the table.
"""
return asyncio.get_event_loop().run_until_complete(self.aclear())
async def aclear(self) -> None:
"""
Asynchronously clear all nodes from Baidu VectorDB table.
This method deletes the table.
"""
import pymochow
try:
# Check if table exists
table_name = self._table.table_name
self._database.describe_table(table_name)
# Table exists, drop it
logger.debug(f"Dropping table '{table_name}'.")
self._database.drop_table(table_name)
# Wait for table to be fully dropped
start_time = time.time()
loop_count = 0
while time.time() - start_time < DEFAULT_WAIT_TIMEOUT:
loop_count += 1
logger.debug(
f"Waiting for table {table_name} to be dropped, attempt {loop_count}"
)
await asyncio.sleep(1)
tables = self._database.list_table()
table_names = {table.table_name for table in tables}
if table_name not in table_names:
logger.debug(f"Table '{table_name}' dropped.")
break
else:
raise TimeoutError(
f"Table {table_name} was not dropped within {DEFAULT_WAIT_TIMEOUT}"
" seconds"
)
except (pymochow.exception.ServerError, AttributeError):
# Table doesn't exist or _table not properly initialized, nothing to delete
logger.debug("Table does not exist, nothing to clear.")
def add(
self,
nodes: List[BaseNode],
*,
rebuild_index: bool = True,
rebuild_timeout: Optional[int] = None,
**add_kwargs: Any,
) -> List[str]:
"""
Add nodes to Baidu VectorDB table.
Args:
nodes: List of nodes with embeddings.
rebuild_index: Optional. Whether to rebuild the vector index
after adding nodes. Defaults to True.
rebuild_timeout: Optional. Timeout for rebuilding the index in seconds.
If None, it will wait indefinitely. Defaults to None.
Returns:
List of node IDs that were added to the table.
"""
return asyncio.get_event_loop().run_until_complete(
self.async_add(
nodes,
rebuild_index=rebuild_index,
rebuild_timeout=rebuild_timeout,
**add_kwargs,
)
)
async def async_add(
self,
nodes: List[BaseNode],
*,
rebuild_index: bool = True,
rebuild_timeout: Optional[int] = None,
**add_kwargs: Any,
) -> List[str]:
"""
Asynchronous method to add nodes to Baidu VectorDB table.
Args:
nodes: List of nodes with embeddings.
rebuild_index: Optional. Whether to rebuild the vector index
after adding nodes. Defaults to True.
rebuild_timeout: Optional. Timeout for rebuilding the index in seconds.
If None, it will wait indefinitely. Defaults to None.
Returns:
List of node IDs that were added to the table.
"""
if len(nodes) == 0:
return []
from pymochow.model.table import Row
from pymochow.model.enum import IndexState
ids = []
rows = []
for i, node in enumerate(nodes):
logger.debug(f"Processing node {i + 1}/{len(nodes)}, id: {node.node_id}")
row = Row(id=node.node_id, vector=node.get_embedding())
if node.ref_doc_id is not None:
row._data[DEFAULT_DOC_ID_KEY] = node.ref_doc_id
if node.metadata is not None:
row._data[FIELD_METADATA] = json.dumps(node.metadata)
for field in self.user_defined_fields:
v = node.metadata.get(field.name)
if v is not None:
row._data[field.name] = v
if isinstance(node, TextNode) and node.text is not None:
row._data[DEFAULT_TEXT_KEY] = node.text
rows.append(row)
ids.append(node.node_id)
if len(rows) >= self.batch_size:
logger.debug(f"Upserting {len(rows)} rows to the table.")
self._table.upsert(rows=rows)
rows = []
if len(rows) > 0:
logger.debug(f"Upserting remaining {len(rows)} rows to the table.")
self._table.upsert(rows=rows)
if rebuild_index:
logger.debug(f"Rebuilding index '{INDEX_VECTOR}'.")
self._table.rebuild_index(INDEX_VECTOR)
start_time = time.time()
loop_count = 0
while True:
loop_count += 1
logger.debug(
f"Waiting for index {INDEX_VECTOR} to be ready, attempt"
f" {loop_count}"
)
await asyncio.sleep(1)
index = self._table.describe_index(INDEX_VECTOR)
if index.state == IndexState.NORMAL:
logger.debug(f"Index '{INDEX_VECTOR}' is ready.")
break
if (
rebuild_timeout is not None
and time.time() - start_time > rebuild_timeout
):
raise TimeoutError(
f"Index {INDEX_VECTOR} did not become ready within"
f" {rebuild_timeout} seconds"
)
return ids
# Baidu VectorDB Not support delete with filter right now, will support it later.
def delete(self, ref_doc_id: str, **delete_kwargs: Any) -> None:
"""
Delete nodes using with ref_doc_id or ids.
Args:
ref_doc_id (str): The doc_id of the document to delete.
"""
raise NotImplementedError("Not support.")
def query(self, query: VectorStoreQuery, **kwargs: Any) -> VectorStoreQueryResult:
"""
Query index for top k most similar nodes.
Args:
query (VectorStoreQuery): contains
query_embedding (List[float]): query embedding
similarity_top_k (int): top k most similar nodes
filters (Optional[MetadataFilters]): filter result
Returns:
VectorStoreQueryResult: Query result containing nodes, similarities, and ids.
"""
return asyncio.get_event_loop().run_until_complete(self.aquery(query, **kwargs))
async def aquery(
self, query: VectorStoreQuery, **kwargs: Any
) -> VectorStoreQueryResult:
"""
Asynchronously query index for top k most similar nodes.
Args:
query (VectorStoreQuery): contains
query_embedding (List[float]): query embedding
similarity_top_k (int): top k most similar nodes
filters (Optional[MetadataFilters]): filter result
Returns:
VectorStoreQueryResult: Query result containing nodes, similarities, and ids.
"""
from pymochow.model.table import AnnSearch, HNSWSearchParams
search_filter = None
if query.filters is not None:
search_filter = self._build_filter_condition(query.filters, **kwargs)
logger.debug(
f"Querying with top_k={query.similarity_top_k} and filter='{search_filter}'"
)
anns = AnnSearch(
vector_field=FIELD_VECTOR,
vector_floats=query.query_embedding,
params=HNSWSearchParams(ef=DEFAULT_HNSW_EF, limit=query.similarity_top_k),
filter=search_filter,
)
res = self._table.search(anns=anns, retrieve_vector=True)
rows = res.rows
if rows is None or len(rows) == 0:
logger.debug("Query returned no results.")
return VectorStoreQueryResult(nodes=[], similarities=[], ids=[])
logger.debug(f"Query returned {len(rows)} results.")
nodes = []
similarities = []
ids = []
for row in rows:
similarities.append(row.get("distance"))
row_data = row.get("row", {})
ids.append(row_data.get(FIELD_ID))
meta_str = row_data.get(FIELD_METADATA)
meta = {} if meta_str is None else json.loads(meta_str)
doc_id = row_data.get(DEFAULT_DOC_ID_KEY)
node = TextNode(
id_=row_data.get(FIELD_ID),
text=row_data.get(DEFAULT_TEXT_KEY),
embedding=row_data.get(FIELD_VECTOR),
metadata=meta,
)
if doc_id is not None:
node.relationships = {
NodeRelationship.SOURCE: RelatedNodeInfo(node_id=doc_id)
}
nodes.append(node)
return VectorStoreQueryResult(nodes=nodes, similarities=similarities, ids=ids)
@staticmethod
def _build_filter_condition(standard_filters: MetadataFilters) -> str:
filters_list = []
for filter in standard_filters.filters:
value = (
f"'{filter.value}'"
if isinstance(filter.value, (str, bool))
else filter.value
)
if filter.operator:
if filter.operator.value in ["<", ">", "<=", ">=", "!="]:
condition = f"{filter.key} {filter.operator.value} {value}"
elif filter.operator.value in ["=="]:
condition = f"{filter.key} == {value}"
else:
raise ValueError(
f"Filter operator {filter.operator} not supported."
)
else:
condition = f"{filter.key} = {value}"
filters_list.append(condition)
return f" {standard_filters.condition.value.upper()} ".join(filters_list)
| BaiduVectorDB |
python | conda__conda | tests/plugins/test_virtual_packages.py | {
"start": 839,
"end": 16763
} | class ____:
@plugins.hookimpl
def conda_virtual_packages(self):
yield CondaVirtualPackage(
name="abc",
version="123",
build=None,
override_entity=None,
)
yield CondaVirtualPackage(
name="def",
version="456",
build=None,
override_entity=None,
)
yield CondaVirtualPackage(
name="ghi",
version="789",
build="xyz",
override_entity=None,
)
@pytest.fixture()
def plugin(plugin_manager):
plugin = VirtualPackagesPlugin()
plugin_manager.register(plugin)
return plugin
def test_invoked(plugin):
index = conda.core.index.ReducedIndex(
prefix=context.default_prefix,
channels=context.default_channels,
subdirs=context.subdirs,
specs=(),
repodata_fn=context.repodata_fns[0],
)
packages = package_dict(index)
assert packages["__abc"].version == "123"
assert packages["__def"].version == "456"
assert packages["__ghi"].version == "789"
assert packages["__ghi"].build == "xyz"
def test_duplicated(plugin_manager):
plugin_manager.register(VirtualPackagesPlugin())
plugin_manager.register(VirtualPackagesPlugin())
with pytest.raises(
PluginError, match=r"Conflicting plugins found for `virtual_packages`"
):
conda.core.index.ReducedIndex(
prefix=context.default_prefix,
channels=context.default_channels,
subdirs=context.subdirs,
specs=(),
repodata_fn=context.repodata_fns[0],
)
def test_cuda_detection(clear_cuda_version):
# confirm that CUDA detection doesn't raise exception
version = cuda.cuda_version()
assert version is None or isinstance(version, str)
@pytest.mark.parametrize(
"override_value,expected, expect_pkg",
[
pytest.param("4.5", "4.5", True, id="override-set"),
pytest.param("", None, False, id="override-empty"),
],
)
def test_cuda_override(
clear_cuda_version,
override_value: str,
expected: str | None,
expect_pkg: bool,
monkeypatch: MonkeyPatch,
):
monkeypatch.setenv("CONDA_OVERRIDE_CUDA", override_value)
reset_context()
virtual_package = CondaVirtualPackage("cuda", "4.1", None, "version")
pkg_record = virtual_package.to_virtual_package()
if expect_pkg:
assert pkg_record
assert pkg_record.version == expected
else:
assert pkg_record is NULL
def get_virtual_precs() -> Iterable[PackageRecord]:
index = conda.core.index.ReducedIndex(
prefix=context.default_prefix,
channels=context.default_channels,
subdirs=context.subdirs,
specs=(),
repodata_fn=context.repodata_fns[0],
)
yield from (
prec
for prec in index
if prec.channel.name == "@" and prec.name.startswith("__")
)
@pytest.mark.parametrize(
"subdir,expected",
[
# see conda.base.constants.KNOWN_SUBDIRS
pytest.param("emscripten-wasm32", [], id="emscripten-wasm32"),
pytest.param("freebsd-64", ["__unix"], id="freebsd-64"),
pytest.param("linux-32", ["__linux", "__unix"], id="linux-32"),
pytest.param("linux-64", ["__linux", "__unix"], id="linux-64"),
pytest.param("linux-aarch64", ["__linux", "__unix"], id="linux-aarch64"),
pytest.param("linux-armv6l", ["__linux", "__unix"], id="linux-armv6l"),
pytest.param("linux-armv7l", ["__linux", "__unix"], id="linux-armv7l"),
pytest.param("linux-ppc64", ["__linux", "__unix"], id="linux-ppc64"),
pytest.param("linux-ppc64le", ["__linux", "__unix"], id="linux-ppc64le"),
pytest.param("linux-riscv64", ["__linux", "__unix"], id="linux-riscv64"),
pytest.param("linux-s390x", ["__linux", "__unix"], id="linux-s390x"),
pytest.param("osx-64", ["__osx", "__unix"], id="osx-64"),
pytest.param("osx-aarch64", ["__osx", "__unix"], id="osx-aarch64"),
pytest.param("osx-arm64", ["__osx", "__unix"], id="osx-arm64"),
pytest.param("wasi-wasm32", [], id="wasi-wasm32"),
pytest.param("win-32", ["__win"], id="win-32"),
pytest.param("win-64", ["__win"], id="win-64"),
pytest.param("win-64", ["__win"], id="win-64"),
pytest.param("win-arm64", ["__win"], id="win-arm64"),
pytest.param("zos-z", [], id="zos-z"),
],
)
def test_subdir_override(
monkeypatch: MonkeyPatch,
subdir: str,
expected: list[str],
clear_cuda_version: None,
):
"""
Conda should create virtual packages for the appropriate platform, following
context.subdir instead of the host operating system.
"""
monkeypatch.setenv("CONDA_SUBDIR", subdir)
monkeypatch.setenv("CONDA_OVERRIDE_ARCHSPEC", "")
monkeypatch.setenv("CONDA_OVERRIDE_CUDA", "")
monkeypatch.setenv("CONDA_OVERRIDE_GLIBC", "")
reset_context()
assert context.subdir == subdir
assert {prec.name for prec in get_virtual_precs()} == {
"__conda", # always present
*expected,
}
@pytest.mark.parametrize("version,expected", [(None, False), ("bla", True)])
def test_archspec_override(
monkeypatch: MonkeyPatch,
version: str | None,
expected: bool,
):
"""Conda should not produce a archspec virtual package when CONDA_OVERRIDE_ARCHSPEC=""."""
monkeypatch.setenv("CONDA_OVERRIDE_ARCHSPEC", version or "")
reset_context()
assert any(prec.name == "__archspec" for prec in get_virtual_precs()) is expected
@pytest.mark.parametrize("version,expected", [(None, True), ("1.0", True)])
def test_linux_override(monkeypatch: MonkeyPatch, version: str | None, expected: bool):
"""Conda will still produce a linux virtual package when CONDA_OVERRIDE_LINUX=""."""
monkeypatch.setenv("CONDA_SUBDIR", "linux-64")
monkeypatch.setenv("CONDA_OVERRIDE_LINUX", version or "")
reset_context()
assert context.subdir == "linux-64"
assert any(prec.name == "__linux" for prec in get_virtual_precs()) is expected
def test_linux_value(monkeypatch: MonkeyPatch):
"""
In non Linux systems, conda cannot know which __linux version to offer if subdir==linux-64;
should be 0. In Linux systems, it should match the beginning of the value reported by
platform.release().
"""
monkeypatch.setenv("CONDA_SUBDIR", "linux-64")
reset_context()
assert context.subdir == "linux-64"
for prec in get_virtual_precs():
if prec.name == "__linux":
if on_linux:
assert platform.release().startswith(prec.version)
else:
assert prec.version == "0"
break
else:
raise AssertionError("Should have found __linux")
@pytest.mark.parametrize("version,expected", [(None, False), ("1.0", True)])
def test_glibc_override(monkeypatch: MonkeyPatch, version: str | None, expected: bool):
"""Conda should not produce a libc virtual package when CONDA_OVERRIDE_GLIBC=""."""
monkeypatch.setenv("CONDA_SUBDIR", "linux-64")
monkeypatch.setenv("CONDA_OVERRIDE_GLIBC", version or "")
reset_context()
assert context.subdir == "linux-64"
assert any(prec.name == "__glibc" for prec in get_virtual_precs()) is expected
@pytest.mark.parametrize("version,expected", [(None, False), ("1.0", True)])
def test_osx_override(monkeypatch: MonkeyPatch, version: str | None, expected: bool):
"""Conda should not produce a osx virtual package when CONDA_OVERRIDE_OSX=""."""
monkeypatch.setenv("CONDA_SUBDIR", "osx-64")
monkeypatch.setenv("CONDA_OVERRIDE_OSX", version or "")
reset_context()
assert context.subdir == "osx-64"
assert any(prec.name == "__osx" for prec in get_virtual_precs()) is expected
@pytest.mark.parametrize("version,expected", [(None, False), ("1.0", True)])
def test_win_override(monkeypatch: MonkeyPatch, version: str | None, expected: bool):
"""Conda should not produce a win virtual package when CONDA_OVERRIDE_WIN=""."""
monkeypatch.setenv("CONDA_SUBDIR", "win-64")
monkeypatch.setenv("CONDA_OVERRIDE_WIN", version or "")
reset_context()
assert context.subdir == "win-64"
assert any(prec.name == "__win" for prec in get_virtual_precs()) is expected
def test_win_value(monkeypatch: MonkeyPatch):
"""
In non Windows systems, conda cannot know which __win version to offer if subdir==win-64;
should be 0. In Windows systems, it should be set to whatever platform.version() reports.
"""
monkeypatch.setenv("CONDA_SUBDIR", "win-64")
reset_context()
assert context.subdir == "win-64"
for prec in get_virtual_precs():
if prec.name == "__win":
assert prec.version == (platform.version() if on_win else "0")
break
else:
raise AssertionError("Should have found __win")
def test_osx_value(monkeypatch: MonkeyPatch):
"""
In non macOS systems, conda cannot know which __osx version to offer if subdir==osx-64;
should be 0. In macOS systems, it should be the value reported by platform.mac_ver()[0].
"""
monkeypatch.setenv("CONDA_SUBDIR", "osx-64")
reset_context()
assert context.subdir == "osx-64"
for prec in get_virtual_precs():
if prec.name == "__osx":
assert prec.version == (mac_ver() if on_mac else "0")
break
else:
raise AssertionError("Should have found __osx")
def test_conda_virtual_package():
"""Conda always produces a conda virtual package."""
assert any(
prec.name == "__conda" and prec.version == __version__
for prec in get_virtual_precs()
)
@pytest.fixture
def virtual_package_plugin(
mocker: MockerFixture,
monkeypatch: MonkeyPatch,
request,
) -> CondaVirtualPackage:
(
version,
build,
override_entity,
override_value,
empty_override,
version_validation,
) = request.param
if override_value is not None:
monkeypatch.setenv("CONDA_OVERRIDE_FOO", override_value)
deferred_version = mocker.MagicMock(return_value=version)
deferred_build = mocker.MagicMock(return_value=build)
plugin = CondaVirtualPackage(
name="foo",
version=deferred_version,
build=deferred_build,
override_entity=override_entity,
empty_override=empty_override,
version_validation=version_validation,
)
return plugin
@pytest.mark.parametrize(
"virtual_package_plugin, expected_null",
[
pytest.param(
(NULL, "1-abc-2", None, None, None, None),
True,
id="`version=NULL` returns NULL package ",
),
pytest.param(
("1.2", NULL, None, None, None, None),
True,
id="`build=NULL` returns NULL package",
),
pytest.param(
("1.2", None, "build", "", NULL, None),
True,
id="`empty_override=NULL` returns NULL package",
),
pytest.param(
("1.2", None, "version", "", None, None),
False,
id="`empty_override=None` returns valid package",
),
],
indirect=["virtual_package_plugin"],
)
def test_package_is_NULL(
virtual_package_plugin: CondaVirtualPackage,
expected_null: bool,
):
package = virtual_package_plugin.to_virtual_package()
if expected_null:
assert package is NULL
else:
assert package is not NULL
@pytest.mark.parametrize(
"virtual_package_plugin, expected_version, expected_build",
[
pytest.param(
("1.2", "1-abc-2", None, None, None, None),
"1.2",
"1-abc-2",
id="no override",
), # no override
pytest.param(
("1.2", "1-abc-2", "version", "override", None, None),
"override",
"1-abc-2",
id="version override",
),
pytest.param(
("1.2", "1-abc-2", "build", "override", None, None),
"1.2",
"override",
id="build override",
),
pytest.param(
("1.2", None, "version", "", None, None),
"0",
"0",
id="version override with `empty_override=None`",
),
pytest.param(
(None, "1-abc-2", "build", "", None, None),
"0",
"0",
id="build override with `empty_override=None`",
),
],
indirect=["virtual_package_plugin"],
)
def test_override_package_values(
virtual_package_plugin: CondaVirtualPackage,
expected_version: str,
expected_build: str,
):
package = virtual_package_plugin.to_virtual_package()
assert package.name == "__foo"
assert package.version == expected_version
assert package.build == expected_build
@pytest.mark.parametrize(
"virtual_package_plugin, expect_version_called, expect_build_called",
[
pytest.param(
("1.2", "1-abc-2", "version", "override", None, None),
False,
True,
id="version overriden",
),
pytest.param(
("1.2", "1-abc-2", "build", "override", None, None),
True,
False,
id="build overriden",
),
pytest.param(
("1.2", "1-abc-2", None, None, None, None),
True,
True,
id="base case, no override",
),
],
indirect=["virtual_package_plugin"],
)
def test_override_mock_calls(
virtual_package_plugin: CondaVirtualPackage,
expect_version_called: bool,
expect_build_called: bool,
):
virtual_package_plugin.to_virtual_package()
assert virtual_package_plugin.version.call_count == expect_version_called
assert virtual_package_plugin.build.call_count == expect_build_called
@pytest.mark.parametrize(
"virtual_package_plugin",
[
pytest.param(
("1.2", "0", None, "", None, None),
id="no version validation, no override",
),
pytest.param(
("1.2", "0", None, "", None, lambda version: "valid"),
id="version validation, no override",
),
pytest.param(
("1.2", "0", "version", "override", None, lambda version: "valid"),
id="version validation, override",
),
],
indirect=["virtual_package_plugin"],
)
def test_version_validation(virtual_package_plugin: CondaVirtualPackage):
package = virtual_package_plugin.to_virtual_package()
version = virtual_package_plugin.version.return_value
version_validation = virtual_package_plugin.version_validation
assert package.name == "__foo"
if version_validation:
assert package.version == "valid"
else:
assert package.version == (version or "0")
@pytest.mark.parametrize(
"virtual_package_plugin, expected_version",
[
pytest.param(
("1.2", "0", "version", None, None, None),
"overriden",
id="`CONDA_OVERRIDE_FOO` not set, but `context.override_virtual_packages` is set",
),
pytest.param(
("1.2", "0", "version", "priority_override", None, None),
"priority_override",
id="Both `CONDA_OVERRIDE_FOO` gets precedence and `context.override_virtual_packages` are set",
),
],
indirect=["virtual_package_plugin"],
)
def test_context_override(
virtual_package_plugin: CondaVirtualPackage,
expected_version: str,
mocker: MockerFixture,
):
mocker.patch(
"conda.base.context.Context.override_virtual_packages",
new_callable=mocker.PropertyMock,
return_value=({"foo": "overriden"}),
)
package = virtual_package_plugin.to_virtual_package()
assert package.name == "__foo"
assert package.version == expected_version
| VirtualPackagesPlugin |
python | sympy__sympy | sympy/physics/quantum/tests/test_innerproduct.py | {
"start": 1070,
"end": 1166
} | class ____(Ket, BarState):
@classmethod
def dual_class(self):
return BarBra
| BarKet |
python | huggingface__transformers | src/transformers/models/owlv2/modeling_owlv2.py | {
"start": 28344,
"end": 32111
} | class ____(nn.Module):
"""
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
[`Owlv2EncoderLayer`].
Args:
config: Owlv2Config
"""
def __init__(self, config: Owlv2Config):
super().__init__()
self.layers = nn.ModuleList([Owlv2EncoderLayer(config) for _ in range(config.num_hidden_layers)])
self.gradient_checkpointing = False
def forward(
self,
inputs_embeds,
attention_mask: Optional[torch.Tensor] = None,
causal_attention_mask: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, BaseModelOutput]:
r"""
Args:
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`).
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Causal mask for the text model. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
encoder_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
hidden_states = inputs_embeds
for encoder_layer in self.layers:
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
layer_outputs = encoder_layer(
hidden_states,
attention_mask,
causal_attention_mask,
output_attentions=output_attentions,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_attentions = all_attentions + (layer_outputs[1],)
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
return BaseModelOutput(
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
)
# Copied from transformers.models.owlvit.modeling_owlvit.OwlViTTextTransformer with OWLVIT->OWLV2,OwlViT->Owlv2
| Owlv2Encoder |
python | rushter__MLAlgorithms | mla/ensemble/random_forest.py | {
"start": 2841,
"end": 3795
} | class ____(RandomForest):
def __init__(
self,
n_estimators=10,
max_features=None,
min_samples_split=10,
max_depth=None,
criterion="mse",
):
super(RandomForestRegressor, self).__init__(
n_estimators=n_estimators,
max_features=max_features,
min_samples_split=min_samples_split,
max_depth=max_depth,
)
if criterion == "mse":
self.criterion = mse_criterion
else:
raise ValueError()
# Initialize empty regression trees
for _ in range(self.n_estimators):
self.trees.append(Tree(regression=True, criterion=self.criterion))
def _predict(self, X=None):
predictions = np.zeros((X.shape[0], self.n_estimators))
for i, tree in enumerate(self.trees):
predictions[:, i] = tree.predict(X)
return predictions.mean(axis=1)
| RandomForestRegressor |
python | walkccc__LeetCode | solutions/133. Clone Graph/133.py | {
"start": 0,
"end": 371
} | class ____:
def cloneGraph(self, node: 'Node') -> 'Node':
if not node:
return None
q = collections.deque([node])
map = {node: Node(node.val)}
while q:
u = q.popleft()
for v in u.neighbors:
if v not in map:
map[v] = Node(v.val)
q.append(v)
map[u].neighbors.append(map[v])
return map[node]
| Solution |
python | doocs__leetcode | solution/3100-3199/3168.Minimum Number of Chairs in a Waiting Room/Solution.py | {
"start": 0,
"end": 297
} | class ____:
def minimumChairs(self, s: str) -> int:
cnt = left = 0
for c in s:
if c == "E":
if left:
left -= 1
else:
cnt += 1
else:
left += 1
return cnt
| Solution |
python | keras-team__keras | keras/src/optimizers/schedules/learning_rate_schedule_test.py | {
"start": 8016,
"end": 9211
} | class ____(testing.TestCase):
def test_config(self):
self.run_class_serialization_test(
schedules.InverseTimeDecay(
initial_learning_rate=0.05,
decay_steps=10,
decay_rate=0.96,
staircase=True,
name="my_itd",
)
)
def test_decay(self):
initial_lr = 0.1
k = 10
decay_rate = 0.96
step = backend.Variable(0.0)
decayed_lr = schedules.InverseTimeDecay(initial_lr, k, decay_rate)
for i in range(k + 1):
expected = initial_lr / (1 + i / k * decay_rate)
self.assertAllClose(decayed_lr(step), expected, 1e-6)
step.assign(step + 1)
def test_staircase(self):
initial_lr = 0.1
k = 10
decay_rate = 0.96
step = backend.Variable(0.0)
decayed_lr = schedules.InverseTimeDecay(
initial_lr, k, decay_rate, staircase=True
)
for i in range(k + 1):
expected = initial_lr / (1 + decay_rate * (i // k))
self.assertAllClose(decayed_lr(step), expected, 1e-6)
step.assign(step + 1)
| InverseTimeDecayTest |
python | crytic__slither | slither/tools/flattening/flattening.py | {
"start": 1619,
"end": 20683
} | class ____:
# pylint: disable=too-many-instance-attributes,too-many-arguments,too-many-locals,too-few-public-methods
def __init__(
self,
compilation_unit: SlitherCompilationUnit,
external_to_public=False,
remove_assert=False,
convert_library_to_internal=False,
private_to_internal=False,
export_path: Optional[str] = None,
pragma_solidity: Optional[str] = None,
):
self._source_codes: Dict[Contract, str] = {}
self._source_codes_top_level: Dict[TopLevel, str] = {}
self._compilation_unit: SlitherCompilationUnit = compilation_unit
self._external_to_public = external_to_public
self._remove_assert = remove_assert
self._use_abi_encoder_v2 = False
self._convert_library_to_internal = convert_library_to_internal
self._private_to_internal = private_to_internal
self._pragma_solidity = pragma_solidity
self._export_path: Path = DEFAULT_EXPORT_PATH if export_path is None else Path(export_path)
self._check_abi_encoder_v2()
for contract in compilation_unit.contracts:
self._get_source_code(contract)
self._get_source_code_top_level(compilation_unit.structures_top_level)
self._get_source_code_top_level(compilation_unit.enums_top_level)
self._get_source_code_top_level(compilation_unit.events_top_level)
self._get_source_code_top_level(compilation_unit.custom_errors)
self._get_source_code_top_level(compilation_unit.variables_top_level)
self._get_source_code_top_level(compilation_unit.functions_top_level)
def _get_source_code_top_level(self, elems: Sequence[TopLevel]) -> None:
for elem in elems:
self._source_codes_top_level[elem] = elem.source_mapping.content
def _check_abi_encoder_v2(self):
"""
Check if ABIEncoderV2 is required
Set _use_abi_encorder_v2
:return:
"""
for p in self._compilation_unit.pragma_directives:
if "ABIEncoderV2" in str(p.directive):
self._use_abi_encoder_v2 = True
return
def _get_source_code(
self, contract: Contract
): # pylint: disable=too-many-branches,too-many-statements
"""
Save the source code of the contract in self._source_codes
Patch the source code
:param contract:
:return:
"""
src_mapping = contract.source_mapping
src_bytes = self._compilation_unit.core.source_code[src_mapping.filename.absolute].encode(
"utf8"
)
to_patch = []
# interface must use external
if self._external_to_public and not contract.is_interface:
for f in contract.functions_declared:
# fallback must be external
if f.is_fallback or f.is_constructor_variables:
continue
if f.visibility == "external":
attributes_start = (
f.parameters_src().source_mapping.start
+ f.parameters_src().source_mapping.length
)
attributes_end = f.returns_src().source_mapping.start
attributes = src_bytes[attributes_start:attributes_end].decode("utf8")
regex = re.search(r"((\sexternal)\s+)|(\sexternal)$|(\)external)$", attributes)
if regex:
to_patch.append(
Patch(
attributes_start + regex.span()[0] + 1,
"public_to_external",
)
)
else:
raise SlitherException(f"External keyword not found {f.name} {attributes}")
for var in f.parameters:
if var.location == "calldata":
calldata_start = var.source_mapping.start
calldata_end = calldata_start + var.source_mapping.length
calldata_idx = src_bytes[calldata_start:calldata_end].find(" calldata ")
to_patch.append(
Patch(
calldata_start + calldata_idx + 1,
"calldata_to_memory",
)
)
if self._convert_library_to_internal and contract.is_library:
for f in contract.functions_declared:
visibility = ""
if f.visibility in ["external", "public"]:
visibility = f.visibility
attributes_start = (
f.parameters_src().source_mapping["start"]
+ f.parameters_src().source_mapping["length"]
)
attributes_end = f.returns_src().source_mapping["start"]
attributes = src_bytes[attributes_start:attributes_end].decode("utf8")
regex = (
re.search(r"((\sexternal)\s+)|(\sexternal)$|(\)external)$", attributes)
if visibility == "external"
else re.search(r"((\spublic)\s+)|(\spublic)$|(\)public)$", attributes)
)
if regex:
to_patch.append(
Patch(
attributes_start + regex.span()[0] + 1,
"external_to_internal"
if visibility == "external"
else "public_to_internal",
)
)
else:
raise SlitherException(
f"{visibility} keyword not found {f.name} {attributes}"
)
if self._private_to_internal:
for variable in contract.state_variables_declared:
if variable.visibility == "private":
attributes_start = variable.source_mapping.start
attributes_end = attributes_start + variable.source_mapping.length
attributes = src_bytes[attributes_start:attributes_end].decode("utf8")
regex = re.search(r" private ", attributes)
if regex:
to_patch.append(
Patch(
attributes_start + regex.span()[0] + 1,
"private_to_internal",
)
)
else:
raise SlitherException(
f"private keyword not found {variable.name} {attributes}"
)
if self._remove_assert:
for function in contract.functions_and_modifiers_declared:
for node in function.nodes:
for ir in node.irs:
if isinstance(ir, SolidityCall) and ir.function == SolidityFunction(
"assert(bool)"
):
to_patch.append(Patch(node.source_mapping.start, "line_removal"))
logger.info(
f"Code commented: {node.expression} ({node.source_mapping})"
)
to_patch.sort(key=lambda x: x.index, reverse=True)
content = src_mapping.content.encode("utf8")
start = src_mapping.start
for patch in to_patch:
patch_type = patch.patch_type
index = patch.index
index = index - start
if patch_type == "public_to_external":
content = (
content[:index].decode("utf8")
+ "public"
+ content[index + len("external") :].decode("utf8")
)
elif patch_type == "external_to_internal":
content = (
content[:index].decode("utf8")
+ "internal"
+ content[index + len("external") :].decode("utf8")
)
elif patch_type == "public_to_internal":
content = (
content[:index].decode("utf8")
+ "internal"
+ content[index + len("public") :].decode("utf8")
)
elif patch_type == "private_to_internal":
content = (
content[:index].decode("utf8")
+ "internal"
+ content[index + len("private") :].decode("utf8")
)
elif patch_type == "calldata_to_memory":
content = (
content[:index].decode("utf8")
+ "memory"
+ content[index + len("calldata") :].decode("utf8")
)
else:
assert patch_type == "line_removal"
content = content[:index].decode("utf8") + " // " + content[index:].decode("utf8")
self._source_codes[contract] = content.decode("utf8")
def _pragmas(self) -> str:
"""
Return the required pragmas
:return:
"""
ret = ""
if self._pragma_solidity:
ret += f"pragma solidity {self._pragma_solidity};\n"
else:
# TODO support multiple compiler version
ret += f"pragma solidity {list(self._compilation_unit.crytic_compile.compilation_units.values())[0].compiler_version.version};\n"
if self._use_abi_encoder_v2:
ret += "pragma experimental ABIEncoderV2;\n"
return ret
def _export_from_type(
self,
t: Type,
contract: Contract,
exported: Set[str],
list_contract: Set[Contract],
list_top_level: Set[TopLevel],
):
if isinstance(t, UserDefinedType):
t_type = t.type
if isinstance(t_type, TopLevel):
list_top_level.add(t_type)
elif isinstance(t_type, (EnumContract, StructureContract)):
if t_type.contract != contract and t_type.contract not in exported:
self._export_list_used_contracts(
t_type.contract, exported, list_contract, list_top_level
)
else:
assert isinstance(t.type, Contract)
if t.type != contract and t.type not in exported:
self._export_list_used_contracts(
t.type, exported, list_contract, list_top_level
)
elif isinstance(t, MappingType):
self._export_from_type(t.type_from, contract, exported, list_contract, list_top_level)
self._export_from_type(t.type_to, contract, exported, list_contract, list_top_level)
elif isinstance(t, ArrayType):
self._export_from_type(t.type, contract, exported, list_contract, list_top_level)
def _export_list_used_contracts( # pylint: disable=too-many-branches
self,
contract: Contract,
exported: Set[str],
list_contract: Set[Contract],
list_top_level: Set[TopLevel],
):
# TODO: investigate why this happen
if not isinstance(contract, Contract):
return
if contract.name in exported:
return
exported.add(contract.name)
for inherited in contract.inheritance:
self._export_list_used_contracts(inherited, exported, list_contract, list_top_level)
# Find all the external contracts called
# High level calls already includes library calls
# We also filter call to itself to avoid infilite loop
externals = list({e[0] for e in contract.all_high_level_calls if e[0] != contract})
for inherited in externals:
self._export_list_used_contracts(inherited, exported, list_contract, list_top_level)
for list_libs in contract.using_for.values():
for lib_candidate_type in list_libs:
if isinstance(lib_candidate_type, UserDefinedType):
lib_candidate = lib_candidate_type.type
if isinstance(lib_candidate, Contract):
self._export_list_used_contracts(
lib_candidate, exported, list_contract, list_top_level
)
# Find all the external contracts use as a base type
local_vars = []
for f in contract.functions_declared:
local_vars += f.variables
for v in contract.variables + local_vars:
self._export_from_type(v.type, contract, exported, list_contract, list_top_level)
for s in contract.structures:
for elem in s.elems.values():
self._export_from_type(elem.type, contract, exported, list_contract, list_top_level)
# Find all convert and "new" operation that can lead to use an external contract
for f in contract.functions_declared:
for ir in f.slithir_operations:
if isinstance(ir, NewContract):
if ir.contract_created != contract and not ir.contract_created in exported:
self._export_list_used_contracts(
ir.contract_created, exported, list_contract, list_top_level
)
if isinstance(ir, TypeConversion):
self._export_from_type(
ir.type, contract, exported, list_contract, list_top_level
)
for read in ir.read:
if isinstance(read, TopLevel):
list_top_level.add(read)
if isinstance(ir, InternalCall) and isinstance(ir.function, FunctionTopLevel):
list_top_level.add(ir.function)
if (
isinstance(ir, SolidityCall)
and isinstance(ir.function, SolidityCustomRevert)
and isinstance(ir.function.custom_error, TopLevel)
):
list_top_level.add(ir.function.custom_error)
list_contract.add(contract)
def _export_contract_with_inheritance(self, contract) -> Export:
list_contracts: Set[Contract] = set() # will contain contract itself
list_top_level: Set[TopLevel] = set()
self._export_list_used_contracts(contract, set(), list_contracts, list_top_level)
path = Path(self._export_path, f"{contract.name}_{uuid.uuid4()}.sol")
content = ""
content += self._pragmas()
for listed_top_level in list_top_level:
content += self._source_codes_top_level[listed_top_level]
content += "\n"
for listed_contract in list_contracts:
content += self._source_codes[listed_contract]
content += "\n"
return Export(filename=path, content=content)
def _export_most_derived(self) -> List[Export]:
ret: List[Export] = []
for contract in self._compilation_unit.contracts_derived:
ret.append(self._export_contract_with_inheritance(contract))
return ret
def _export_all(self) -> List[Export]:
path = Path(self._export_path, "export.sol")
content = ""
content += self._pragmas()
for top_level_content in self._source_codes_top_level.values():
content += "\n"
content += top_level_content
content += "\n"
contract_seen = set()
contract_to_explore = list(self._compilation_unit.contracts)
# We only need the inheritance order here, as solc can compile
# a contract that use another contract type (ex: state variable) that he has not seen yet
while contract_to_explore:
next_to_explore = contract_to_explore.pop(0)
if not next_to_explore.inheritance or all(
(father in contract_seen for father in next_to_explore.inheritance)
):
content += "\n"
content += self._source_codes[next_to_explore]
content += "\n"
contract_seen.add(next_to_explore)
else:
contract_to_explore.append(next_to_explore)
return [Export(filename=path, content=content)]
def _export_with_import(self) -> List[Export]:
exports: List[Export] = []
for contract in self._compilation_unit.contracts:
list_contracts: Set[Contract] = set() # will contain contract itself
list_top_level: Set[TopLevel] = set()
self._export_list_used_contracts(contract, set(), list_contracts, list_top_level)
if list_top_level:
logger.info(
"Top level objects are not yet supported with the local import flattening"
)
for elem in list_top_level:
logger.info(f"Missing {elem} for {contract.name}")
path = Path(self._export_path, f"{contract.name}.sol")
content = ""
content += self._pragmas()
for used_contract in list_contracts:
if used_contract != contract:
content += f"import './{used_contract.name}.sol';\n"
content += "\n"
content += self._source_codes[contract]
content += "\n"
exports.append(Export(filename=path, content=content))
return exports
def export( # pylint: disable=too-many-arguments,too-few-public-methods
self,
strategy: Strategy,
target: Optional[str] = None,
json: Optional[str] = None,
zip: Optional[str] = None, # pylint: disable=redefined-builtin
zip_type: Optional[str] = None,
):
if not self._export_path.exists():
self._export_path.mkdir(parents=True)
exports: List[Export] = []
if target is None:
if strategy == Strategy.MostDerived:
exports = self._export_most_derived()
elif strategy == Strategy.OneFile:
exports = self._export_all()
elif strategy == Strategy.LocalImport:
exports = self._export_with_import()
else:
contracts = self._compilation_unit.get_contract_from_name(target)
if len(contracts) == 0:
logger.error(f"{target} not found")
return
exports = []
for contract in contracts:
exports.append(self._export_contract_with_inheritance(contract))
if json:
export_as_json(exports, json)
elif zip:
save_to_zip(exports, zip, zip_type)
else:
save_to_disk(exports)
| Flattening |
python | getsentry__sentry | src/sentry/snuba/sessions_v2.py | {
"start": 2729,
"end": 2882
} | class ____(Protocol):
def extract_from_row(self, row, group) -> float | None: ...
def get_snuba_columns(self, raw_groupby) -> list[str]: ...
| _Field |
python | ray-project__ray | python/ray/serve/_private/handle_options.py | {
"start": 1802,
"end": 2263
} | class ____(DynamicHandleOptionsBase):
_by_reference: bool = True
def copy_and_update(self, **kwargs) -> "DynamicHandleOptions":
new_kwargs = {}
for f in fields(self):
if f.name not in kwargs or kwargs[f.name] == DEFAULT.VALUE:
new_kwargs[f.name] = getattr(self, f.name)
else:
new_kwargs[f.name] = kwargs[f.name]
return DynamicHandleOptions(**new_kwargs)
| DynamicHandleOptions |
python | getsentry__sentry | src/sentry/search/snuba/executors.py | {
"start": 1882,
"end": 2295
} | class ____(TypedDict):
log_level: int
has_stacktrace: int
relative_volume: int
event_halflife_hours: int
issue_halflife_hours: int
v2: bool
norm: bool
DEFAULT_TRENDS_WEIGHTS: TrendsSortWeights = {
"log_level": 0,
"has_stacktrace": 0,
"relative_volume": 1,
"event_halflife_hours": 4,
"issue_halflife_hours": 12,
"v2": True,
"norm": False,
}
| TrendsSortWeights |
python | paramiko__paramiko | paramiko/client.py | {
"start": 33409,
"end": 33926
} | class ____(MissingHostKeyPolicy):
"""
Policy for automatically rejecting the unknown hostname & key. This is
used by `.SSHClient`.
"""
def missing_host_key(self, client, hostname, key):
client._log(
DEBUG,
"Rejecting {} host key for {}: {}".format(
key.get_name(), hostname, hexlify(key.get_fingerprint())
),
)
raise SSHException(
"Server {!r} not found in known_hosts".format(hostname)
)
| RejectPolicy |
python | kamyu104__LeetCode-Solutions | Python/minimize-rounding-error-to-meet-target.py | {
"start": 68,
"end": 1957
} | class ____(object):
def minimizeError(self, prices, target):
"""
:type prices: List[str]
:type target: int
:rtype: str
"""
def kthElement(nums, k, compare=lambda a, b: a < b):
def PartitionAroundPivot(left, right, pivot_idx, nums, compare):
new_pivot_idx = left
nums[pivot_idx], nums[right] = nums[right], nums[pivot_idx]
for i in xrange(left, right):
if compare(nums[i], nums[right]):
nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
new_pivot_idx += 1
nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
return new_pivot_idx
left, right = 0, len(nums) - 1
while left <= right:
pivot_idx = random.randint(left, right)
new_pivot_idx = PartitionAroundPivot(left, right, pivot_idx, nums, compare)
if new_pivot_idx == k:
return
elif new_pivot_idx > k:
right = new_pivot_idx - 1
else: # new_pivot_idx < k.
left = new_pivot_idx + 1
errors = []
lower, upper = 0, 0
for i, p in enumerate(map(float, prices)):
lower += int(math.floor(p))
upper += int(math.ceil(p))
if p != math.floor(p):
errors.append(p-math.floor(p))
if not lower <= target <= upper:
return "-1"
lower_round_count = upper-target
kthElement(errors, lower_round_count)
result = 0.0
for i in xrange(len(errors)):
if i < lower_round_count:
result += errors[i]
else:
result += 1.0-errors[i]
return "{:.3f}".format(result)
| Solution |
python | google__pytype | pytype/overlays/named_tuple.py | {
"start": 8077,
"end": 11357
} | class ____(_NamedTupleBuilderBase):
"""Factory for creating typing.NamedTuples via the function constructor."""
_fields_param: error_types.BadType
@classmethod
def make(cls, ctx):
# typing.pytd contains a NamedTuple class def and a _NamedTuple func def.
self = super().make("NamedTuple", ctx, "typing", pyval_name="_NamedTuple")
# NamedTuple's fields arg has type Sequence[Sequence[Union[str, type]]],
# which doesn't provide precise enough type-checking, so we have to do
# some of our own in _getargs. _NamedTupleFields is an alias to
# List[Tuple[str, type]], which gives a more understandable error message.
fields_pyval = ctx.loader.lookup_pytd("typing", "_NamedTupleFields").type
fields_type = ctx.convert.constant_to_value(fields_pyval, {}, ctx.root_node)
# pylint: disable=protected-access
self._fields_param = error_types.BadType(name="fields", typ=fields_type)
return self
def _is_str_instance(self, val):
return isinstance(val, abstract.Instance) and val.full_name in (
"builtins.str",
"builtins.unicode",
)
def extract_args(self, node, callargs):
"""Extracts the typename and fields arguments.
fields is postprocessed into field_names and field_types.
typing.NamedTuple doesn't support rename, it will default to False
"""
cls_name = callargs["typename"]
fields = callargs["fields"]
if isinstance(fields, str):
# Since str matches Sequence, we have to manually check for it.
raise _FieldMatchError(self._fields_param)
# The fields is a list of tuples, so we need to deeply unwrap them.
fields = [abstract_utils.get_atomic_python_constant(t) for t in fields]
# We need the actual string for the field names and the BaseValue
# for the field types.
names = []
types = []
for field in fields:
if isinstance(field, str):
# Since str matches Sequence, we have to manually check for it.
raise _FieldMatchError(self._fields_param)
if len(field) != 2 or any(
not self._is_str_instance(v) for v in field[0].data
):
# Note that we don't need to check field[1] because both 'str'
# (forward reference) and 'type' are valid for it.
raise _FieldMatchError(self._fields_param)
name, typ = field
name_py_constant = abstract_utils.get_atomic_python_constant(name)
names.append(name_py_constant)
annot = self.ctx.annotation_utils.extract_annotation(
node,
typ,
name_py_constant,
self.ctx.vm.simple_stack(),
allowed_type_params=set(),
)
types.append(annot)
return _Args(name=cls_name, field_names=names, field_types=types)
def call(self, node, func, args, alias_map=None):
try:
args, props = self.process_args(node, args)
except _ArgsError:
return node, self.ctx.new_unsolvable(node)
# fill in field types from annotations
annots = self.ctx.annotation_utils.convert_annotations_list(
node, zip(args.field_names, args.field_types)
)
for f in props.fields:
f.typ = annots.get(f.name, self.ctx.convert.unsolvable)
node, cls_var = _build_namedtuple(props, node, self.ctx)
return node, cls_var
| NamedTupleFuncBuilder |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/ext.py | {
"start": 4050,
"end": 10323
} | class ____(ColumnCollectionConstraint):
"""A table-level EXCLUDE constraint.
Defines an EXCLUDE constraint as described in the `PostgreSQL
documentation`__.
__ https://www.postgresql.org/docs/current/static/sql-createtable.html#SQL-CREATETABLE-EXCLUDE
""" # noqa
__visit_name__ = "exclude_constraint"
where = None
inherit_cache = False
create_drop_stringify_dialect = "postgresql"
@elements._document_text_coercion(
"where",
":class:`.ExcludeConstraint`",
":paramref:`.ExcludeConstraint.where`",
)
def __init__(self, *elements, **kw):
r"""
Create an :class:`.ExcludeConstraint` object.
E.g.::
const = ExcludeConstraint(
(Column("period"), "&&"),
(Column("group"), "="),
where=(Column("group") != "some group"),
ops={"group": "my_operator_class"},
)
The constraint is normally embedded into the :class:`_schema.Table`
construct
directly, or added later using :meth:`.append_constraint`::
some_table = Table(
"some_table",
metadata,
Column("id", Integer, primary_key=True),
Column("period", TSRANGE()),
Column("group", String),
)
some_table.append_constraint(
ExcludeConstraint(
(some_table.c.period, "&&"),
(some_table.c.group, "="),
where=some_table.c.group != "some group",
name="some_table_excl_const",
ops={"group": "my_operator_class"},
)
)
The exclude constraint defined in this example requires the
``btree_gist`` extension, that can be created using the
command ``CREATE EXTENSION btree_gist;``.
:param \*elements:
A sequence of two tuples of the form ``(column, operator)`` where
"column" is either a :class:`_schema.Column` object, or a SQL
expression element (e.g. ``func.int8range(table.from, table.to)``)
or the name of a column as string, and "operator" is a string
containing the operator to use (e.g. `"&&"` or `"="`).
In order to specify a column name when a :class:`_schema.Column`
object is not available, while ensuring
that any necessary quoting rules take effect, an ad-hoc
:class:`_schema.Column` or :func:`_expression.column`
object should be used.
The ``column`` may also be a string SQL expression when
passed as :func:`_expression.literal_column` or
:func:`_expression.text`
:param name:
Optional, the in-database name of this constraint.
:param deferrable:
Optional bool. If set, emit DEFERRABLE or NOT DEFERRABLE when
issuing DDL for this constraint.
:param initially:
Optional string. If set, emit INITIALLY <value> when issuing DDL
for this constraint.
:param using:
Optional string. If set, emit USING <index_method> when issuing DDL
for this constraint. Defaults to 'gist'.
:param where:
Optional SQL expression construct or literal SQL string.
If set, emit WHERE <predicate> when issuing DDL
for this constraint.
:param ops:
Optional dictionary. Used to define operator classes for the
elements; works the same way as that of the
:ref:`postgresql_ops <postgresql_operator_classes>`
parameter specified to the :class:`_schema.Index` construct.
.. seealso::
:ref:`postgresql_operator_classes` - general description of how
PostgreSQL operator classes are specified.
"""
columns = []
render_exprs = []
self.operators = {}
expressions, operators = zip(*elements)
for (expr, column, strname, add_element), operator in zip(
coercions.expect_col_expression_collection(
roles.DDLConstraintColumnRole, expressions
),
operators,
):
if add_element is not None:
columns.append(add_element)
name = column.name if column is not None else strname
if name is not None:
# backwards compat
self.operators[name] = operator
render_exprs.append((expr, name, operator))
self._render_exprs = render_exprs
ColumnCollectionConstraint.__init__(
self,
*columns,
name=kw.get("name"),
deferrable=kw.get("deferrable"),
initially=kw.get("initially"),
)
self.using = kw.get("using", "gist")
where = kw.get("where")
if where is not None:
self.where = coercions.expect(roles.StatementOptionRole, where)
self.ops = kw.get("ops", {})
def _set_parent(self, table, **kw):
super()._set_parent(table)
self._render_exprs = [
(
expr if not isinstance(expr, str) else table.c[expr],
name,
operator,
)
for expr, name, operator in (self._render_exprs)
]
def _copy(self, target_table=None, **kw):
elements = [
(
schema._copy_expression(expr, self.parent, target_table),
operator,
)
for expr, _, operator in self._render_exprs
]
c = self.__class__(
*elements,
name=self.name,
deferrable=self.deferrable,
initially=self.initially,
where=self.where,
using=self.using,
)
c.dispatch._update(self.dispatch)
return c
def array_agg(*arg, **kw):
"""PostgreSQL-specific form of :class:`_functions.array_agg`, ensures
return type is :class:`_postgresql.ARRAY` and not
the plain :class:`_types.ARRAY`, unless an explicit ``type_``
is passed.
"""
kw["_default_array_type"] = ARRAY
return functions.func.array_agg(*arg, **kw)
| ExcludeConstraint |
python | ansible__ansible | test/lib/ansible_test/_internal/config.py | {
"start": 11596,
"end": 11854
} | class ____(IntegrationConfig):
"""Configuration for the network integration command."""
def __init__(self, args: t.Any) -> None:
super().__init__(args, 'network-integration')
self.testcase: str = args.testcase
| NetworkIntegrationConfig |
python | astropy__astropy | astropy/modeling/projections.py | {
"start": 22743,
"end": 23016
} | class ____(Pix2SkyProjection, Cylindrical):
r"""
Mercator - pixel to sky.
Corresponds to the ``MER`` projection in FITS WCS.
.. math::
\phi &= x \\
\theta &= 2 \tan^{-1}\left(e^{y \pi / 180^{\circ}}\right)-90^{\circ}
"""
| Pix2Sky_Mercator |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/roots/mutation.py | {
"start": 34046,
"end": 34836
} | class ____(graphene.Mutation):
"""Frees concurrency slots."""
Output = graphene.NonNull(graphene.Boolean)
class Meta:
name = "FreeConcurrencySlotsMutation"
class Arguments:
runId = graphene.Argument(graphene.NonNull(graphene.String))
stepKey = graphene.Argument(graphene.String)
@capture_error
@check_permission(Permissions.EDIT_CONCURRENCY_LIMIT)
def mutate(self, graphene_info, runId: str, stepKey: Optional[str] = None):
event_log_storage = graphene_info.context.instance.event_log_storage
if stepKey:
event_log_storage.free_concurrency_slot_for_step(runId, stepKey)
else:
event_log_storage.free_concurrency_slots_for_run(runId)
return True
| GrapheneFreeConcurrencySlotsMutation |
python | huggingface__transformers | src/transformers/models/speech_to_text/feature_extraction_speech_to_text.py | {
"start": 1126,
"end": 13888
} | class ____(SequenceFeatureExtractor):
r"""
Constructs a Speech2Text feature extractor.
This feature extractor inherits from [`Speech2TextFeatureExtractor`] which contains most of the main methods. Users
should refer to this superclass for more information regarding those methods.
This class extracts mel-filter bank features from raw speech using TorchAudio if installed or using numpy
otherwise, and applies utterance-level cepstral mean and variance normalization to the extracted features.
Args:
feature_size (`int`, *optional*, defaults to 80):
The feature dimension of the extracted features.
sampling_rate (`int`, *optional*, defaults to 16000):
The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
num_mel_bins (`int`, *optional*, defaults to 80):
Number of Mel-frequency bins.
padding_value (`float`, *optional*, defaults to 0.0):
The value that is used to fill the padding vectors.
dither (`float`, *optional*, defaults to 0.0):
Adds dithering. In other words, adds a small Gaussian noise to each frame.
E.g. use 4.0 to add dithering with a normal distribution centered
around 0.0 with standard deviation 4.0 (assuming [-32k,+32k] range of kaldi waveform).
The value 0.0 means no dithering.
Dithering has similar effect as `mel_floor`. It reduces the high log_mel_fbank
values for signals with hard-zero sections, when VAD cutoff is present in the signal.
do_ceptral_normalize (`bool`, *optional*, defaults to `True`):
Whether or not to apply utterance-level cepstral mean and variance normalization to extracted features.
normalize_means (`bool`, *optional*, defaults to `True`):
Whether or not to zero-mean normalize the extracted features.
normalize_vars (`bool`, *optional*, defaults to `True`):
Whether or not to unit-variance normalize the extracted features.
"""
model_input_names = ["input_features", "attention_mask"]
def __init__(
self,
feature_size=80,
sampling_rate=16000,
num_mel_bins=80,
padding_value=0.0,
dither=0.0,
do_ceptral_normalize=True,
normalize_means=True,
normalize_vars=True,
**kwargs,
):
super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
self.num_mel_bins = num_mel_bins
self.dither = dither
self.do_ceptral_normalize = do_ceptral_normalize
self.normalize_means = normalize_means
self.normalize_vars = normalize_vars
self.return_attention_mask = True
if not is_speech_available():
mel_filters = mel_filter_bank(
num_frequency_bins=257,
num_mel_filters=self.num_mel_bins,
min_frequency=20,
max_frequency=sampling_rate // 2,
sampling_rate=sampling_rate,
norm=None,
mel_scale="kaldi",
triangularize_in_mel_space=True,
)
self.mel_filters = mel_filters
self.window = window_function(400, "povey", periodic=False)
def _extract_fbank_features(
self,
waveform: np.ndarray,
) -> np.ndarray:
"""
Get mel-filter bank features using TorchAudio. Note that TorchAudio requires 16-bit signed integers as inputs
and hence the waveform should not be normalized before feature extraction.
"""
waveform = waveform * (2**15) # Kaldi compliance: 16-bit signed integers
if is_speech_available():
waveform = torch.from_numpy(waveform).unsqueeze(0)
features = ta_kaldi.fbank(
waveform,
dither=self.dither,
num_mel_bins=self.num_mel_bins,
sample_frequency=self.sampling_rate,
)
features = features.numpy()
else:
waveform = np.squeeze(waveform)
features = spectrogram(
waveform,
self.window,
frame_length=400,
hop_length=160,
fft_length=512,
power=2.0,
center=False,
dither=self.dither,
preemphasis=0.97,
mel_filters=self.mel_filters,
log_mel="log",
mel_floor=1.192092955078125e-07,
remove_dc_offset=True,
).T
return features
@staticmethod
def utterance_cmvn(
x: np.ndarray,
input_length: int,
normalize_means: Optional[bool] = True,
normalize_vars: Optional[bool] = True,
padding_value: float = 0.0,
) -> np.ndarray:
# make sure we normalize float32 arrays
if normalize_means:
mean = x[:input_length].mean(axis=0)
x = np.subtract(x, mean)
if normalize_vars:
std = x[:input_length].std(axis=0)
x = np.divide(x, std)
if input_length < x.shape[0]:
x[input_length:] = padding_value
# make sure array is in float32
x = x.astype(np.float32)
return x
def normalize(
self, input_features: list[np.ndarray], attention_mask: Optional[np.ndarray] = None
) -> list[np.ndarray]:
lengths = attention_mask.sum(-1) if attention_mask is not None else [x.shape[0] for x in input_features]
return [
self.utterance_cmvn(x, n, self.normalize_means, self.normalize_vars, self.padding_value)
for x, n in zip(input_features, lengths)
]
def __call__(
self,
raw_speech: Union[np.ndarray, list[float], list[np.ndarray], list[list[float]]],
padding: Union[bool, str, PaddingStrategy] = False,
max_length: Optional[int] = None,
truncation: bool = False,
pad_to_multiple_of: Optional[int] = None,
return_tensors: Optional[Union[str, TensorType]] = None,
sampling_rate: Optional[int] = None,
return_attention_mask: Optional[bool] = None,
**kwargs,
) -> BatchFeature:
"""
Main method to featurize and prepare for the model one or several sequence(s).
Args:
raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
stereo, i.e. single float per timestep.
padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
Select a strategy to pad the returned sequences (according to the model's padding side and padding
index) among:
- `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
sequence if provided).
- `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
acceptable input length for the model if that argument is not provided.
- `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
lengths).
max_length (`int`, *optional*):
Maximum length of the returned list and optionally padding length (see above).
truncation (`bool`):
Activates truncation to cut input sequences longer than *max_length* to *max_length*.
pad_to_multiple_of (`int`, *optional*):
If set will pad the sequence to a multiple of the provided value.
This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
`>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
return_attention_mask (`bool`, *optional*):
Whether to return the attention mask. If left to the default, will return the attention mask according
to the specific feature_extractor's default.
[What are attention masks?](../glossary#attention-mask)
<Tip>
For Speech2TextTransformer models, `attention_mask` should always be passed for batched inference, to
avoid subtle bugs.
</Tip>
return_tensors (`str` or [`~utils.TensorType`], *optional*):
If set, will return tensors instead of list of python integers. Acceptable values are:
- `'pt'`: Return PyTorch `torch.Tensor` objects.
- `'np'`: Return Numpy `np.ndarray` objects.
sampling_rate (`int`, *optional*):
The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
`sampling_rate` at the forward call to prevent silent errors.
padding_value (`float`, *optional*, defaults to 0.0):
The value that is used to fill the padding values / vectors.
"""
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"
f" {self.sampling_rate} and not {sampling_rate}."
)
else:
logger.warning(
f"It is strongly recommended to pass the `sampling_rate` argument to `{self.__class__.__name__}()`. "
"Failing to do so can result in silent errors that might be hard to debug."
)
is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
if is_batched_numpy and len(raw_speech.shape) > 2:
raise ValueError(f"Only mono-channel audio is supported for input to {self}")
is_batched = is_batched_numpy or (
isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
)
if is_batched:
raw_speech = [np.asarray(speech, dtype=np.float32) for speech in raw_speech]
elif not is_batched and not isinstance(raw_speech, np.ndarray):
raw_speech = np.asarray(raw_speech, dtype=np.float32)
elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
raw_speech = raw_speech.astype(np.float32)
# always return batch
if not is_batched:
raw_speech = [raw_speech]
# extract fbank features
features = [self._extract_fbank_features(waveform) for waveform in raw_speech]
# convert into correct format for padding
encoded_inputs = BatchFeature({"input_features": features})
padded_inputs = self.pad(
encoded_inputs,
padding=padding,
max_length=max_length,
truncation=truncation,
pad_to_multiple_of=pad_to_multiple_of,
return_attention_mask=return_attention_mask,
**kwargs,
)
# make sure list is in array format
input_features = padded_inputs.get("input_features")
if isinstance(input_features[0], list):
padded_inputs["input_features"] = [np.asarray(feature, dtype=np.float32) for feature in input_features]
attention_mask = padded_inputs.get("attention_mask")
if attention_mask is not None:
padded_inputs["attention_mask"] = [np.asarray(array, dtype=np.int32) for array in attention_mask]
# Utterance-level cepstral mean and variance normalization
if self.do_ceptral_normalize:
attention_mask = (
np.array(attention_mask, dtype=np.int32)
if self._get_padding_strategies(padding, max_length=max_length) is not PaddingStrategy.DO_NOT_PAD
else None
)
padded_inputs["input_features"] = self.normalize(
padded_inputs["input_features"], attention_mask=attention_mask
)
if return_tensors is not None:
padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
return padded_inputs
__all__ = ["Speech2TextFeatureExtractor"]
| Speech2TextFeatureExtractor |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-google-sheets/destination_google_sheets/writer.py | {
"start": 219,
"end": 5205
} | class ____(WriteBufferMixin):
def __init__(self, spreadsheet: GoogleSheets):
self.spreadsheet = spreadsheet
super().__init__()
def delete_stream_entries(self, stream_name: str):
"""
Deletes all the records belonging to the input stream.
"""
self.spreadsheet.clean_worksheet(stream_name)
def check_headers(self, stream_name: str):
"""
Checks whether data headers belonging to the input stream are set.
"""
stream = self.stream_info[stream_name]
if not stream["is_set"]:
self.spreadsheet.set_headers(stream_name, stream["headers"])
self.stream_info[stream_name]["is_set"] = True
def queue_write_operation(self, stream_name: str):
"""
Mimics `batch_write` operation using records_buffer.
1) gets data from the records_buffer, with respect to the size of the records_buffer (records count or size in Kb)
2) writes it to the target worksheet
3) cleans-up the records_buffer belonging to input stream
"""
# get the size of records_buffer for target stream in Kb
# TODO unit test flush triggers
records_buffer_size_in_kb = self.records_buffer[stream_name].__sizeof__() / 1024
if len(self.records_buffer[stream_name]) == self.flush_interval or records_buffer_size_in_kb > self.flush_interval_size_in_kb:
self.write_from_queue(stream_name)
self.clear_buffer(stream_name)
def write_from_queue(self, stream_name: str):
"""
Writes data from records_buffer for belonging to the input stream.
1) checks the headers are set
2) gets the values from the records_buffer
3) if there are records to write - writes them to the target worksheet
"""
self.check_headers(stream_name)
values: list = self.records_buffer[stream_name] or []
if values:
stream: Worksheet = self.spreadsheet.open_worksheet(stream_name)
self.logger.info(f"Writing data for stream: {stream_name}")
# we start from the cell of `A2` as starting range to fill the spreadsheet
values = [
[self._truncate_cell(val, row_idx, col_idx) for col_idx, val in enumerate(row)] for row_idx, row in enumerate(values, 1)
]
stream.append_table(values, start="A2", dimension="ROWS")
else:
self.logger.info(f"Skipping empty stream: {stream_name}")
def _truncate_cell(self, value: str, row_idx: int, col_idx: int) -> str:
"""
Truncates the input string if it exceeds the Google Sheets cell limit (50,000 characters).
Adds a '...[TRUNCATED]' suffix to indicate data loss and logs the truncation with cell location.
"""
max_len = 50_000
suffix = "...[TRUNCATED]"
if len(value) > max_len:
a1_notation = self._a1_notation(row_idx, col_idx)
self.logger.warn(f"Truncated cell at {a1_notation} to {max_len} characters.")
return value[: max_len - len(suffix)] + suffix
return value
def _a1_notation(self, row: int, col: int) -> str:
"""
Converts zero-based row and column indexes to A1 notation.
For example, (0, 0) -> 'A1', (1, 1) -> 'B2', (0, 26) -> 'AA1'.
"""
col += 1
row += 1
col_letter = ""
while col:
col, rem = divmod(col - 1, 26)
col_letter = f"{chr(65 + rem)}{col_letter}"
return f"{col_letter}{row}"
def write_whats_left(self):
"""
Stands for writing records that are still left to be written,
but don't match the condition for `queue_write_operation`.
"""
for stream_name in self.records_buffer:
self.write_from_queue(stream_name)
self.clear_buffer(stream_name)
def deduplicate_records(self, configured_stream: AirbyteStream):
"""
Finds and removes duplicated records for target stream, using `primary_key`.
Processing the worksheet happens offline and sync it afterwards to reduce API calls rate
If rate limits are hit while deduplicating, it will be handeled automatically, the operation continues after backoff.
"""
primary_key: str = configured_stream.primary_key[0][0]
stream_name: str = configured_stream.stream.name
stream: Worksheet = self.spreadsheet.open_worksheet(stream_name)
rows_to_remove: list = self.spreadsheet.find_duplicates(stream, primary_key)
if rows_to_remove:
self.logger.info(f"Duplicated records are found for stream: {stream_name}, resolving...")
self.spreadsheet.remove_duplicates(stream, rows_to_remove)
self.logger.info(f"Finished deduplicating records for stream: {stream_name}")
else:
self.logger.info(f"No duplicated records found for stream: {stream_name}")
| GoogleSheetsWriter |
python | ansible__ansible | test/lib/ansible_test/_internal/config.py | {
"start": 6975,
"end": 8091
} | class ____(EnvironmentConfig):
"""Configuration common to all test commands."""
def __init__(self, args: t.Any, command: str) -> None:
super().__init__(args, command)
self.coverage: bool = args.coverage
self.coverage_check: bool = args.coverage_check
self.include: list[str] = args.include or []
self.exclude: list[str] = args.exclude or []
self.require: list[str] = args.require or []
self.changed: bool = args.changed
self.tracked: bool = args.tracked
self.untracked: bool = args.untracked
self.committed: bool = args.committed
self.staged: bool = args.staged
self.unstaged: bool = args.unstaged
self.changed_from: str = args.changed_from
self.changed_path: list[str] = args.changed_path
self.base_branch: str = args.base_branch
self.lint: bool = getattr(args, 'lint', False)
self.junit: bool = getattr(args, 'junit', False)
self.failure_ok: bool = getattr(args, 'failure_ok', False)
if self.coverage_check:
self.coverage = True
| TestConfig |
python | django-haystack__django-haystack | test_haystack/test_utils.py | {
"start": 301,
"end": 746
} | class ____(TestCase):
def test_get_facet_field_name(self):
self.assertEqual(get_facet_field_name("id"), "id")
self.assertEqual(get_facet_field_name("django_id"), "django_id")
self.assertEqual(get_facet_field_name("django_ct"), "django_ct")
self.assertEqual(get_facet_field_name("author"), "author_exact")
self.assertEqual(get_facet_field_name("author_exact"), "author_exact_exact")
| GetIdentifierTestCase |
python | getsentry__sentry-python | sentry_sdk/integrations/starlite.py | {
"start": 1519,
"end": 1783
} | class ____(Integration):
identifier = "starlite"
origin = f"auto.http.{identifier}"
@staticmethod
def setup_once():
# type: () -> None
patch_app_init()
patch_middlewares()
patch_http_route_handle()
| StarliteIntegration |
python | kamyu104__LeetCode-Solutions | Python/minimum-absolute-difference-between-elements-with-constraint.py | {
"start": 104,
"end": 615
} | class ____(object):
def minAbsoluteDifference(self, nums, x):
"""
:type nums: List[int]
:type x: int
:rtype: int
"""
result = float("inf")
sl = SortedList()
for i in xrange(x, len(nums)):
sl.add(nums[i-x])
j = sl.bisect_left(nums[i])
if j-1 >= 0:
result = min(result, nums[i]-sl[j-1])
if j < len(sl):
result = min(result, sl[j]-nums[i])
return result
| Solution |
python | spyder-ide__spyder | external-deps/spyder-remote-services/spyder_remote_services/services/files/handlers.py | {
"start": 6910,
"end": 7235
} | class ____(BaseFSHandler):
@web.authenticated
@authorized
def delete(self):
path = self.get_path_argument("path")
missing_ok = (self.get_argument("missing_ok", "false").lower() == "true")
result = self.fs_rm_file(path, missing_ok=missing_ok)
self.write_json(result)
| RemoveFileHandler |
python | pytorch__pytorch | torch/_dynamo/variables/functions.py | {
"start": 110139,
"end": 111659
} | class ____(UserFunctionVariable):
"""
`torch.utils._pytree._get_node_type` function is very hot function. We want to special case it to reduce Dynamo tracing time.
def _get_node_type(tree: Any) -> Any:
node_type = type(tree)
# All namedtuple types are implicitly registered as pytree nodes.
# XXX: Other parts of the codebase expect namedtuple types always return
# `namedtuple` instead of the actual namedtuple type. Even if the type
# is explicitly registered.
if is_namedtuple_class(node_type):
return namedtuple
return node_type
"""
def call_function(
self,
tx: "InstructionTranslator",
args: Sequence[VariableTracker],
kwargs: dict[str, VariableTracker],
) -> VariableTracker:
if len(args) != 1:
raise_type_error_exc(
tx,
f"pytree_get_node_type requires exactly 1 argument, got {len(args)}",
)
type_source = None
if args[0].source:
install_guard(args[0].source.make_guard(GuardBuilder.TYPE_MATCH))
type_source = TypeSource(args[0].source)
python_type = args[0].python_type()
if is_namedtuple_class(python_type):
type_source = AttrSource(CollectionsSource(), "namedtuple")
return VariableTracker.build(tx, namedtuple, type_source)
return VariableTracker.build(tx, python_type, source=type_source)
| PyTreeGetNodeTypeFunctionVariable |
python | apache__airflow | providers/standard/src/airflow/providers/standard/hooks/subprocess.py | {
"start": 1605,
"end": 4667
} | class ____(BaseHook):
"""Hook for running processes with the ``subprocess`` module."""
def __init__(self, **kwargs) -> None:
self.sub_process: Popen[bytes] | None = None
super().__init__(**kwargs)
def run_command(
self,
command: list[str],
env: dict[str, str] | None = None,
output_encoding: str = "utf-8",
cwd: str | None = None,
) -> SubprocessResult:
"""
Execute the command.
If ``cwd`` is None, execute the command in a temporary directory which will be cleaned afterwards.
If ``env`` is not supplied, ``os.environ`` is passed
:param command: the command to run
:param env: Optional dict containing environment variables to be made available to the shell
environment in which ``command`` will be executed. If omitted, ``os.environ`` will be used.
Note, that in case you have Sentry configured, original variables from the environment
will also be passed to the subprocess with ``SUBPROCESS_`` prefix. See:
https://airflow.apache.org/docs/apache-airflow/stable/administration-and-deployment/logging-monitoring/errors.html for details.
:param output_encoding: encoding to use for decoding stdout
:param cwd: Working directory to run the command in.
If None (default), the command is run in a temporary directory.
:return: :class:`namedtuple` containing ``exit_code`` and ``output``, the last line from stderr
or stdout
"""
self.log.info("Tmp dir root location: %s", gettempdir())
with working_directory(cwd=cwd) as cwd:
self.log.info("Running command: %s", command)
self.sub_process = Popen(
command,
stdout=PIPE,
stderr=STDOUT,
cwd=cwd,
env=env if env or env == {} else os.environ,
start_new_session=True,
restore_signals=True,
)
self.log.info("Output:")
line = ""
if self.sub_process is None:
raise RuntimeError("The subprocess should be created here and is None!")
if self.sub_process.stdout is not None:
for raw_line in iter(self.sub_process.stdout.readline, b""):
line = raw_line.decode(output_encoding, errors="backslashreplace").rstrip()
self.log.info("%s", line)
self.sub_process.wait()
self.log.info("Command exited with return code %s", self.sub_process.returncode)
return_code: int = self.sub_process.returncode
return SubprocessResult(exit_code=return_code, output=line)
def send_sigterm(self):
"""Send SIGTERM signal to ``self.sub_process`` if one exists."""
self.log.info("Sending SIGTERM signal to process group")
if self.sub_process and hasattr(self.sub_process, "pid"):
os.killpg(os.getpgid(self.sub_process.pid), signal.SIGTERM)
| SubprocessHook |
python | lazyprogrammer__machine_learning_examples | ab_testing/epsilon_greedy.py | {
"start": 505,
"end": 2458
} | class ____:
def __init__(self, p):
# p: the win rate
self.p = p
self.p_estimate = 0.
self.N = 0. # num samples collected so far
def pull(self):
# draw a 1 with probability p
return np.random.random() < self.p
def update(self, x):
self.N += 1.
self.p_estimate = ((self.N - 1)*self.p_estimate + x) / self.N
def choose_random_argmax(a):
idx = np.argwhere(np.amax(a) == a).flatten()
return np.random.choice(idx)
def experiment():
bandits = [BanditArm(p) for p in BANDIT_PROBABILITIES]
rewards = np.zeros(NUM_TRIALS)
num_times_explored = 0
num_times_exploited = 0
num_optimal = 0
optimal_j = np.argmax([b.p for b in bandits])
print("optimal j:", optimal_j)
for i in range(NUM_TRIALS):
# use epsilon-greedy to select the next bandit
if np.random.random() < EPS:
num_times_explored += 1
j = np.random.randint(len(bandits))
else:
num_times_exploited += 1
j = choose_random_argmax([b.p_estimate for b in bandits])
if j == optimal_j:
num_optimal += 1
# pull the arm for the bandit with the largest sample
x = bandits[j].pull()
# update rewards log
rewards[i] = x
# update the distribution for the bandit whose arm we just pulled
bandits[j].update(x)
# print mean estimates for each bandit
for b in bandits:
print("mean estimate:", b.p_estimate)
# print total reward
print("total reward earned:", rewards.sum())
print("overall win rate:", rewards.sum() / NUM_TRIALS)
print("num_times_explored:", num_times_explored)
print("num_times_exploited:", num_times_exploited)
print("num times selected optimal bandit:", num_optimal)
# plot the results
cumulative_rewards = np.cumsum(rewards)
win_rates = cumulative_rewards / (np.arange(NUM_TRIALS) + 1)
plt.plot(win_rates)
plt.plot(np.ones(NUM_TRIALS)*np.max(BANDIT_PROBABILITIES))
plt.show()
if __name__ == "__main__":
experiment()
| BanditArm |
python | huggingface__transformers | tests/models/longcat_flash/test_modeling_longcat_flash.py | {
"start": 7446,
"end": 13233
} | class ____(CausalLMModelTest, unittest.TestCase):
model_split_percents = [0.5, 0.8]
model_tester_class = LongcatFlashModelTester
@unittest.skip("LongcatFlash buffers include complex numbers, which breaks this test")
def test_save_load_fast_init_from_base(self):
pass
@unittest.skip("LongcatFlash buffers include complex numbers, which breaks this test")
def test_save_load_fast_init_to_base(self):
pass
def _check_past_key_values_for_generate(self, batch_size, past_key_values, seq_length, config):
self.assertIsInstance(past_key_values, Cache)
k_embed_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
v_embed_dim = config.v_head_dim
expected_key_shape = (batch_size, config.num_key_value_heads, seq_length, k_embed_dim)
expected_value_shape = (batch_size, config.num_key_value_heads, seq_length, v_embed_dim)
for layer_idx in range(config.num_hidden_layers):
self.assertEqual(past_key_values.layers[layer_idx].keys.shape, expected_key_shape)
self.assertEqual(past_key_values.layers[layer_idx].values.shape, expected_value_shape)
@unittest.skip("MoE experts may not receive gradients with small test data")
def test_training_gradient_checkpointing(self):
pass
@unittest.skip("MoE experts may not receive gradients with small test data")
def test_training_gradient_checkpointing_use_reentrant(self):
pass
@unittest.skip("MoE experts may not receive gradients with small test data")
def test_training_gradient_checkpointing_use_reentrant_false(self):
pass
@unittest.skip("LongcatFlash router uses weight.type() directly in forward which prevents offloading")
def test_cpu_offload(self):
pass
@unittest.skip("LongcatFlash router uses weight.type() directly in forward which prevents offloading")
def test_disk_offload_bin(self):
pass
@unittest.skip("LongcatFlash router uses weight.type() directly in forward which prevents offloading")
def test_disk_offload_safetensors(self):
pass
@unittest.skip("Most probably because of the MOE, the moe and router does not ignore padding tokens")
def test_eager_padding_matches_padding_free_with_position_ids(self):
pass
@unittest.skip(reason="SDPA can't dispatch on flash due to unsupported head dims")
def test_sdpa_can_dispatch_on_flash(self):
pass
@staticmethod
def _prepare_config_headdim(config, requested_dim):
# there's specific head dims due to lora compressions in longcat
config = copy.deepcopy(config)
config.attention_dropout = 0
if requested_dim > config.qk_rope_head_dim:
config.qk_rope_head_dim = requested_dim
config.qk_nope_head_dim = max(config.qk_nope_head_dim, requested_dim)
config.v_head_dim = max(config.v_head_dim, requested_dim)
config.qk_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim
config.head_dim = requested_dim
config.q_lora_rank = max(config.q_lora_rank, requested_dim * 4)
config.kv_lora_rank = max(config.kv_lora_rank, requested_dim * 2)
config.hidden_size = max(config.hidden_size, config.num_attention_heads * requested_dim)
return config
@require_flash_attn
@require_torch_gpu
@require_bitsandbytes
@mark.flash_attn_test
@slow
def test_flash_attn_2_fp32_ln(self):
if not self.has_attentions:
self.skipTest(reason="Model architecture does not support attentions")
for model_class in self.all_generative_model_classes: # TODO: this test should run on all classes instead
if not model_class._supports_flash_attn:
self.skipTest(f"{model_class.__name__} does not support Flash Attention 2")
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
model = model_class(config)
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(tmpdirname)
dummy_input = inputs_dict[model.main_input_name]
dummy_attention_mask = inputs_dict.get("attention_mask", torch.ones_like(dummy_input))
batch_size = dummy_attention_mask.shape[0]
is_padding_right = dummy_attention_mask[:, -1].sum().item() != batch_size
# To avoid errors with padding_side=="right"
if is_padding_right:
dummy_attention_mask = torch.ones_like(dummy_input)
model = model_class.from_pretrained(
tmpdirname,
dtype=torch.float16,
attn_implementation="flash_attention_2",
device_map="auto", # small change to ensure device placement
)
# no upcasting at all
if model.config.is_encoder_decoder:
dummy_decoder_input_ids = inputs_dict["decoder_input_ids"]
dummy_decoder_attention_mask = inputs_dict["decoder_attention_mask"]
_ = model(dummy_input, decoder_input_ids=dummy_decoder_input_ids)
# with attention mask
_ = model(
dummy_input,
attention_mask=dummy_attention_mask,
decoder_input_ids=dummy_decoder_input_ids,
decoder_attention_mask=dummy_decoder_attention_mask,
)
else:
_ = model(dummy_input)
# with attention mask
_ = model(dummy_input, attention_mask=dummy_attention_mask)
@slow
| LongcatFlashModelTest |
python | huggingface__transformers | tests/models/patchtsmixer/test_modeling_patchtsmixer.py | {
"start": 7349,
"end": 18063
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
PatchTSMixerModel,
PatchTSMixerForPrediction,
PatchTSMixerForPretraining,
PatchTSMixerForTimeSeriesClassification,
PatchTSMixerForRegression,
)
if is_torch_available()
else ()
)
pipeline_model_mapping = {"feature-extraction": PatchTSMixerModel} if is_torch_available() else {}
is_encoder_decoder = False
test_missing_keys = False
test_inputs_embeds = False
test_resize_embeddings = True
test_resize_position_embeddings = False
test_mismatched_shapes = True
has_attentions = False
def setUp(self):
self.model_tester = PatchTSMixerModelTester()
self.config_tester = ConfigTester(
self,
config_class=PatchTSMixerConfig,
has_text_modality=False,
prediction_length=self.model_tester.prediction_length,
common_properties=["hidden_size", "expansion_factor", "num_hidden_layers"],
)
def test_config(self):
self.config_tester.run_common_tests()
def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
if model_class == PatchTSMixerForPrediction:
rng = random.Random(self.model_tester.seed_number)
labels = floats_tensor(
[
self.model_tester.batch_size,
self.model_tester.prediction_length,
self.model_tester.num_input_channels,
],
rng=rng,
)
inputs_dict["future_values"] = labels
elif model_class in get_values(MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING):
rng = random.Random(self.model_tester.seed_number)
labels = ids_tensor([self.model_tester.batch_size], self.model_tester.num_targets, rng=rng)
inputs_dict["target_values"] = labels
elif model_class in get_values(MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING):
rng = random.Random(self.model_tester.seed_number)
labels = floats_tensor([self.model_tester.batch_size, self.model_tester.num_targets], rng=rng)
inputs_dict["target_values"] = labels
inputs_dict["output_hidden_states"] = True
return inputs_dict
def test_save_load_strict(self):
config, _ = self.model_tester.prepare_config_and_inputs()
for model_class in self.all_model_classes:
model = model_class(config)
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(tmpdirname)
model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
self.assertEqual(info["missing_keys"], set())
def test_hidden_states_output(self):
def check_hidden_states_output(inputs_dict, config, model_class):
model = model_class(config)
model.to(torch_device)
model.eval()
with torch.no_grad():
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
expected_num_layers = getattr(
self.model_tester,
"expected_num_hidden_layers",
self.model_tester.num_hidden_layers,
)
self.assertEqual(len(hidden_states), expected_num_layers)
expected_hidden_size = self.model_tester.hidden_size
self.assertEqual(hidden_states[0].shape[-1], expected_hidden_size)
num_patch = self.model_tester.num_patches
self.assertListEqual(
list(hidden_states[0].shape[-2:]),
[num_patch, self.model_tester.hidden_size],
)
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
check_hidden_states_output(inputs_dict, config, model_class)
@unittest.skip(reason="No tokens embeddings")
def test_resize_tokens_embeddings(self):
pass
def test_model_outputs_equivalence(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
def set_nan_tensor_to_zero(t):
t[t != t] = 0
return t
def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}):
with torch.no_grad():
tuple_output = model(**tuple_inputs, return_dict=False, **additional_kwargs)
output_ = model(**dict_inputs, return_dict=True, **additional_kwargs)
attributes_ = vars(output_)
dict_output = tuple(attributes_.values())
def recursive_check(tuple_object, dict_object):
if isinstance(tuple_object, (list, tuple)):
for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object):
recursive_check(tuple_iterable_value, dict_iterable_value)
elif isinstance(tuple_object, dict):
for tuple_iterable_value, dict_iterable_value in zip(
tuple_object.values(), dict_object.values()
):
recursive_check(tuple_iterable_value, dict_iterable_value)
elif tuple_object is None:
return
else:
self.assertTrue(
torch.allclose(
set_nan_tensor_to_zero(tuple_object),
set_nan_tensor_to_zero(dict_object),
atol=1e-5,
),
msg=(
"Tuple and dict output are not equal. Difference:"
f" {torch.max(torch.abs(tuple_object - dict_object))}. Tuple has `nan`:"
f" {torch.isnan(tuple_object).any()} and `inf`: {torch.isinf(tuple_object)}. Dict has"
f" `nan`: {torch.isnan(dict_object).any()} and `inf`: {torch.isinf(dict_object)}."
),
)
recursive_check(tuple_output, dict_output)
for model_class in self.all_model_classes:
print(model_class)
model = model_class(config)
model.to(torch_device)
model.eval()
tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
dict_inputs = self._prepare_for_class(inputs_dict, model_class)
check_equivalence(model, tuple_inputs, dict_inputs)
tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
check_equivalence(model, tuple_inputs, dict_inputs)
tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
dict_inputs = self._prepare_for_class(inputs_dict, model_class)
tuple_inputs.update({"output_hidden_states": False})
dict_inputs.update({"output_hidden_states": False})
check_equivalence(model, tuple_inputs, dict_inputs)
tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
tuple_inputs.update({"output_hidden_states": False})
dict_inputs.update({"output_hidden_states": False})
check_equivalence(
model,
tuple_inputs,
dict_inputs,
)
def test_model_main_input_name(self):
model_signature = inspect.signature(getattr(PatchTSMixerModel, "forward"))
# The main input is the name of the argument after `self`
observed_main_input_name = list(model_signature.parameters.keys())[1]
self.assertEqual(PatchTSMixerModel.main_input_name, observed_main_input_name)
def test_forward_signature(self):
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
model = model_class(config)
signature = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
arg_names = [*signature.parameters.keys()]
if model_class == PatchTSMixerForPretraining:
expected_arg_names = [
"past_values",
"observed_mask",
"output_hidden_states",
"return_loss",
]
elif model_class == PatchTSMixerModel:
expected_arg_names = [
"past_values",
"observed_mask",
"output_hidden_states",
]
elif model_class in get_values(MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING) or model_class in get_values(
MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING
):
expected_arg_names = [
"past_values",
"target_values",
"output_hidden_states",
"return_loss",
]
else:
# PatchTSMixerForPrediction
expected_arg_names = [
"past_values",
"observed_mask",
"future_values",
"output_hidden_states",
"return_loss",
]
self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names)
@is_flaky()
def test_retain_grad_hidden_states_attentions(self):
super().test_retain_grad_hidden_states_attentions()
@unittest.skip(reason="Model does not have input embeddings")
def test_model_get_set_embeddings(self):
pass
def prepare_batch(repo_id="ibm/patchtsmixer-etth1-test-data", file="pretrain_batch.pt"):
# TODO: Make repo public
file = hf_hub_download(repo_id=repo_id, filename=file, repo_type="dataset")
check_torch_load_is_safe()
batch = torch.load(file, map_location=torch_device, weights_only=True)
return batch
@require_torch
@slow
| PatchTSMixerModelTest |
python | wandb__wandb | wandb/apis/public/artifacts.py | {
"start": 28430,
"end": 30409
} | class ____(SizedRelayPaginator["ArtifactFragment", "Artifact"]):
"""An iterable collection of artifacts associated with a specific run.
<!-- lazydoc-ignore-init: internal -->
"""
QUERY: Document # Must be set per-instance
last_response: ConnectionWithTotal[ArtifactFragment] | None
def __init__(
self,
client: Client,
run: Run,
mode: Literal["logged", "used"] = "logged",
per_page: int = 50,
):
try:
query_str = _run_artifacts_mode_to_gql()[mode]
except LookupError:
raise ValueError("mode must be logged or used")
else:
self.QUERY = gql_compat(query_str, omit_fields=omit_artifact_fields(client))
self.run = run
variables = {"entity": run.entity, "project": run.project, "runName": run.id}
super().__init__(client, variables=variables, per_page=per_page)
@override
def _update_response(self) -> None:
from wandb.sdk.artifacts._models.pagination import RunArtifactConnection
data = self.client.execute(self.QUERY, variable_values=self.variables)
# Extract the inner `*Connection` result for faster/easier access.
inner_data = data["project"]["run"]["artifacts"]
self.last_response = RunArtifactConnection.model_validate(inner_data)
def _convert(self, node: ArtifactFragment) -> Artifact | None:
from wandb.sdk.artifacts._validators import FullArtifactPath
from wandb.sdk.artifacts.artifact import Artifact
if node.artifact_sequence.project is None:
return None
return Artifact._from_attrs(
path=FullArtifactPath(
prefix=node.artifact_sequence.project.entity.name,
project=node.artifact_sequence.project.name,
name=f"{node.artifact_sequence.name}:v{node.version_index}",
),
attrs=node,
client=self.client,
)
| RunArtifacts |
python | numpy__numpy | numpy/distutils/fcompiler/fujitsu.py | {
"start": 206,
"end": 1333
} | class ____(FCompiler):
compiler_type = 'fujitsu'
description = 'Fujitsu Fortran Compiler'
possible_executables = ['frt']
version_pattern = r'frt \(FRT\) (?P<version>[a-z\d.]+)'
# $ frt --version
# frt (FRT) x.x.x yyyymmdd
executables = {
'version_cmd' : ["<F77>", "--version"],
'compiler_f77' : ["frt", "-Fixed"],
'compiler_fix' : ["frt", "-Fixed"],
'compiler_f90' : ["frt"],
'linker_so' : ["frt", "-shared"],
'archiver' : ["ar", "-cr"],
'ranlib' : ["ranlib"]
}
pic_flags = ['-KPIC']
module_dir_switch = '-M'
module_include_switch = '-I'
def get_flags_opt(self):
return ['-O3']
def get_flags_debug(self):
return ['-g']
def runtime_library_dir_option(self, dir):
return f'-Wl,-rpath={dir}'
def get_libraries(self):
return ['fj90f', 'fj90i', 'fjsrcinfo']
if __name__ == '__main__':
from distutils import log
from numpy.distutils import customized_fcompiler
log.set_verbosity(2)
print(customized_fcompiler('fujitsu').get_version())
| FujitsuFCompiler |
python | getsentry__sentry | src/sentry/apidocs/examples/discover_saved_query_examples.py | {
"start": 4373,
"end": 5103
} | class ____:
DISCOVER_SAVED_QUERY_GET_RESPONSE = [
OpenApiExample(
"Discover Saved Query GET response",
value=DISCOVER_SAVED_QUERY_OBJ,
status_codes=["200"],
response_only=True,
)
]
DISCOVER_SAVED_QUERY_POST_RESPONSE = [
OpenApiExample(
"Create Discover Saved Query",
value=DISCOVER_SAVED_QUERY_OBJ,
status_codes=["201"],
response_only=True,
)
]
DISCOVER_SAVED_QUERIES_QUERY_RESPONSE = [
OpenApiExample(
"Get Discover Saved Queries",
value=SAVED_QUERIES,
status_codes=["200"],
response_only=True,
)
]
| DiscoverExamples |
python | doocs__leetcode | solution/0900-0999/0918.Maximum Sum Circular Subarray/Solution.py | {
"start": 0,
"end": 347
} | class ____:
def maxSubarraySumCircular(self, nums: List[int]) -> int:
pmi, pmx = 0, -inf
ans, s, smi = -inf, 0, inf
for x in nums:
s += x
ans = max(ans, s - pmi)
smi = min(smi, s - pmx)
pmi = min(pmi, s)
pmx = max(pmx, s)
return max(ans, s - smi)
| Solution |
python | kamyu104__LeetCode-Solutions | Python/find-the-duplicate-number.py | {
"start": 1359,
"end": 1947
} | class ____(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
duplicate = 0
# Mark the value as visited by negative.
for num in nums:
if nums[abs(num) - 1] > 0:
nums[abs(num) - 1] *= -1
else:
duplicate = abs(num)
break
# Rollback the value.
for num in nums:
if nums[abs(num) - 1] < 0:
nums[abs(num) - 1] *= -1
else:
break
return duplicate
| Solution3 |
python | keras-team__keras | keras/src/trainers/trainer_test.py | {
"start": 9234,
"end": 9478
} | class ____(metrics.MeanSquaredError):
def __init__(self):
super().__init__(name="mse")
super().reset_state()
def reset_state(self):
# prevent reset at each starting epoch
pass
| EpochAgnosticMeanSquaredError |
python | pydantic__pydantic | pydantic/v1/errors.py | {
"start": 5135,
"end": 5255
} | class ____(UrlError):
code = 'url.userinfo'
msg_template = 'userinfo required in URL but missing'
| UrlUserInfoError |
python | apache__airflow | scripts/ci/prek/check_deferrable_default.py | {
"start": 1426,
"end": 2553
} | class ____(ast.NodeVisitor):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, *kwargs)
self.error_linenos: list[int] = []
def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:
if node.name == "__init__":
args = node.args
arguments = reversed([*args.args, *args.posonlyargs, *args.kwonlyargs])
defaults = reversed([*args.defaults, *args.kw_defaults])
for argument, default in itertools.zip_longest(arguments, defaults):
# argument is not deferrable
if argument is None or argument.arg != "deferrable":
continue
# argument is deferrable, but comes with no default value
if default is None:
self.error_linenos.append(argument.lineno)
continue
# argument is deferrable, but the default value is not valid
if not _is_valid_deferrable_default(default):
self.error_linenos.append(default.lineno)
return node
| DefaultDeferrableVisitor |
python | FactoryBoy__factory_boy | factory/declarations.py | {
"start": 22526,
"end": 24123
} | class ____(PostGenerationDeclaration):
"""Calls a factory once the object has been generated.
Attributes:
factory (Factory): the factory to call
defaults (dict): extra declarations for calling the related factory
name (str): the name to use to refer to the generated object when
calling the related factory
"""
UNROLL_CONTEXT_BEFORE_EVALUATION = False
def __init__(self, factory, factory_related_name='', **defaults):
super().__init__()
self.name = factory_related_name
self.defaults = defaults
self.factory_wrapper = _FactoryWrapper(factory)
def get_factory(self):
"""Retrieve the wrapped factory.Factory subclass."""
return self.factory_wrapper.get()
def call(self, instance, step, context):
factory = self.get_factory()
if context.value_provided:
# The user passed in a custom value
logger.debug(
"RelatedFactory: Using provided %r instead of generating %s.%s.",
context.value,
factory.__module__, factory.__name__,
)
return context.value
passed_kwargs = dict(self.defaults)
passed_kwargs.update(context.extra)
if self.name:
passed_kwargs[self.name] = instance
logger.debug(
"RelatedFactory: Generating %s.%s(%s)",
factory.__module__,
factory.__name__,
utils.log_pprint((step,), passed_kwargs),
)
return step.recurse(factory, passed_kwargs)
| RelatedFactory |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0145_alter_importedfile_id.py | {
"start": 100,
"end": 451
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0144_addons_blank_field"),
]
operations = [
migrations.AlterField(
model_name="importedfile",
name="id",
field=models.BigAutoField(primary_key=True, serialize=False),
),
]
| Migration |
python | PyCQA__pyflakes | pyflakes/messages.py | {
"start": 3094,
"end": 3319
} | class ____(Message):
message = 'duplicate argument %r in function definition'
def __init__(self, filename, loc, name):
Message.__init__(self, filename, loc)
self.message_args = (name,)
| DuplicateArgument |
python | ray-project__ray | rllib/algorithms/ppo/torch/ppo_torch_learner.py | {
"start": 887,
"end": 6745
} | class ____(PPOLearner, TorchLearner):
"""Implements torch-specific PPO loss logic on top of PPOLearner.
This class implements the ppo loss under `self.compute_loss_for_module()`.
"""
@override(TorchLearner)
def compute_loss_for_module(
self,
*,
module_id: ModuleID,
config: PPOConfig,
batch: Dict[str, Any],
fwd_out: Dict[str, TensorType],
) -> TensorType:
module = self.module[module_id].unwrapped()
# Possibly apply masking to some sub loss terms and to the total loss term
# at the end. Masking could be used for RNN-based model (zero padded `batch`)
# and for PPO's batched value function (and bootstrap value) computations,
# for which we add an (artificial) timestep to each episode to
# simplify the actual computation.
if Columns.LOSS_MASK in batch:
mask = batch[Columns.LOSS_MASK]
num_valid = torch.sum(mask)
def possibly_masked_mean(data_):
return torch.sum(data_[mask]) / num_valid
else:
possibly_masked_mean = torch.mean
action_dist_class_train = module.get_train_action_dist_cls()
action_dist_class_exploration = module.get_exploration_action_dist_cls()
curr_action_dist = action_dist_class_train.from_logits(
fwd_out[Columns.ACTION_DIST_INPUTS]
)
# TODO (sven): We should ideally do this in the LearnerConnector (separation of
# concerns: Only do things on the EnvRunners that are required for computing
# actions, do NOT do anything on the EnvRunners that's only required for a
# training update).
prev_action_dist = action_dist_class_exploration.from_logits(
batch[Columns.ACTION_DIST_INPUTS]
)
logp_ratio = torch.exp(
curr_action_dist.logp(batch[Columns.ACTIONS]) - batch[Columns.ACTION_LOGP]
)
# Only calculate kl loss if necessary (kl-coeff > 0.0).
if config.use_kl_loss:
action_kl = prev_action_dist.kl(curr_action_dist)
mean_kl_loss = possibly_masked_mean(action_kl)
else:
mean_kl_loss = torch.tensor(0.0, device=logp_ratio.device)
curr_entropy = curr_action_dist.entropy()
mean_entropy = possibly_masked_mean(curr_entropy)
surrogate_loss = torch.min(
batch[Postprocessing.ADVANTAGES] * logp_ratio,
batch[Postprocessing.ADVANTAGES]
* torch.clamp(logp_ratio, 1 - config.clip_param, 1 + config.clip_param),
)
# Compute a value function loss.
if config.use_critic:
value_fn_out = module.compute_values(
batch, embeddings=fwd_out.get(Columns.EMBEDDINGS)
)
vf_loss = torch.pow(value_fn_out - batch[Postprocessing.VALUE_TARGETS], 2.0)
vf_loss_clipped = torch.clamp(vf_loss, 0, config.vf_clip_param)
mean_vf_loss = possibly_masked_mean(vf_loss_clipped)
mean_vf_unclipped_loss = possibly_masked_mean(vf_loss)
# Ignore the value function -> Set all to 0.0.
else:
z = torch.tensor(0.0, device=surrogate_loss.device)
value_fn_out = mean_vf_unclipped_loss = vf_loss_clipped = mean_vf_loss = z
total_loss = possibly_masked_mean(
-surrogate_loss
+ config.vf_loss_coeff * vf_loss_clipped
- (
self.entropy_coeff_schedulers_per_module[module_id].get_current_value()
* curr_entropy
)
)
# Add mean_kl_loss (already processed through `possibly_masked_mean`),
# if necessary.
if config.use_kl_loss:
total_loss += self.curr_kl_coeffs_per_module[module_id] * mean_kl_loss
# Log important loss stats.
self.metrics.log_dict(
{
POLICY_LOSS_KEY: -possibly_masked_mean(surrogate_loss),
VF_LOSS_KEY: mean_vf_loss,
LEARNER_RESULTS_VF_LOSS_UNCLIPPED_KEY: mean_vf_unclipped_loss,
LEARNER_RESULTS_VF_EXPLAINED_VAR_KEY: explained_variance(
batch[Postprocessing.VALUE_TARGETS], value_fn_out
),
ENTROPY_KEY: mean_entropy,
LEARNER_RESULTS_KL_KEY: mean_kl_loss,
},
key=module_id,
window=1, # <- single items (should not be mean/ema-reduced over time).
)
# Return the total loss.
return total_loss
@override(PPOLearner)
def _update_module_kl_coeff(
self,
*,
module_id: ModuleID,
config: PPOConfig,
kl_loss: float,
) -> None:
if np.isnan(kl_loss):
logger.warning(
f"KL divergence for Module {module_id} is non-finite, this "
"will likely destabilize your model and the training "
"process. Action(s) in a specific state have near-zero "
"probability. This can happen naturally in deterministic "
"environments where the optimal policy has zero mass for a "
"specific action. To fix this issue, consider setting "
"`kl_coeff` to 0.0 or increasing `entropy_coeff` in your "
"config."
)
# Update the KL coefficient.
curr_var = self.curr_kl_coeffs_per_module[module_id]
if kl_loss > 2.0 * config.kl_target:
# TODO (Kourosh) why not 2?
curr_var.data *= 1.5
elif kl_loss < 0.5 * config.kl_target:
curr_var.data *= 0.5
# Log the updated KL-coeff value.
self.metrics.log_value(
(module_id, LEARNER_RESULTS_CURR_KL_COEFF_KEY),
curr_var.item(),
window=1,
)
| PPOTorchLearner |
python | python__mypy | mypy/plugins/dataclasses.py | {
"start": 6809,
"end": 47043
} | class ____:
"""Implement the behavior of @dataclass.
Note that this may be executed multiple times on the same class, so
everything here must be idempotent.
This runs after the main semantic analysis pass, so you can assume that
there are no placeholders.
"""
def __init__(
self,
cls: ClassDef,
# Statement must also be accepted since class definition itself may be passed as the reason
# for subclass/metaclass-based uses of `typing.dataclass_transform`
reason: Expression | Statement,
spec: DataclassTransformSpec,
api: SemanticAnalyzerPluginInterface,
) -> None:
self._cls = cls
self._reason = reason
self._spec = spec
self._api = api
def transform(self) -> bool:
"""Apply all the necessary transformations to the underlying
dataclass so as to ensure it is fully type checked according
to the rules in PEP 557.
"""
info = self._cls.info
attributes = self.collect_attributes()
if attributes is None:
# Some definitions are not ready. We need another pass.
return False
for attr in attributes:
if attr.type is None:
return False
decorator_arguments = {
"init": self._get_bool_arg("init", True),
"eq": self._get_bool_arg("eq", self._spec.eq_default),
"order": self._get_bool_arg("order", self._spec.order_default),
"frozen": self._get_bool_arg("frozen", self._spec.frozen_default),
"slots": self._get_bool_arg("slots", False),
"match_args": self._get_bool_arg("match_args", True),
}
py_version = self._api.options.python_version
# If there are no attributes, it may be that the semantic analyzer has not
# processed them yet. In order to work around this, we can simply skip generating
# __init__ if there are no attributes, because if the user truly did not define any,
# then the object default __init__ with an empty signature will be present anyway.
if (
decorator_arguments["init"]
and ("__init__" not in info.names or info.names["__init__"].plugin_generated)
and attributes
):
args = [
attr.to_argument(info, of="__init__")
for attr in attributes
if attr.is_in_init and not self._is_kw_only_type(attr.type)
]
if info.fallback_to_any:
# Make positional args optional since we don't know their order.
# This will at least allow us to typecheck them if they are called
# as kwargs
for arg in args:
if arg.kind == ARG_POS:
arg.kind = ARG_OPT
existing_args_names = {arg.variable.name for arg in args}
gen_args_name = "generated_args"
while gen_args_name in existing_args_names:
gen_args_name += "_"
gen_kwargs_name = "generated_kwargs"
while gen_kwargs_name in existing_args_names:
gen_kwargs_name += "_"
args = [
Argument(Var(gen_args_name), AnyType(TypeOfAny.explicit), None, ARG_STAR),
*args,
Argument(Var(gen_kwargs_name), AnyType(TypeOfAny.explicit), None, ARG_STAR2),
]
add_method_to_class(
self._api, self._cls, "__init__", args=args, return_type=NoneType()
)
if (
decorator_arguments["eq"]
and info.get("__eq__") is None
or decorator_arguments["order"]
):
# Type variable for self types in generated methods.
obj_type = self._api.named_type("builtins.object")
self_tvar_expr = TypeVarExpr(
SELF_TVAR_NAME,
info.fullname + "." + SELF_TVAR_NAME,
[],
obj_type,
AnyType(TypeOfAny.from_omitted_generics),
)
info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr)
# Add <, >, <=, >=, but only if the class has an eq method.
if decorator_arguments["order"]:
if not decorator_arguments["eq"]:
self._api.fail('"eq" must be True if "order" is True', self._reason)
for method_name in ["__lt__", "__gt__", "__le__", "__ge__"]:
# Like for __eq__ and __ne__, we want "other" to match
# the self type.
obj_type = self._api.named_type("builtins.object")
order_tvar_def = TypeVarType(
SELF_TVAR_NAME,
f"{info.fullname}.{SELF_TVAR_NAME}",
id=TypeVarId(-1, namespace=f"{info.fullname}.{method_name}"),
values=[],
upper_bound=obj_type,
default=AnyType(TypeOfAny.from_omitted_generics),
)
order_return_type = self._api.named_type("builtins.bool")
order_args = [
Argument(Var("other", order_tvar_def), order_tvar_def, None, ARG_POS)
]
existing_method = info.get(method_name)
if existing_method is not None and not existing_method.plugin_generated:
assert existing_method.node
self._api.fail(
f'You may not have a custom "{method_name}" method when "order" is True',
existing_method.node,
)
add_method_to_class(
self._api,
self._cls,
method_name,
args=order_args,
return_type=order_return_type,
self_type=order_tvar_def,
tvar_def=order_tvar_def,
)
parent_decorator_arguments = []
for parent in info.mro[1:-1]:
parent_args = parent.metadata.get("dataclass")
# Ignore parent classes that directly specify a dataclass transform-decorated metaclass
# when searching for usage of the frozen parameter. PEP 681 states that a class that
# directly specifies such a metaclass must be treated as neither frozen nor non-frozen.
if parent_args and not _has_direct_dataclass_transform_metaclass(parent):
parent_decorator_arguments.append(parent_args)
if decorator_arguments["frozen"]:
if any(not parent["frozen"] for parent in parent_decorator_arguments):
self._api.fail("Frozen dataclass cannot inherit from a non-frozen dataclass", info)
self._propertize_callables(attributes, settable=False)
self._freeze(attributes)
else:
if any(parent["frozen"] for parent in parent_decorator_arguments):
self._api.fail("Non-frozen dataclass cannot inherit from a frozen dataclass", info)
self._propertize_callables(attributes)
if decorator_arguments["slots"]:
self.add_slots(info, attributes, correct_version=py_version >= (3, 10))
self.reset_init_only_vars(info, attributes)
if (
decorator_arguments["match_args"]
and (
"__match_args__" not in info.names or info.names["__match_args__"].plugin_generated
)
and py_version >= (3, 10)
):
str_type = self._api.named_type("builtins.str")
literals: list[Type] = [
LiteralType(attr.name, str_type)
for attr in attributes
if attr.is_in_init and not attr.kw_only
]
match_args_type = TupleType(literals, self._api.named_type("builtins.tuple"))
add_attribute_to_class(self._api, self._cls, "__match_args__", match_args_type)
self._add_dataclass_fields_magic_attribute()
self._add_internal_replace_method(attributes)
if self._api.options.python_version >= (3, 13):
self._add_dunder_replace(attributes)
if "__post_init__" in info.names:
self._add_internal_post_init_method(attributes)
info.metadata["dataclass"] = {
"attributes": [attr.serialize() for attr in attributes],
"frozen": decorator_arguments["frozen"],
}
return True
def _add_dunder_replace(self, attributes: list[DataclassAttribute]) -> None:
"""Add a `__replace__` method to the class, which is used to replace attributes in the `copy` module."""
args = [
attr.to_argument(self._cls.info, of="replace")
for attr in attributes
if attr.is_in_init
]
add_method_to_class(
self._api,
self._cls,
"__replace__",
args=args,
return_type=fill_typevars(self._cls.info),
)
def _add_internal_replace_method(self, attributes: list[DataclassAttribute]) -> None:
"""
Stashes the signature of 'dataclasses.replace(...)' for this specific dataclass
to be used later whenever 'dataclasses.replace' is called for this dataclass.
"""
add_method_to_class(
self._api,
self._cls,
_INTERNAL_REPLACE_SYM_NAME,
args=[attr.to_argument(self._cls.info, of="replace") for attr in attributes],
return_type=NoneType(),
is_staticmethod=True,
)
def _add_internal_post_init_method(self, attributes: list[DataclassAttribute]) -> None:
add_method_to_class(
self._api,
self._cls,
_INTERNAL_POST_INIT_SYM_NAME,
args=[
attr.to_argument(self._cls.info, of="__post_init__")
for attr in attributes
if attr.is_init_var
],
return_type=NoneType(),
)
def add_slots(
self, info: TypeInfo, attributes: list[DataclassAttribute], *, correct_version: bool
) -> None:
if not correct_version:
# This means that version is lower than `3.10`,
# it is just a non-existent argument for `dataclass` function.
self._api.fail(
'Keyword argument "slots" for "dataclass" is only valid in Python 3.10 and higher',
self._reason,
)
return
generated_slots = {attr.name for attr in attributes}
if (info.slots is not None and info.slots != generated_slots) or info.names.get(
"__slots__"
):
# This means we have a slots conflict.
# Class explicitly specifies a different `__slots__` field.
# And `@dataclass(slots=True)` is used.
# In runtime this raises a type error.
self._api.fail(
'"{}" both defines "__slots__" and is used with "slots=True"'.format(
self._cls.name
),
self._cls,
)
return
if any(p.slots is None for p in info.mro[1:-1]):
# At least one type in mro (excluding `self` and `object`)
# does not have concrete `__slots__` defined. Ignoring.
return
info.slots = generated_slots
# Now, insert `.__slots__` attribute to class namespace:
slots_type = TupleType(
[self._api.named_type("builtins.str") for _ in generated_slots],
self._api.named_type("builtins.tuple"),
)
add_attribute_to_class(self._api, self._cls, "__slots__", slots_type)
def reset_init_only_vars(self, info: TypeInfo, attributes: list[DataclassAttribute]) -> None:
"""Remove init-only vars from the class and reset init var declarations."""
for attr in attributes:
if attr.is_init_var:
if attr.name in info.names:
del info.names[attr.name]
else:
# Nodes of superclass InitVars not used in __init__ cannot be reached.
assert attr.is_init_var
for stmt in info.defn.defs.body:
if isinstance(stmt, AssignmentStmt) and stmt.unanalyzed_type:
lvalue = stmt.lvalues[0]
if isinstance(lvalue, NameExpr) and lvalue.name == attr.name:
# Reset node so that another semantic analysis pass will
# recreate a symbol node for this attribute.
lvalue.node = None
def _get_assignment_statements_from_if_statement(
self, stmt: IfStmt
) -> Iterator[AssignmentStmt]:
for body in stmt.body:
if not body.is_unreachable:
yield from self._get_assignment_statements_from_block(body)
if stmt.else_body is not None and not stmt.else_body.is_unreachable:
yield from self._get_assignment_statements_from_block(stmt.else_body)
def _get_assignment_statements_from_block(self, block: Block) -> Iterator[AssignmentStmt]:
for stmt in block.body:
if isinstance(stmt, AssignmentStmt):
yield stmt
elif isinstance(stmt, IfStmt):
yield from self._get_assignment_statements_from_if_statement(stmt)
def collect_attributes(self) -> list[DataclassAttribute] | None:
"""Collect all attributes declared in the dataclass and its parents.
All assignments of the form
a: SomeType
b: SomeOtherType = ...
are collected.
Return None if some dataclass base class hasn't been processed
yet and thus we'll need to ask for another pass.
"""
cls = self._cls
# First, collect attributes belonging to any class in the MRO, ignoring duplicates.
#
# We iterate through the MRO in reverse because attrs defined in the parent must appear
# earlier in the attributes list than attrs defined in the child. See:
# https://docs.python.org/3/library/dataclasses.html#inheritance
#
# However, we also want attributes defined in the subtype to override ones defined
# in the parent. We can implement this via a dict without disrupting the attr order
# because dicts preserve insertion order in Python 3.7+.
found_attrs: dict[str, DataclassAttribute] = {}
for info in reversed(cls.info.mro[1:-1]):
if "dataclass_tag" in info.metadata and "dataclass" not in info.metadata:
# We haven't processed the base class yet. Need another pass.
return None
if "dataclass" not in info.metadata:
continue
# Each class depends on the set of attributes in its dataclass ancestors.
self._api.add_plugin_dependency(make_wildcard_trigger(info.fullname))
for data in info.metadata["dataclass"]["attributes"]:
name: str = data["name"]
attr = DataclassAttribute.deserialize(info, data, self._api)
# TODO: We shouldn't be performing type operations during the main
# semantic analysis pass, since some TypeInfo attributes might
# still be in flux. This should be performed in a later phase.
attr.expand_typevar_from_subtype(cls.info)
found_attrs[name] = attr
sym_node = cls.info.names.get(name)
if sym_node and sym_node.node and not isinstance(sym_node.node, Var):
self._api.fail(
"Dataclass attribute may only be overridden by another attribute",
sym_node.node,
)
# Second, collect attributes belonging to the current class.
current_attr_names: set[str] = set()
kw_only = self._get_bool_arg("kw_only", self._spec.kw_only_default)
for stmt in self._get_assignment_statements_from_block(cls.defs):
# Any assignment that doesn't use the new type declaration
# syntax can be ignored out of hand.
if not stmt.new_syntax:
continue
# a: int, b: str = 1, 'foo' is not supported syntax so we
# don't have to worry about it.
lhs = stmt.lvalues[0]
if not isinstance(lhs, NameExpr):
continue
sym = cls.info.names.get(lhs.name)
if sym is None:
# There was probably a semantic analysis error.
continue
node = sym.node
assert not isinstance(node, PlaceholderNode)
if isinstance(node, TypeAlias):
self._api.fail(
("Type aliases inside dataclass definitions are not supported at runtime"),
node,
)
# Skip processing this node. This doesn't match the runtime behaviour,
# but the only alternative would be to modify the SymbolTable,
# and it's a little hairy to do that in a plugin.
continue
if isinstance(node, Decorator):
# This might be a property / field name clash.
# We will issue an error later.
continue
assert isinstance(node, Var), node
# x: ClassVar[int] is ignored by dataclasses.
if node.is_classvar:
continue
# x: InitVar[int] is turned into x: int and is removed from the class.
is_init_var = False
node_type = get_proper_type(node.type)
if (
isinstance(node_type, Instance)
and node_type.type.fullname == "dataclasses.InitVar"
):
is_init_var = True
node.type = node_type.args[0]
if self._is_kw_only_type(node_type):
kw_only = True
has_field_call, field_args = self._collect_field_args(stmt.rvalue)
is_in_init_param = field_args.get("init")
if is_in_init_param is None:
is_in_init = self._get_default_init_value_for_field_specifier(stmt.rvalue)
else:
is_in_init = bool(self._api.parse_bool(is_in_init_param))
has_default = False
# Ensure that something like x: int = field() is rejected
# after an attribute with a default.
if has_field_call:
has_default = (
"default" in field_args
or "default_factory" in field_args
# alias for default_factory defined in PEP 681
or "factory" in field_args
)
# All other assignments are already type checked.
elif not isinstance(stmt.rvalue, TempNode):
has_default = True
if not has_default and self._spec is _TRANSFORM_SPEC_FOR_DATACLASSES:
# Make all non-default dataclass attributes implicit because they are de-facto
# set on self in the generated __init__(), not in the class body. On the other
# hand, we don't know how custom dataclass transforms initialize attributes,
# so we don't treat them as implicit. This is required to support descriptors
# (https://github.com/python/mypy/issues/14868).
sym.implicit = True
is_kw_only = kw_only
# Use the kw_only field arg if it is provided. Otherwise use the
# kw_only value from the decorator parameter.
field_kw_only_param = field_args.get("kw_only")
if field_kw_only_param is not None:
value = self._api.parse_bool(field_kw_only_param)
if value is not None:
is_kw_only = value
else:
self._api.fail('"kw_only" argument must be a boolean literal', stmt.rvalue)
if sym.type is None and node.is_final and node.is_inferred:
# This is a special case, assignment like x: Final = 42 is classified
# annotated above, but mypy strips the `Final` turning it into x = 42.
# We do not support inferred types in dataclasses, so we can try inferring
# type for simple literals, and otherwise require an explicit type
# argument for Final[...].
typ = self._api.analyze_simple_literal_type(stmt.rvalue, is_final=True)
if typ:
node.type = typ
else:
self._api.fail(
"Need type argument for Final[...] with non-literal default in dataclass",
stmt,
)
node.type = AnyType(TypeOfAny.from_error)
alias = None
if "alias" in field_args:
alias = self._api.parse_str_literal(field_args["alias"])
if alias is None:
self._api.fail(
message_registry.DATACLASS_FIELD_ALIAS_MUST_BE_LITERAL,
stmt.rvalue,
code=errorcodes.LITERAL_REQ,
)
current_attr_names.add(lhs.name)
with state.strict_optional_set(self._api.options.strict_optional):
init_type = self._infer_dataclass_attr_init_type(sym, lhs.name, stmt)
found_attrs[lhs.name] = DataclassAttribute(
name=lhs.name,
alias=alias,
is_in_init=is_in_init,
is_init_var=is_init_var,
has_default=has_default,
line=stmt.line,
column=stmt.column,
type=init_type,
info=cls.info,
kw_only=is_kw_only,
is_neither_frozen_nor_nonfrozen=_has_direct_dataclass_transform_metaclass(
cls.info
),
api=self._api,
)
all_attrs = list(found_attrs.values())
all_attrs.sort(key=lambda a: a.kw_only)
# Third, ensure that arguments without a default don't follow
# arguments that have a default and that the KW_ONLY sentinel
# is only provided once.
found_default = False
found_kw_sentinel = False
for attr in all_attrs:
# If we find any attribute that is_in_init, not kw_only, and that
# doesn't have a default after one that does have one,
# then that's an error.
if found_default and attr.is_in_init and not attr.has_default and not attr.kw_only:
# If the issue comes from merging different classes, report it
# at the class definition point.
context: Context = cls
if attr.name in current_attr_names:
context = Context(line=attr.line, column=attr.column)
self._api.fail(
"Attributes without a default cannot follow attributes with one", context
)
found_default = found_default or (attr.has_default and attr.is_in_init)
if found_kw_sentinel and self._is_kw_only_type(attr.type):
context = cls
if attr.name in current_attr_names:
context = Context(line=attr.line, column=attr.column)
self._api.fail(
"There may not be more than one field with the KW_ONLY type", context
)
found_kw_sentinel = found_kw_sentinel or self._is_kw_only_type(attr.type)
return all_attrs
def _freeze(self, attributes: list[DataclassAttribute]) -> None:
"""Converts all attributes to @property methods in order to
emulate frozen classes.
"""
info = self._cls.info
for attr in attributes:
# Classes that directly specify a dataclass_transform metaclass must be neither frozen
# non non-frozen per PEP681. Though it is surprising, this means that attributes from
# such a class must be writable even if the rest of the class hierarchy is frozen. This
# matches the behavior of Pyright (the reference implementation).
if attr.is_neither_frozen_nor_nonfrozen:
continue
sym_node = info.names.get(attr.name)
if sym_node is not None:
var = sym_node.node
if isinstance(var, Var):
if var.is_final:
continue # do not turn `Final` attrs to `@property`
var.is_property = True
else:
var = attr.to_var(info)
var.info = info
var.is_property = True
var._fullname = info.fullname + "." + var.name
info.names[var.name] = SymbolTableNode(MDEF, var)
def _propertize_callables(
self, attributes: list[DataclassAttribute], settable: bool = True
) -> None:
"""Converts all attributes with callable types to @property methods.
This avoids the typechecker getting confused and thinking that
`my_dataclass_instance.callable_attr(foo)` is going to receive a
`self` argument (it is not).
"""
info = self._cls.info
for attr in attributes:
if isinstance(get_proper_type(attr.type), CallableType):
var = attr.to_var(info)
var.info = info
var.is_property = True
var.is_settable_property = settable
var._fullname = info.fullname + "." + var.name
info.names[var.name] = SymbolTableNode(MDEF, var)
def _is_kw_only_type(self, node: Type | None) -> bool:
"""Checks if the type of the node is the KW_ONLY sentinel value."""
if node is None:
return False
node_type = get_proper_type(node)
if not isinstance(node_type, Instance):
return False
return node_type.type.fullname == "dataclasses.KW_ONLY"
def _add_dataclass_fields_magic_attribute(self) -> None:
attr_name = "__dataclass_fields__"
any_type = AnyType(TypeOfAny.explicit)
# For `dataclasses`, use the type `dict[str, Field[Any]]` for accuracy. For dataclass
# transforms, it's inaccurate to use `Field` since a given transform may use a completely
# different type (or none); fall back to `Any` there.
#
# In either case, we're aiming to match the Typeshed stub for `is_dataclass`, which expects
# the instance to have a `__dataclass_fields__` attribute of type `dict[str, Field[Any]]`.
if self._spec is _TRANSFORM_SPEC_FOR_DATACLASSES:
field_type = self._api.named_type_or_none("dataclasses.Field", [any_type]) or any_type
else:
field_type = any_type
attr_type = self._api.named_type(
"builtins.dict", [self._api.named_type("builtins.str"), field_type]
)
var = Var(name=attr_name, type=attr_type)
var.info = self._cls.info
var._fullname = self._cls.info.fullname + "." + attr_name
var.is_classvar = True
self._cls.info.names[attr_name] = SymbolTableNode(
kind=MDEF, node=var, plugin_generated=True
)
def _collect_field_args(self, expr: Expression) -> tuple[bool, dict[str, Expression]]:
"""Returns a tuple where the first value represents whether or not
the expression is a call to dataclass.field and the second is a
dictionary of the keyword arguments that field() was called with.
"""
if (
isinstance(expr, CallExpr)
and isinstance(expr.callee, RefExpr)
and expr.callee.fullname in self._spec.field_specifiers
):
# field() only takes keyword arguments.
args = {}
for name, arg, kind in zip(expr.arg_names, expr.args, expr.arg_kinds):
if not kind.is_named():
if kind.is_named(star=True):
# This means that `field` is used with `**` unpacking,
# the best we can do for now is not to fail.
# TODO: we can infer what's inside `**` and try to collect it.
message = 'Unpacking **kwargs in "field()" is not supported'
elif self._spec is not _TRANSFORM_SPEC_FOR_DATACLASSES:
# dataclasses.field can only be used with keyword args, but this
# restriction is only enforced for the *standardized* arguments to
# dataclass_transform field specifiers. If this is not a
# dataclasses.dataclass class, we can just skip positional args safely.
continue
else:
message = '"field()" does not accept positional arguments'
self._api.fail(message, expr)
return True, {}
assert name is not None
args[name] = arg
return True, args
return False, {}
def _get_bool_arg(self, name: str, default: bool) -> bool:
# Expressions are always CallExprs (either directly or via a wrapper like Decorator), so
# we can use the helpers from common
if isinstance(self._reason, Expression):
return _get_decorator_bool_argument(
ClassDefContext(self._cls, self._reason, self._api), name, default
)
# Subclass/metaclass use of `typing.dataclass_transform` reads the parameters from the
# class's keyword arguments (ie `class Subclass(Parent, kwarg1=..., kwarg2=...)`)
expression = self._cls.keywords.get(name)
if expression is not None:
return require_bool_literal_argument(self._api, expression, name, default)
return default
def _get_default_init_value_for_field_specifier(self, call: Expression) -> bool:
"""
Find a default value for the `init` parameter of the specifier being called. If the
specifier's type signature includes an `init` parameter with a type of `Literal[True]` or
`Literal[False]`, return the appropriate boolean value from the literal. Otherwise,
fall back to the standard default of `True`.
"""
if not isinstance(call, CallExpr):
return True
specifier_type = _get_callee_type(call)
if specifier_type is None:
return True
parameter = specifier_type.argument_by_name("init")
if parameter is None:
return True
literals = try_getting_literals_from_type(parameter.typ, bool, "builtins.bool")
if literals is None or len(literals) != 1:
return True
return literals[0]
def _infer_dataclass_attr_init_type(
self, sym: SymbolTableNode, name: str, context: Context
) -> Type | None:
"""Infer __init__ argument type for an attribute.
In particular, possibly use the signature of __set__.
"""
default = sym.type
if sym.implicit:
return default
t = get_proper_type(sym.type)
# Perform a simple-minded inference from the signature of __set__, if present.
# We can't use mypy.checkmember here, since this plugin runs before type checking.
# We only support some basic scanerios here, which is hopefully sufficient for
# the vast majority of use cases.
if not isinstance(t, Instance):
return default
setter = t.type.get("__set__")
if setter:
if isinstance(setter.node, FuncDef):
super_info = t.type.get_containing_type_info("__set__")
assert super_info
if setter.type:
setter_type = get_proper_type(
map_type_from_supertype(setter.type, t.type, super_info)
)
else:
return AnyType(TypeOfAny.unannotated)
if isinstance(setter_type, CallableType) and setter_type.arg_kinds == [
ARG_POS,
ARG_POS,
ARG_POS,
]:
return expand_type_by_instance(setter_type.arg_types[2], t)
else:
self._api.fail(
f'Unsupported signature for "__set__" in "{t.type.name}"', context
)
else:
self._api.fail(f'Unsupported "__set__" in "{t.type.name}"', context)
return default
def add_dataclass_tag(info: TypeInfo) -> None:
# The value is ignored, only the existence matters.
info.metadata["dataclass_tag"] = {}
def dataclass_tag_callback(ctx: ClassDefContext) -> None:
"""Record that we have a dataclass in the main semantic analysis pass.
The later pass implemented by DataclassTransformer will use this
to detect dataclasses in base classes.
"""
add_dataclass_tag(ctx.cls.info)
def dataclass_class_maker_callback(ctx: ClassDefContext) -> bool:
"""Hooks into the class typechecking process to add support for dataclasses."""
if any(i.is_named_tuple for i in ctx.cls.info.mro):
ctx.api.fail("A NamedTuple cannot be a dataclass", ctx=ctx.cls.info)
return True
transformer = DataclassTransformer(
ctx.cls, ctx.reason, _get_transform_spec(ctx.reason), ctx.api
)
return transformer.transform()
def _get_transform_spec(reason: Expression) -> DataclassTransformSpec:
"""Find the relevant transform parameters from the decorator/parent class/metaclass that
triggered the dataclasses plugin.
Although the resulting DataclassTransformSpec is based on the typing.dataclass_transform
function, we also use it for traditional dataclasses.dataclass classes as well for simplicity.
In those cases, we return a default spec rather than one based on a call to
`typing.dataclass_transform`.
"""
if _is_dataclasses_decorator(reason):
return _TRANSFORM_SPEC_FOR_DATACLASSES
spec = find_dataclass_transform_spec(reason)
assert spec is not None, (
"trying to find dataclass transform spec, but reason is neither dataclasses.dataclass nor "
"decorated with typing.dataclass_transform"
)
return spec
def _is_dataclasses_decorator(node: Node) -> bool:
if isinstance(node, CallExpr):
node = node.callee
if isinstance(node, RefExpr):
return node.fullname in dataclass_makers
return False
def _has_direct_dataclass_transform_metaclass(info: TypeInfo) -> bool:
return (
info.declared_metaclass is not None
and info.declared_metaclass.type.dataclass_transform_spec is not None
)
def _get_expanded_dataclasses_fields(
ctx: FunctionSigContext, typ: ProperType, display_typ: ProperType, parent_typ: ProperType
) -> list[CallableType] | None:
"""
For a given type, determine what dataclasses it can be: for each class, return the field types.
For generic classes, the field types are expanded.
If the type contains Any or a non-dataclass, returns None; in the latter case, also reports an error.
"""
if isinstance(typ, UnionType):
ret: list[CallableType] | None = []
for item in typ.relevant_items():
item = get_proper_type(item)
item_types = _get_expanded_dataclasses_fields(ctx, item, item, parent_typ)
if ret is not None and item_types is not None:
ret += item_types
else:
ret = None # but keep iterating to emit all errors
return ret
elif isinstance(typ, TypeVarType):
return _get_expanded_dataclasses_fields(
ctx, get_proper_type(typ.upper_bound), display_typ, parent_typ
)
elif isinstance(typ, Instance):
replace_sym = typ.type.get_method(_INTERNAL_REPLACE_SYM_NAME)
if replace_sym is None:
return None
replace_sig = replace_sym.type
assert isinstance(replace_sig, ProperType)
assert isinstance(replace_sig, CallableType)
return [expand_type_by_instance(replace_sig, typ)]
else:
return None
# TODO: we can potentially get the function signature hook to allow returning a union
# and leave this to the regular machinery of resolving a union of callables
# (https://github.com/python/mypy/issues/15457)
def _meet_replace_sigs(sigs: list[CallableType]) -> CallableType:
"""
Produces the lowest bound of the 'replace' signatures of multiple dataclasses.
"""
args = {
name: (typ, kind)
for name, typ, kind in zip(sigs[0].arg_names, sigs[0].arg_types, sigs[0].arg_kinds)
}
for sig in sigs[1:]:
sig_args = {
name: (typ, kind)
for name, typ, kind in zip(sig.arg_names, sig.arg_types, sig.arg_kinds)
}
for name in (*args.keys(), *sig_args.keys()):
sig_typ, sig_kind = args.get(name, (UninhabitedType(), ARG_NAMED_OPT))
sig2_typ, sig2_kind = sig_args.get(name, (UninhabitedType(), ARG_NAMED_OPT))
args[name] = (
meet_types(sig_typ, sig2_typ),
ARG_NAMED_OPT if sig_kind == sig2_kind == ARG_NAMED_OPT else ARG_NAMED,
)
return sigs[0].copy_modified(
arg_names=list(args.keys()),
arg_types=[typ for typ, _ in args.values()],
arg_kinds=[kind for _, kind in args.values()],
)
def replace_function_sig_callback(ctx: FunctionSigContext) -> CallableType:
"""
Returns a signature for the 'dataclasses.replace' function that's dependent on the type
of the first positional argument.
"""
if len(ctx.args) != 2:
# Ideally the name and context should be callee's, but we don't have it in FunctionSigContext.
ctx.api.fail(f'"{ctx.default_signature.name}" has unexpected type annotation', ctx.context)
return ctx.default_signature
if len(ctx.args[0]) != 1:
return ctx.default_signature # leave it to the type checker to complain
obj_arg = ctx.args[0][0]
obj_type = get_proper_type(ctx.api.get_expression_type(obj_arg))
inst_type_str = format_type_bare(obj_type, ctx.api.options)
replace_sigs = _get_expanded_dataclasses_fields(ctx, obj_type, obj_type, obj_type)
if replace_sigs is None:
return ctx.default_signature
replace_sig = _meet_replace_sigs(replace_sigs)
return replace_sig.copy_modified(
arg_names=[None, *replace_sig.arg_names],
arg_kinds=[ARG_POS, *replace_sig.arg_kinds],
arg_types=[obj_type, *replace_sig.arg_types],
ret_type=obj_type,
fallback=ctx.default_signature.fallback,
name=f"{ctx.default_signature.name} of {inst_type_str}",
)
def is_processed_dataclass(info: TypeInfo) -> bool:
return bool(info) and "dataclass" in info.metadata
def check_post_init(api: TypeChecker, defn: FuncItem, info: TypeInfo) -> None:
if defn.type is None:
return
assert isinstance(defn.type, FunctionLike)
ideal_sig_method = info.get_method(_INTERNAL_POST_INIT_SYM_NAME)
assert ideal_sig_method is not None and ideal_sig_method.type is not None
ideal_sig = ideal_sig_method.type
assert isinstance(ideal_sig, ProperType) # we set it ourselves
assert isinstance(ideal_sig, CallableType)
ideal_sig = ideal_sig.copy_modified(name="__post_init__")
api.check_override(
override=defn.type,
original=ideal_sig,
name="__post_init__",
name_in_super="__post_init__",
supertype="dataclass",
original_class_or_static=False,
override_class_or_static=False,
node=defn,
)
| DataclassTransformer |
python | openai__openai-python | src/openai/types/beta/thread_create_and_run_params.py | {
"start": 9691,
"end": 10159
} | class ____(TypedDict, total=False):
static: Required[ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStaticStatic]
type: Required[Literal["static"]]
"""Always `static`."""
ThreadToolResourcesFileSearchVectorStoreChunkingStrategy: TypeAlias = Union[
ThreadToolResourcesFileSearchVectorStoreChunkingStrategyAuto,
ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic,
]
| ThreadToolResourcesFileSearchVectorStoreChunkingStrategyStatic |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_table23.py | {
"start": 315,
"end": 1768
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("table23.xlsx")
self.ignore_files = [
"xl/calcChain.xml",
"[Content_Types].xml",
"xl/_rels/workbook.xml.rels",
]
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with tables."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.set_column("B:F", 10.288)
worksheet.write_string("A1", "Column1")
worksheet.write_string("F1", "Total")
worksheet.write_string("B1", "Column'")
worksheet.write_string("C1", "Column#")
worksheet.write_string("D1", "Column[")
worksheet.write_string("E1", "Column]")
worksheet.add_table(
"B3:F9",
{
"total_row": True,
"columns": [
{"header": "Column1", "total_string": "Total"},
{"header": "Column'", "total_function": "sum"},
{"header": "Column#", "total_function": "sum"},
{"header": "Column[", "total_function": "sum"},
{"header": "Column]", "total_function": "sum"},
],
},
)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | wandb__wandb | wandb/filesync/stats.py | {
"start": 102,
"end": 225
} | class ____(NamedTuple):
deduped: bool
total: int
uploaded: int
failed: bool
artifact_file: bool
| FileStats |
python | python-openxml__python-docx | tests/oxml/unitdata/text.py | {
"start": 1260,
"end": 3153
} | class ____(BaseBuilder):
__tag__ = "w:u"
__nspfxs__ = ("w",)
__attrs__ = ("w:val", "w:color", "w:themeColor", "w:themeTint", "w:themeShade")
def a_b():
return CT_OnOffBuilder("w:b")
def a_bCs():
return CT_OnOffBuilder("w:bCs")
def a_br():
return CT_BrBuilder()
def a_caps():
return CT_OnOffBuilder("w:caps")
def a_cr():
return CT_EmptyBuilder("w:cr")
def a_cs():
return CT_OnOffBuilder("w:cs")
def a_dstrike():
return CT_OnOffBuilder("w:dstrike")
def a_jc():
return CT_JcBuilder()
def a_noProof():
return CT_OnOffBuilder("w:noProof")
def a_shadow():
return CT_OnOffBuilder("w:shadow")
def a_smallCaps():
return CT_OnOffBuilder("w:smallCaps")
def a_snapToGrid():
return CT_OnOffBuilder("w:snapToGrid")
def a_specVanish():
return CT_OnOffBuilder("w:specVanish")
def a_strike():
return CT_OnOffBuilder("w:strike")
def a_tab():
return CT_EmptyBuilder("w:tab")
def a_vanish():
return CT_OnOffBuilder("w:vanish")
def a_webHidden():
return CT_OnOffBuilder("w:webHidden")
def a_p():
return CT_PBuilder()
def a_pPr():
return CT_PPrBuilder()
def a_pStyle():
return CT_StringBuilder("w:pStyle")
def a_sectPr():
return CT_SectPrBuilder()
def a_t():
return CT_TextBuilder()
def a_u():
return CT_UnderlineBuilder()
def an_emboss():
return CT_OnOffBuilder("w:emboss")
def an_i():
return CT_OnOffBuilder("w:i")
def an_iCs():
return CT_OnOffBuilder("w:iCs")
def an_imprint():
return CT_OnOffBuilder("w:imprint")
def an_oMath():
return CT_OnOffBuilder("w:oMath")
def an_outline():
return CT_OnOffBuilder("w:outline")
def an_r():
return CT_RBuilder()
def an_rPr():
return CT_RPrBuilder()
def an_rStyle():
return CT_StringBuilder("w:rStyle")
def an_rtl():
return CT_OnOffBuilder("w:rtl")
| CT_UnderlineBuilder |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 19423,
"end": 22250
} | class ____(ASTExpression):
def __init__(
self, leftExpr: ASTExpression | None, op: str, rightExpr: ASTExpression | None
) -> None:
assert leftExpr is not None or rightExpr is not None
self.leftExpr = leftExpr
self.op = op
self.rightExpr = rightExpr
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTFoldExpr):
return NotImplemented
return (
self.leftExpr == other.leftExpr
and self.op == other.op
and self.rightExpr == other.rightExpr
)
def __hash__(self) -> int:
return hash((self.leftExpr, self.op, self.rightExpr))
def _stringify(self, transform: StringifyTransform) -> str:
res = ['(']
if self.leftExpr:
res.extend((
transform(self.leftExpr),
' ',
self.op,
' ',
))
res.append('...')
if self.rightExpr:
res.extend((
' ',
self.op,
' ',
transform(self.rightExpr),
))
res.append(')')
return ''.join(res)
def get_id(self, version: int) -> str:
assert version >= 3
if version == 3:
return str(self)
# https://github.com/itanium-cxx-abi/cxx-abi/pull/67
res = []
if self.leftExpr is None: # (... op expr)
res.append('fl')
elif self.rightExpr is None: # (expr op ...)
res.append('fr')
else: # (expr op ... op expr)
# we don't check where the parameter pack is,
# we just always call this a binary left fold
res.append('fL')
res.append(_id_operator_v2[self.op])
if self.leftExpr:
res.append(self.leftExpr.get_id(version))
if self.rightExpr:
res.append(self.rightExpr.get_id(version))
return ''.join(res)
def describe_signature(
self, signode: TextElement, mode: str, env: BuildEnvironment, symbol: Symbol
) -> None:
signode += addnodes.desc_sig_punctuation('(', '(')
if self.leftExpr:
self.leftExpr.describe_signature(signode, mode, env, symbol)
signode += addnodes.desc_sig_space()
signode += addnodes.desc_sig_operator(self.op, self.op)
signode += addnodes.desc_sig_space()
signode += addnodes.desc_sig_punctuation('...', '...')
if self.rightExpr:
signode += addnodes.desc_sig_space()
signode += addnodes.desc_sig_operator(self.op, self.op)
signode += addnodes.desc_sig_space()
self.rightExpr.describe_signature(signode, mode, env, symbol)
signode += addnodes.desc_sig_punctuation(')', ')')
| ASTFoldExpr |
python | redis__redis-py | tests/test_search.py | {
"start": 70942,
"end": 73800
} | class ____(SearchTestsBase):
@pytest.mark.redismod
@pytest.mark.onlynoncluster
@skip_ifmodversion_lt("2.2.0", "search")
@skip_if_server_version_gte("7.9.0")
def test_config(self, client):
assert client.ft().config_set("TIMEOUT", "100")
with pytest.raises(redis.ResponseError):
client.ft().config_set("TIMEOUT", "null")
res = client.ft().config_get("*")
assert "100" == res["TIMEOUT"]
res = client.ft().config_get("TIMEOUT")
assert "100" == res["TIMEOUT"]
@pytest.mark.redismod
@pytest.mark.onlynoncluster
@skip_if_server_version_lt("7.9.0")
def test_config_with_removed_ftconfig(self, client):
assert client.config_set("timeout", "100")
with pytest.raises(redis.ResponseError):
client.config_set("timeout", "null")
res = client.config_get("*")
assert "100" == res["timeout"]
res = client.config_get("timeout")
assert "100" == res["timeout"]
@pytest.mark.redismod
@pytest.mark.onlynoncluster
@skip_ifmodversion_lt("2.4.3", "search")
def test_dialect_config(self, client):
assert client.ft().config_get("DEFAULT_DIALECT")
client.ft().config_set("DEFAULT_DIALECT", 2)
assert client.ft().config_get("DEFAULT_DIALECT") == {"DEFAULT_DIALECT": "2"}
with pytest.raises(redis.ResponseError):
client.ft().config_set("DEFAULT_DIALECT", 0)
@pytest.mark.redismod
@skip_ifmodversion_lt("2.4.3", "search")
def test_dialect(self, client):
client.ft().create_index(
(
TagField("title"),
TextField("t1"),
TextField("t2"),
NumericField("num"),
VectorField(
"v",
"HNSW",
{"TYPE": "FLOAT32", "DIM": 1, "DISTANCE_METRIC": "COSINE"},
),
)
)
client.hset("h", "t1", "hello")
with pytest.raises(redis.ResponseError) as err:
client.ft().explain(Query("(*)").dialect(1))
assert "Syntax error" in str(err)
assert "WILDCARD" in client.ft().explain(Query("(*)"))
with pytest.raises(redis.ResponseError) as err:
client.ft().explain(Query("$hello").dialect(1))
assert "Syntax error" in str(err)
q = Query("$hello")
expected = "UNION {\n hello\n +hello(expanded)\n}\n"
assert expected in client.ft().explain(q, query_params={"hello": "hello"})
expected = "NUMERIC {0.000000 <= @num <= 10.000000}\n"
assert expected in client.ft().explain(Query("@title:(@num:[0 10])").dialect(1))
with pytest.raises(redis.ResponseError) as err:
client.ft().explain(Query("@title:(@num:[0 10])"))
assert "Syntax error" in str(err)
| TestConfig |
python | python-poetry__poetry | src/poetry/installation/operations/update.py | {
"start": 208,
"end": 1540
} | class ____(Operation):
def __init__(
self,
initial: Package,
target: Package,
reason: str | None = None,
priority: int = 0,
) -> None:
self._initial_package = initial
self._target_package = target
super().__init__(reason, priority=priority)
@property
def initial_package(self) -> Package:
return self._initial_package
@property
def target_package(self) -> Package:
return self._target_package
@property
def package(self) -> Package:
return self._target_package
@property
def job_type(self) -> str:
return "update"
def __str__(self) -> str:
init_version = self.format_version(self.initial_package)
target_version = self.format_version(self.target_package)
return (
f"Updating {self.initial_package.pretty_name} ({init_version}) "
f"to {self.target_package.pretty_name} ({target_version})"
)
def __repr__(self) -> str:
init_version = self.format_version(self.initial_package)
target_version = self.format_version(self.target_package)
return (
f"<Update {self.initial_package.pretty_name} ({init_version}) "
f"to {self.target_package.pretty_name} ({target_version})>"
)
| Update |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 35404,
"end": 38967
} | class ____(TestCase):
def test_equal_lengths(self):
# when lengths are equal, the relative order shouldn't change
a = [1, 2, 3]
b = [5, 6, 7]
actual = list(mi.interleave_evenly([a, b]))
expected = [1, 5, 2, 6, 3, 7]
self.assertEqual(actual, expected)
def test_proportional(self):
# easy case where the iterables have proportional length
a = [1, 2, 3, 4]
b = [5, 6]
actual = list(mi.interleave_evenly([a, b]))
expected = [1, 2, 5, 3, 4, 6]
self.assertEqual(actual, expected)
# swapping a and b should yield the same result
actual_swapped = list(mi.interleave_evenly([b, a]))
self.assertEqual(actual_swapped, expected)
def test_not_proportional(self):
a = [1, 2, 3, 4, 5, 6, 7]
b = [8, 9, 10]
expected = [1, 2, 8, 3, 4, 9, 5, 6, 10, 7]
actual = list(mi.interleave_evenly([a, b]))
self.assertEqual(actual, expected)
def test_degenerate_one(self):
a = [0, 1, 2, 3, 4]
b = [5]
expected = [0, 1, 2, 5, 3, 4]
actual = list(mi.interleave_evenly([a, b]))
self.assertEqual(actual, expected)
def test_degenerate_empty(self):
a = [1, 2, 3]
b = []
expected = [1, 2, 3]
actual = list(mi.interleave_evenly([a, b]))
self.assertEqual(actual, expected)
def test_three_iters(self):
a = ["a1", "a2", "a3", "a4", "a5"]
b = ["b1", "b2", "b3"]
c = ["c1"]
actual = list(mi.interleave_evenly([a, b, c]))
expected = ["a1", "b1", "a2", "c1", "a3", "b2", "a4", "b3", "a5"]
self.assertEqual(actual, expected)
def test_many_iters(self):
# smoke test with many iterables: create iterables with a random
# number of elements starting with a character ("a0", "a1", ...)
rng = Random(0)
iterables = []
for ch in ascii_letters:
length = rng.randint(0, 100)
iterable = [f"{ch}{i}" for i in range(length)]
iterables.append(iterable)
interleaved = list(mi.interleave_evenly(iterables))
# for each iterable, check that the result contains all its items
for iterable, ch_expect in zip(iterables, ascii_letters):
interleaved_actual = [
e for e in interleaved if e.startswith(ch_expect)
]
assert len(set(interleaved_actual)) == len(iterable)
def test_manual_lengths(self):
a = combinations(range(4), 2)
len_a = 4 * (4 - 1) // 2 # == 6
b = combinations(range(4), 3)
len_b = 4
expected = [
(0, 1),
(0, 1, 2),
(0, 2),
(0, 3),
(0, 1, 3),
(1, 2),
(0, 2, 3),
(1, 3),
(2, 3),
(1, 2, 3),
]
actual = list(mi.interleave_evenly([a, b], lengths=[len_a, len_b]))
self.assertEqual(expected, actual)
def test_no_length_raises(self):
# combinations doesn't have __len__, should trigger ValueError
iterables = [range(5), combinations(range(5), 2)]
with self.assertRaises(ValueError):
list(mi.interleave_evenly(iterables))
def test_argument_mismatch_raises(self):
# pass mismatching number of iterables and lengths
iterables = [range(3)]
lengths = [3, 4]
with self.assertRaises(ValueError):
list(mi.interleave_evenly(iterables, lengths=lengths))
| InterleaveEvenlyTests |
python | apache__airflow | providers/databricks/src/airflow/providers/databricks/plugins/databricks_workflow.py | {
"start": 10680,
"end": 13567
} | class ____(BaseOperatorLink, LoggingMixin):
"""Constructs a link to monitor a Databricks Job Run."""
name = "See Databricks Job Run"
@property
def xcom_key(self) -> str:
"""XCom key where the link is stored during task execution."""
return "databricks_job_run_link"
def get_link(
self,
operator: BaseOperator,
dttm=None,
*,
ti_key: TaskInstanceKey | None = None,
) -> str:
if AIRFLOW_V_3_0_PLUS:
# Use public XCom API to get the pre-computed link
try:
link = XCom.get_value(
ti_key=ti_key,
key=self.xcom_key,
)
return link if link else ""
except Exception as e:
self.log.warning("Failed to retrieve Databricks job run link from XCom: %s", e)
return ""
else:
# Airflow 2.x - keep original implementation
return self._get_link_legacy(operator, dttm, ti_key=ti_key)
def _get_link_legacy(
self,
operator: BaseOperator,
dttm=None,
*,
ti_key: TaskInstanceKey | None = None,
) -> str:
"""Legacy implementation for Airflow 2.x."""
if not ti_key:
ti = get_task_instance(operator, dttm)
ti_key = ti.key
task_group = operator.task_group
if not task_group:
raise AirflowException("Task group is required for generating Databricks Workflow Job Run Link.")
self.log.info("Getting link for task %s", ti_key.task_id)
if ".launch" not in ti_key.task_id:
self.log.debug("Finding the launch task for job run metadata %s", ti_key.task_id)
launch_task_id = get_launch_task_id(task_group)
ti_key = _get_launch_task_key(ti_key, task_id=launch_task_id)
metadata = get_xcom_result(ti_key, "return_value")
hook = DatabricksHook(metadata.conn_id)
return f"https://{hook.host}/#job/{metadata.job_id}/run/{metadata.run_id}"
def store_databricks_job_run_link(
context: Context,
metadata: Any,
logger: Logger,
) -> None:
"""
Store the Databricks job run link in XCom during task execution.
This should be called by Databricks operators during their execution.
"""
if not AIRFLOW_V_3_0_PLUS:
return # Only needed for Airflow 3
try:
hook = DatabricksHook(metadata.conn_id)
link = f"https://{hook.host}/#job/{metadata.job_id}/run/{metadata.run_id}"
# Store the link in XCom for the UI to retrieve as extra link
context["ti"].xcom_push(key="databricks_job_run_link", value=link)
logger.info("Stored Databricks job run link in XCom: %s", link)
except Exception as e:
logger.warning("Failed to store Databricks job run link: %s", e)
| WorkflowJobRunLink |
python | kamyu104__LeetCode-Solutions | Python/maximize-value-of-function-in-a-ball-passing-game.py | {
"start": 2694,
"end": 3448
} | class ____(object):
def getMaxFunctionValue(self, receiver, k):
"""
:type receiver: List[int]
:type k: int
:rtype: int
"""
l = (k+1).bit_length()
P = [receiver[:] for _ in xrange(l)]
S = [range(len(receiver)) for _ in xrange(l)]
for i in xrange(1, len(P)):
for u in xrange(len(receiver)):
P[i][u] = P[i-1][P[i-1][u]]
S[i][u] = S[i-1][u]+S[i-1][P[i-1][u]]
result = 0
for u in xrange(len(receiver)):
curr = 0
for i in xrange(l):
if (k+1)&(1<<i):
curr += S[i][u]
u = P[i][u]
result = max(result, curr)
return result
| Solution2 |
python | openai__gym | gym/spaces/multi_binary.py | {
"start": 196,
"end": 4569
} | class ____(Space[np.ndarray]):
"""An n-shape binary space.
Elements of this space are binary arrays of a shape that is fixed during construction.
Example Usage::
>>> observation_space = MultiBinary(5)
>>> observation_space.sample()
array([0, 1, 0, 1, 0], dtype=int8)
>>> observation_space = MultiBinary([3, 2])
>>> observation_space.sample()
array([[0, 0],
[0, 1],
[1, 1]], dtype=int8)
"""
def __init__(
self,
n: Union[np.ndarray, Sequence[int], int],
seed: Optional[Union[int, np.random.Generator]] = None,
):
"""Constructor of :class:`MultiBinary` space.
Args:
n: This will fix the shape of elements of the space. It can either be an integer (if the space is flat)
or some sort of sequence (tuple, list or np.ndarray) if there are multiple axes.
seed: Optionally, you can use this argument to seed the RNG that is used to sample from the space.
"""
if isinstance(n, (Sequence, np.ndarray)):
self.n = input_n = tuple(int(i) for i in n)
assert (np.asarray(input_n) > 0).all() # n (counts) have to be positive
else:
self.n = n = int(n)
input_n = (n,)
assert (np.asarray(input_n) > 0).all() # n (counts) have to be positive
super().__init__(input_n, np.int8, seed)
@property
def shape(self) -> Tuple[int, ...]:
"""Has stricter type than gym.Space - never None."""
return self._shape # type: ignore
@property
def is_np_flattenable(self):
"""Checks whether this space can be flattened to a :class:`spaces.Box`."""
return True
def sample(self, mask: Optional[np.ndarray] = None) -> np.ndarray:
"""Generates a single random sample from this space.
A sample is drawn by independent, fair coin tosses (one toss per binary variable of the space).
Args:
mask: An optional np.ndarray to mask samples with expected shape of ``space.shape``.
For mask == 0 then the samples will be 0 and mask == 1 then random samples will be generated.
The expected mask shape is the space shape and mask dtype is `np.int8`.
Returns:
Sampled values from space
"""
if mask is not None:
assert isinstance(
mask, np.ndarray
), f"The expected type of the mask is np.ndarray, actual type: {type(mask)}"
assert (
mask.dtype == np.int8
), f"The expected dtype of the mask is np.int8, actual dtype: {mask.dtype}"
assert (
mask.shape == self.shape
), f"The expected shape of the mask is {self.shape}, actual shape: {mask.shape}"
assert np.all(
(mask == 0) | (mask == 1) | (mask == 2)
), f"All values of a mask should be 0, 1 or 2, actual values: {mask}"
return np.where(
mask == 2,
self.np_random.integers(low=0, high=2, size=self.n, dtype=self.dtype),
mask.astype(self.dtype),
)
return self.np_random.integers(low=0, high=2, size=self.n, dtype=self.dtype)
def contains(self, x) -> bool:
"""Return boolean specifying if x is a valid member of this space."""
if isinstance(x, Sequence):
x = np.array(x) # Promote list to array for contains check
return bool(
isinstance(x, np.ndarray)
and self.shape == x.shape
and np.all((x == 0) | (x == 1))
)
def to_jsonable(self, sample_n) -> list:
"""Convert a batch of samples from this space to a JSONable data type."""
return np.array(sample_n).tolist()
def from_jsonable(self, sample_n) -> list:
"""Convert a JSONable data type to a batch of samples from this space."""
return [np.asarray(sample, self.dtype) for sample in sample_n]
def __repr__(self) -> str:
"""Gives a string representation of this space."""
return f"MultiBinary({self.n})"
def __eq__(self, other) -> bool:
"""Check whether `other` is equivalent to this instance."""
return isinstance(other, MultiBinary) and self.n == other.n
| MultiBinary |
python | getsentry__sentry | src/sentry/integrations/discord/message_builder/base/component/button.py | {
"start": 141,
"end": 317
} | class ____(DiscordMessageComponentDict):
style: int
custom_id: str
label: NotRequired[str]
url: NotRequired[str]
disabled: NotRequired[bool]
| DiscordButtonDict |
python | celery__celery | celery/utils/text.py | {
"start": 5441,
"end": 5844
} | class ____(StringIO):
"""StringIO that takes bytes or str."""
def __init__(
self, v: bytes | str | None = None, *a: Any, **kw: Any) -> None:
_SIO_init(self, v.decode() if isinstance(v, bytes) else v, *a, **kw)
def write(self, data: bytes | str) -> int:
return _SIO_write(self, data.decode()
if isinstance(data, bytes) else data)
| WhateverIO |
python | getsentry__sentry | src/sentry/lang/native/error.py | {
"start": 1103,
"end": 3450
} | class ____(Exception):
def __init__(self, message=None, type=None, obj=None):
Exception.__init__(self)
self.message = str(message)
self.type = type
self.image_name: str | None = None
self.image_path: str | None = None
if obj is not None:
self.image_uuid: str | None = str(obj.debug_id)
if obj.name:
self.image_path = obj.name
self.image_name = image_name(obj.name)
self.image_arch: str | None = obj.arch
else:
self.image_uuid = None
self.image_arch = None
@property
def is_user_fixable(self):
"""These are errors that a user can fix themselves."""
return self.type in USER_FIXABLE_ERRORS
@property
def is_fatal(self):
"""If this is true then a processing issues has to be reported."""
return self.type in FATAL_ERRORS
@property
def is_sdk_failure(self):
"""An error that most likely happened because of a bad SDK."""
return self.type == EventError.NATIVE_UNKNOWN_IMAGE
def get_data(self):
"""Returns the event data."""
rv = {"message": self.message, "type": self.type}
if self.image_path is not None:
rv["image_path"] = self.image_path
if self.image_uuid is not None:
rv["image_uuid"] = self.image_uuid
if self.image_arch is not None:
rv["image_arch"] = self.image_arch
return rv
def __str__(self) -> str:
rv = []
if self.type is not None:
rv.append("%s: " % self.type)
rv.append(self.message or "no information available")
if self.image_uuid is not None:
rv.append(" image-uuid=%s" % self.image_uuid)
if self.image_name is not None:
rv.append(" image-name=%s" % self.image_name)
return "".join(rv)
def write_error(e, data):
if e.is_user_fixable or e.is_sdk_failure:
errors = data.setdefault("errors", [])
errors.append(e.get_data())
else:
logger.debug("Failed to symbolicate with native backend")
if not e.is_user_fixable:
data.setdefault("_metrics", {})["flag.processing.error"] = True
if e.is_fatal:
data.setdefault("_metrics", {})["flag.processing.fatal"] = True
| SymbolicationFailed |
python | getsentry__sentry | tests/sentry/dashboards/endpoints/test_organization_dashboards_starred.py | {
"start": 3549,
"end": 7802
} | class ____(StarredDashboardTestCase):
def setUp(self) -> None:
super().setUp()
self.login_as(self.user)
self.url = reverse(
"sentry-api-0-organization-dashboard-starred-order",
kwargs={"organization_id_or_slug": self.organization.slug},
)
self.dashboard_1 = self.create_dashboard(title="Dashboard 1")
self.dashboard_2 = self.create_dashboard(title="Dashboard 2")
self.dashboard_3 = self.create_dashboard(title="Dashboard 3")
def test_reorder_dashboards(self) -> None:
self.create_dashboard_favorite(self.dashboard_1, self.user, self.organization, 0)
self.create_dashboard_favorite(self.dashboard_2, self.user, self.organization, 1)
self.create_dashboard_favorite(self.dashboard_3, self.user, self.organization, 2)
assert list(
DashboardFavoriteUser.objects.filter(
organization=self.organization, user_id=self.user.id
)
.order_by("position")
.values_list("dashboard_id", flat=True)
) == [
self.dashboard_1.id,
self.dashboard_2.id,
self.dashboard_3.id,
]
# Reorder the favorited dashboards
response = self.do_request(
"put",
self.url,
data={"dashboard_ids": [self.dashboard_3.id, self.dashboard_1.id, self.dashboard_2.id]},
)
assert response.status_code == 204
assert list(
DashboardFavoriteUser.objects.filter(
organization=self.organization, user_id=self.user.id
)
.order_by("position")
.values_list("dashboard_id", flat=True)
) == [
self.dashboard_3.id,
self.dashboard_1.id,
self.dashboard_2.id,
]
def test_throws_an_error_if_dashboard_ids_are_not_unique(self) -> None:
self.create_dashboard_favorite(self.dashboard_1, self.user, self.organization, 0)
self.create_dashboard_favorite(self.dashboard_2, self.user, self.organization, 1)
self.create_dashboard_favorite(self.dashboard_3, self.user, self.organization, 2)
response = self.do_request(
"put",
self.url,
data={"dashboard_ids": [self.dashboard_1.id, self.dashboard_1.id, self.dashboard_2.id]},
)
assert response.status_code == 400
assert response.data == {
"dashboard_ids": ["Single dashboard cannot take up multiple positions"]
}
def test_throws_an_error_if_reordered_dashboard_ids_are_not_complete(self) -> None:
self.create_dashboard_favorite(self.dashboard_1, self.user, self.organization, 0)
self.create_dashboard_favorite(self.dashboard_2, self.user, self.organization, 1)
self.create_dashboard_favorite(self.dashboard_3, self.user, self.organization, 2)
response = self.do_request(
"put",
self.url,
data={"dashboard_ids": [self.dashboard_1.id, self.dashboard_2.id]},
)
assert response.status_code == 400
assert response.data == {
"detail": ErrorDetail(
string="Mismatch between existing and provided starred dashboards.",
code="parse_error",
)
}
def test_allows_reordering_even_if_no_initial_positions(self) -> None:
self.create_dashboard_favorite(self.dashboard_1, self.user, self.organization, 0)
self.create_dashboard_favorite(self.dashboard_2, self.user, self.organization, 1)
self.create_dashboard_favorite(self.dashboard_3, self.user, self.organization, 2)
response = self.do_request(
"put",
self.url,
data={"dashboard_ids": [self.dashboard_3.id, self.dashboard_1.id, self.dashboard_2.id]},
)
assert response.status_code == 204
assert list(
DashboardFavoriteUser.objects.filter(
organization=self.organization, user_id=self.user.id
)
.order_by("position")
.values_list("dashboard_id", flat=True)
) == [self.dashboard_3.id, self.dashboard_1.id, self.dashboard_2.id]
| OrganizationDashboardsStarredOrderTest |
python | langchain-ai__langchain | libs/langchain/langchain_classic/memory/token_buffer.py | {
"start": 494,
"end": 2572
} | class ____(BaseChatMemory):
"""Conversation chat memory with token limit.
Keeps only the most recent messages in the conversation under the constraint
that the total number of tokens in the conversation does not exceed a certain limit.
"""
human_prefix: str = "Human"
ai_prefix: str = "AI"
llm: BaseLanguageModel
memory_key: str = "history"
max_token_limit: int = 2000
@property
def buffer(self) -> Any:
"""String buffer of memory."""
return self.buffer_as_messages if self.return_messages else self.buffer_as_str
@property
def buffer_as_str(self) -> str:
"""Exposes the buffer as a string in case return_messages is False."""
return get_buffer_string(
self.chat_memory.messages,
human_prefix=self.human_prefix,
ai_prefix=self.ai_prefix,
)
@property
def buffer_as_messages(self) -> list[BaseMessage]:
"""Exposes the buffer as a list of messages in case return_messages is True."""
return self.chat_memory.messages
@property
def memory_variables(self) -> list[str]:
"""Will always return list of memory variables."""
return [self.memory_key]
@override
def load_memory_variables(self, inputs: dict[str, Any]) -> dict[str, Any]:
"""Return history buffer."""
return {self.memory_key: self.buffer}
def save_context(self, inputs: dict[str, Any], outputs: dict[str, str]) -> None:
"""Save context from this conversation to buffer. Pruned."""
super().save_context(inputs, outputs)
# Prune buffer if it exceeds max token limit
buffer = self.chat_memory.messages
curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer)
if curr_buffer_length > self.max_token_limit:
pruned_memory = []
while curr_buffer_length > self.max_token_limit:
pruned_memory.append(buffer.pop(0))
curr_buffer_length = self.llm.get_num_tokens_from_messages(buffer)
| ConversationTokenBufferMemory |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/torch_entities/networks.py | {
"start": 7157,
"end": 10167
} | class ____(nn.Module):
def __init__(
self,
observation_specs: List[ObservationSpec],
network_settings: NetworkSettings,
encoded_act_size: int = 0,
):
super().__init__()
self.normalize = network_settings.normalize
self.use_lstm = network_settings.memory is not None
self.h_size = network_settings.hidden_units
self.m_size = (
network_settings.memory.memory_size
if network_settings.memory is not None
else 0
)
self.observation_encoder = ObservationEncoder(
observation_specs,
self.h_size,
network_settings.vis_encode_type,
self.normalize,
)
self.processors = self.observation_encoder.processors
total_enc_size = self.observation_encoder.total_enc_size
total_enc_size += encoded_act_size
if (
self.observation_encoder.total_goal_enc_size > 0
and network_settings.goal_conditioning_type == ConditioningType.HYPER
):
self._body_endoder = ConditionalEncoder(
total_enc_size,
self.observation_encoder.total_goal_enc_size,
self.h_size,
network_settings.num_layers,
1,
)
else:
self._body_endoder = LinearEncoder(
total_enc_size, network_settings.num_layers, self.h_size
)
if self.use_lstm:
self.lstm = LSTM(self.h_size, self.m_size)
else:
self.lstm = None # type: ignore
def update_normalization(self, buffer: AgentBuffer) -> None:
self.observation_encoder.update_normalization(buffer)
def copy_normalization(self, other_network: "NetworkBody") -> None:
self.observation_encoder.copy_normalization(other_network.observation_encoder)
@property
def memory_size(self) -> int:
return self.lstm.memory_size if self.use_lstm else 0
def forward(
self,
inputs: List[torch.Tensor],
actions: Optional[torch.Tensor] = None,
memories: Optional[torch.Tensor] = None,
sequence_length: int = 1,
) -> Tuple[torch.Tensor, torch.Tensor]:
encoded_self = self.observation_encoder(inputs)
if actions is not None:
encoded_self = torch.cat([encoded_self, actions], dim=1)
if isinstance(self._body_endoder, ConditionalEncoder):
goal = self.observation_encoder.get_goal_encoding(inputs)
encoding = self._body_endoder(encoded_self, goal)
else:
encoding = self._body_endoder(encoded_self)
if self.use_lstm:
# Resize to (batch, sequence length, encoding size)
encoding = encoding.reshape([-1, sequence_length, self.h_size])
encoding, memories = self.lstm(encoding, memories)
encoding = encoding.reshape([-1, self.m_size // 2])
return encoding, memories
| NetworkBody |
python | redis__redis-py | redis/asyncio/multidb/healthcheck.py | {
"start": 4260,
"end": 5518
} | class ____(AbstractHealthCheckPolicy):
"""
Policy that returns True if at least one health check probe is successful.
"""
def __init__(self, health_check_probes: int, health_check_delay: float):
super().__init__(health_check_probes, health_check_delay)
async def execute(self, health_checks: List[HealthCheck], database) -> bool:
is_healthy = False
for health_check in health_checks:
exception = None
for attempt in range(self.health_check_probes):
try:
if await health_check.check_health(database):
is_healthy = True
break
else:
is_healthy = False
except Exception as e:
exception = UnhealthyDatabaseException(
"Unhealthy database", database, e
)
if attempt < self.health_check_probes - 1:
await asyncio.sleep(self._health_check_delay)
if not is_healthy and not exception:
return is_healthy
elif not is_healthy and exception:
raise exception
return is_healthy
| HealthyAnyPolicy |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.