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 | google__pytype | pytype/abstract/_instances.py | {
"start": 6909,
"end": 9102
} | class ____(_instance_base.Instance):
"""A base class of instances of generators and async generators."""
def __init__(
self,
generator_type: _instance_base.SimpleValue,
frame: "state.Frame",
ctx: "context.Context",
is_return_allowed: bool,
) -> None:
super().__init__(generator_type, ctx)
self.frame = frame
self.runs = 0
self.is_return_allowed = is_return_allowed # if return statement is allowed
def run_generator(
self, node: cfg.CFGNode
) -> tuple[cfg.CFGNode, cfg.Variable]:
"""Run the generator."""
if self.runs == 0: # Optimization: We only run it once.
node, _ = self.ctx.vm.resume_frame(node, self.frame)
ret_type = self.frame.allowed_returns
if ret_type:
# set type parameters according to annotated Generator return type
type_params = [abstract_utils.T, abstract_utils.T2]
if self.is_return_allowed:
type_params.append(abstract_utils.V)
for param_name in type_params:
param_var = self.ctx.vm.init_class(
node, ret_type.get_formal_type_parameter(param_name)
)
self.merge_instance_type_parameter(node, param_name, param_var)
else:
# infer the type parameters based on the collected type information.
self.merge_instance_type_parameter(
node, abstract_utils.T, self.frame.yield_variable
)
# For T2 type, it can not be decided until the send/asend function is
# called later on. So set T2 type as ANY so that the type check will
# not fail when the function is called afterwards.
self.merge_instance_type_parameter(
node, abstract_utils.T2, self.ctx.new_unsolvable(node)
)
if self.is_return_allowed:
self.merge_instance_type_parameter(
node, abstract_utils.V, self.frame.return_variable
)
self.runs += 1
return node, self.get_instance_type_parameter(abstract_utils.T)
def call(self, node, func, args, alias_map=None):
"""Call this generator or (more common) its "next/anext" attribute."""
del func, args
return self.run_generator(node)
| BaseGenerator |
python | pypa__setuptools | setuptools/_vendor/wheel/vendored/packaging/markers.py | {
"start": 5790,
"end": 8230
} | class ____:
def __init__(self, marker: str) -> None:
# Note: We create a Marker object without calling this constructor in
# packaging.requirements.Requirement. If any additional logic is
# added here, make sure to mirror/adapt Requirement.
try:
self._markers = _normalize_extra_values(_parse_marker(marker))
# The attribute `_markers` can be described in terms of a recursive type:
# MarkerList = List[Union[Tuple[Node, ...], str, MarkerList]]
#
# For example, the following expression:
# python_version > "3.6" or (python_version == "3.6" and os_name == "unix")
#
# is parsed into:
# [
# (<Variable('python_version')>, <Op('>')>, <Value('3.6')>),
# 'and',
# [
# (<Variable('python_version')>, <Op('==')>, <Value('3.6')>),
# 'or',
# (<Variable('os_name')>, <Op('==')>, <Value('unix')>)
# ]
# ]
except ParserSyntaxError as e:
raise InvalidMarker(str(e)) from e
def __str__(self) -> str:
return _format_marker(self._markers)
def __repr__(self) -> str:
return f"<Marker('{self}')>"
def __hash__(self) -> int:
return hash((self.__class__.__name__, str(self)))
def __eq__(self, other: Any) -> bool:
if not isinstance(other, Marker):
return NotImplemented
return str(self) == str(other)
def evaluate(self, environment: Optional[Dict[str, str]] = None) -> bool:
"""Evaluate a marker.
Return the boolean from evaluating the given marker against the
environment. environment is an optional argument to override all or
part of the determined environment.
The environment is determined from the current Python process.
"""
current_environment = default_environment()
current_environment["extra"] = ""
if environment is not None:
current_environment.update(environment)
# The API used to allow setting extra to None. We need to handle this
# case for backwards compatibility.
if current_environment["extra"] is None:
current_environment["extra"] = ""
return _evaluate_markers(self._markers, current_environment)
| Marker |
python | wandb__wandb | wandb/sdk/data_types/_dtypes.py | {
"start": 11519,
"end": 13020
} | class ____(Type):
name = "number"
types: t.ClassVar[t.List[type]] = [int, float]
if np:
NumberType.types.append(np.byte)
NumberType.types.append(np.short)
NumberType.types.append(np.ushort)
NumberType.types.append(np.intc)
NumberType.types.append(np.uintc)
NumberType.types.append(np.int_)
NumberType.types.append(np.uint)
NumberType.types.append(np.longlong)
NumberType.types.append(np.ulonglong)
NumberType.types.append(np.half)
NumberType.types.append(np.float16)
NumberType.types.append(np.single)
NumberType.types.append(np.double)
NumberType.types.append(np.longdouble)
NumberType.types.append(np.csingle)
NumberType.types.append(np.cdouble)
NumberType.types.append(np.clongdouble)
NumberType.types.append(np.int8)
NumberType.types.append(np.int16)
NumberType.types.append(np.int32)
NumberType.types.append(np.int64)
NumberType.types.append(np.uint8)
NumberType.types.append(np.uint16)
NumberType.types.append(np.uint32)
NumberType.types.append(np.uint64)
NumberType.types.append(np.intp)
NumberType.types.append(np.uintp)
NumberType.types.append(np.float32)
NumberType.types.append(np.float64)
NumberType.types.append(np.complex64)
NumberType.types.append(np.complex128)
numpy_major_version = np.__version__.split(".")[0]
if int(numpy_major_version) < 2:
NumberType.types.append(np.float_)
NumberType.types.append(np.complex_)
| NumberType |
python | ray-project__ray | python/ray/util/state/common.py | {
"start": 22952,
"end": 24823
} | class ____(StateSchema, JobDetails if JobDetails is not None else object):
"""The state of the job that's submitted by Ray's Job APIs or driver jobs"""
def __init__(self, **kwargs):
JobDetails.__init__(self, **kwargs)
@classmethod
def filterable_columns(cls) -> Set[str]:
# We are not doing any filtering since filtering is currently done
# at the backend.
return {"job_id", "type", "status", "submission_id"}
@classmethod
def humanify(cls, state: dict) -> dict:
return state
@classmethod
def list_columns(cls, detail: bool = True) -> List[str]:
if not detail:
return [
"job_id",
"submission_id",
"entrypoint",
"type",
"status",
"message",
"error_type",
"driver_info",
]
if JobDetails is None:
# We don't have pydantic in the dashboard. This is because
# we call this method at module import time, so we need to
# check if the class is a pydantic model.
return []
# TODO(aguo): Once we only support pydantic 2, we can remove this if check.
# In pydantic 2.0, `__fields__` has been renamed to `model_fields`.
return (
list(JobDetails.model_fields.keys())
if hasattr(JobDetails, "model_fields")
else list(JobDetails.__fields__.keys())
)
def asdict(self):
return JobDetails.dict(self)
@classmethod
def schema_dict(cls) -> Dict[str, Any]:
schema_types = cls.schema()["properties"]
# Get type name to actual type mapping.
return {
k: v["type"] for k, v in schema_types.items() if v.get("type") is not None
}
@dataclass(init=not IS_PYDANTIC_2)
| JobState |
python | readthedocs__readthedocs.org | readthedocs/api/v2/serializers.py | {
"start": 12643,
"end": 13682
} | class ____(serializers.RelatedField):
"""
Attached to related field for Notifications.
Used together with ``rest-framework-generic-relations`` to accept multiple object types on ``attached_to``.
See https://github.com/LilyFoote/rest-framework-generic-relations
"""
default_error_messages = {
"required": _("This field is required."),
"does_not_exist": _("Object does not exist."),
"incorrect_type": _("Incorrect type. Expected URL string, received {data_type}."),
}
def to_representation(self, value):
return f"{self.queryset.model._meta.model_name}/{value.pk}"
def to_internal_value(self, data):
# TODO: handle exceptions
model, pk = data.strip("/").split("/")
if self.queryset.model._meta.model_name != model:
self.fail("incorrect_type")
try:
return self.queryset.get(pk=pk)
except (ObjectDoesNotExist, ValueError, TypeError):
self.fail("does_not_exist")
| NotificationAttachedToRelatedField |
python | scipy__scipy | scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py | {
"start": 3990,
"end": 11689
} | class ____(TestCase):
def test_2d_box_constraints(self):
# Box constraint in the direction of vector d
ta, tb, intersect = box_intersections([2, 0], [0, 2],
[1, 1], [3, 3])
assert_array_almost_equal([ta, tb], [0.5, 1])
assert_equal(intersect, True)
# Negative direction
ta, tb, intersect = box_intersections([2, 0], [0, 2],
[1, -3], [3, -1])
assert_equal(intersect, False)
# Some constraints are absent (set to +/- inf)
ta, tb, intersect = box_intersections([2, 0], [0, 2],
[-np.inf, 1],
[np.inf, np.inf])
assert_array_almost_equal([ta, tb], [0.5, 1])
assert_equal(intersect, True)
# Intersect on the face of the box
ta, tb, intersect = box_intersections([1, 0], [0, 1],
[1, 1], [3, 3])
assert_array_almost_equal([ta, tb], [1, 1])
assert_equal(intersect, True)
# Interior initial point
ta, tb, intersect = box_intersections([0, 0], [4, 4],
[-2, -3], [3, 2])
assert_array_almost_equal([ta, tb], [0, 0.5])
assert_equal(intersect, True)
# No intersection between line and box constraints
ta, tb, intersect = box_intersections([2, 0], [0, 2],
[-3, -3], [-1, -1])
assert_equal(intersect, False)
ta, tb, intersect = box_intersections([2, 0], [0, 2],
[-3, 3], [-1, 1])
assert_equal(intersect, False)
ta, tb, intersect = box_intersections([2, 0], [0, 2],
[-3, -np.inf],
[-1, np.inf])
assert_equal(intersect, False)
ta, tb, intersect = box_intersections([0, 0], [1, 100],
[1, 1], [3, 3])
assert_equal(intersect, False)
ta, tb, intersect = box_intersections([0.99, 0], [0, 2],
[1, 1], [3, 3])
assert_equal(intersect, False)
# Initial point on the boundary
ta, tb, intersect = box_intersections([2, 2], [0, 1],
[-2, -2], [2, 2])
assert_array_almost_equal([ta, tb], [0, 0])
assert_equal(intersect, True)
def test_2d_box_constraints_entire_line(self):
# Box constraint in the direction of vector d
ta, tb, intersect = box_intersections([2, 0], [0, 2],
[1, 1], [3, 3],
entire_line=True)
assert_array_almost_equal([ta, tb], [0.5, 1.5])
assert_equal(intersect, True)
# Negative direction
ta, tb, intersect = box_intersections([2, 0], [0, 2],
[1, -3], [3, -1],
entire_line=True)
assert_array_almost_equal([ta, tb], [-1.5, -0.5])
assert_equal(intersect, True)
# Some constraints are absent (set to +/- inf)
ta, tb, intersect = box_intersections([2, 0], [0, 2],
[-np.inf, 1],
[np.inf, np.inf],
entire_line=True)
assert_array_almost_equal([ta, tb], [0.5, np.inf])
assert_equal(intersect, True)
# Intersect on the face of the box
ta, tb, intersect = box_intersections([1, 0], [0, 1],
[1, 1], [3, 3],
entire_line=True)
assert_array_almost_equal([ta, tb], [1, 3])
assert_equal(intersect, True)
# Interior initial point
ta, tb, intersect = box_intersections([0, 0], [4, 4],
[-2, -3], [3, 2],
entire_line=True)
assert_array_almost_equal([ta, tb], [-0.5, 0.5])
assert_equal(intersect, True)
# No intersection between line and box constraints
ta, tb, intersect = box_intersections([2, 0], [0, 2],
[-3, -3], [-1, -1],
entire_line=True)
assert_equal(intersect, False)
ta, tb, intersect = box_intersections([2, 0], [0, 2],
[-3, 3], [-1, 1],
entire_line=True)
assert_equal(intersect, False)
ta, tb, intersect = box_intersections([2, 0], [0, 2],
[-3, -np.inf],
[-1, np.inf],
entire_line=True)
assert_equal(intersect, False)
ta, tb, intersect = box_intersections([0, 0], [1, 100],
[1, 1], [3, 3],
entire_line=True)
assert_equal(intersect, False)
ta, tb, intersect = box_intersections([0.99, 0], [0, 2],
[1, 1], [3, 3],
entire_line=True)
assert_equal(intersect, False)
# Initial point on the boundary
ta, tb, intersect = box_intersections([2, 2], [0, 1],
[-2, -2], [2, 2],
entire_line=True)
assert_array_almost_equal([ta, tb], [-4, 0])
assert_equal(intersect, True)
def test_3d_box_constraints(self):
# Simple case
ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, 1],
[1, 1, 1], [3, 3, 3])
assert_array_almost_equal([ta, tb], [1, 1])
assert_equal(intersect, True)
# Negative direction
ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, -1],
[1, 1, 1], [3, 3, 3])
assert_equal(intersect, False)
# Interior point
ta, tb, intersect = box_intersections([2, 2, 2], [0, -1, 1],
[1, 1, 1], [3, 3, 3])
assert_array_almost_equal([ta, tb], [0, 1])
assert_equal(intersect, True)
def test_3d_box_constraints_entire_line(self):
# Simple case
ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, 1],
[1, 1, 1], [3, 3, 3],
entire_line=True)
assert_array_almost_equal([ta, tb], [1, 3])
assert_equal(intersect, True)
# Negative direction
ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, -1],
[1, 1, 1], [3, 3, 3],
entire_line=True)
assert_array_almost_equal([ta, tb], [-3, -1])
assert_equal(intersect, True)
# Interior point
ta, tb, intersect = box_intersections([2, 2, 2], [0, -1, 1],
[1, 1, 1], [3, 3, 3],
entire_line=True)
assert_array_almost_equal([ta, tb], [-1, 1])
assert_equal(intersect, True)
| TestBoxBoundariesIntersections |
python | modin-project__modin | modin/core/dataframe/base/dataframe/utils.py | {
"start": 1787,
"end": 6894
} | class ____(Enum): # noqa: PR01
"""
An enum that represents the `join_type` argument provided to the algebra operators.
The enum has 4 values - INNER to represent inner joins, LEFT to represent left joins, RIGHT to
represent right joins, and OUTER to represent outer joins.
"""
INNER = "inner"
LEFT = "left"
RIGHT = "right"
OUTER = "outer"
def join_columns(
left: pandas.Index,
right: pandas.Index,
left_on: IndexLabel,
right_on: IndexLabel,
suffixes: Tuple[str, str],
) -> Tuple[pandas.Index, Dict[IndexLabel, IndexLabel], Dict[IndexLabel, IndexLabel]]:
"""
Compute resulting columns for the two dataframes being merged.
Parameters
----------
left : pandas.Index
Columns of the left frame to join.
right : pandas.Index
Columns of the right frame to join.
left_on : list-like or scalar
Column names on which the frames are joined in the left DataFrame.
right_on : list-like or scalar
Column names on which the frames are joined in the right DataFrame.
suffixes : tuple[str, str]
A 2-length sequence containing suffixes to append to the intersected columns.
Returns
-------
pandas.Index, dict[IndexLabel -> IndexLabel], dict[IndexLabel -> IndexLabel]
Returns columns for the resulting frame and mappings of old to new column
names for `left` and `right` accordingly.
Raises
------
NotImplementedError
Raised when one of the keys to join is an index level, pandas behaviour is really
complicated in this case, so we're not supporting this case for now.
"""
# using `cast` to make `mypy` acknowledged that the variable now ensured to be `Sequence[IndexLabel]`
left_on = cast(Sequence[IndexLabel], [left_on] if is_scalar(left_on) else left_on)
right_on = cast(
Sequence[IndexLabel], [right_on] if is_scalar(right_on) else right_on
)
# handling a simple case of merging on one column and when the column is located in an index
if len(left_on) == 1 and len(right_on) == 1 and left_on[0] == right_on[0]:
if left_on[0] not in left and right_on[0] not in right:
# in this case the 'on' column will stay in the index, so we can simply
# drop the 'left/right_on' values and proceed as normal
left_on = []
right_on = []
# in other cases, we can simply add the index name to columns and proceed as normal
# on python 3.9 with pandas-stubs 2.2, these lines will warn about insert being an untyped call,
# but this error is no longer present on higher versions
elif left_on[0] not in left:
left = left.insert(loc=0, item=left_on[0]) # type: ignore[no-untyped-call, unused-ignore]
elif right_on[0] not in right:
right = right.insert(loc=0, item=right_on[0]) # type: ignore[no-untyped-call, unused-ignore]
if any(col not in left for col in left_on) or any(
col not in right for col in right_on
):
raise NotImplementedError(
"Cases, where one of the keys to join is an index level, are not yet supported."
)
left_conflicts = set(left) & (set(right) - set(right_on))
right_conflicts = set(right) & (set(left) - set(left_on))
conflicting_cols = left_conflicts | right_conflicts
def _get_new_name(col: IndexLabel, suffix: str) -> IndexLabel:
if col in conflicting_cols:
return (
(f"{col[0]}{suffix}", *col[1:])
if isinstance(col, tuple)
else f"{col}{suffix}"
)
else:
return col
left_renamer: Dict[IndexLabel, IndexLabel] = {}
right_renamer: Dict[IndexLabel, IndexLabel] = {}
new_left: List = []
new_right: List = []
for col in left:
new_name = _get_new_name(col, suffixes[0])
new_left.append(new_name)
left_renamer[col] = new_name
for col in right:
# If we're joining on the column that exists in both frames then it was already
# taken from the 'left', don't want to take it again from the 'right'.
if not (col in left_on and col in right_on):
new_name = _get_new_name(col, suffixes[1])
new_right.append(new_name)
right_renamer[col] = new_name
new_columns = pandas.Index(new_left + new_right)
return new_columns, left_renamer, right_renamer
def is_trivial_index(index: pandas.Index) -> bool:
"""
Check if the index is a trivial index, i.e. a sequence [0..n].
Parameters
----------
index : pandas.Index
An index to check.
Returns
-------
bool
"""
if len(index) == 0:
return True
if isinstance(index, pandas.RangeIndex):
return index.start == 0 and index.step == 1
if not (isinstance(index, pandas.Index) and is_integer_dtype(index)):
return False
return (
index.is_monotonic_increasing
and index.is_unique
and index.min() == 0
and index.max() == len(index) - 1
)
| JoinType |
python | dask__distributed | distributed/shuffle/tests/test_buffer.py | {
"start": 502,
"end": 3961
} | class ____(ShardsBuffer):
def __init__(self, memory_limiter: ResourceLimiter, concurrency_limit: int) -> None:
self.allow_process = asyncio.Event()
self.storage: dict[str, bytes] = defaultdict(bytes)
super().__init__(
memory_limiter=memory_limiter, concurrency_limit=concurrency_limit
)
async def _process(self, id: str, shards: list[bytes]) -> None:
await self.allow_process.wait()
self.storage[id] += b"".join(shards)
def read(self, id: str) -> bytes:
return self.storage[id]
limit = parse_bytes("10.0 MiB")
@pytest.mark.parametrize(
"big_payloads",
[
[{"big": gen_bytes(2, limit)}],
[{"big": gen_bytes(0.5, limit)}] * 4,
[{f"big-{ix}": gen_bytes(0.5, limit)} for ix in range(4)],
[{f"big-{ix}": gen_bytes(0.5, limit)} for ix in range(2)] * 2,
],
)
@gen_test()
async def test_memory_limit(big_payloads):
small_payload = {"small": gen_bytes(0.1, limit)}
limiter = ResourceLimiter(limit, "my_label")
async with BufferTest(
memory_limiter=limiter,
concurrency_limit=2,
) as buf:
with captured_context_meter() as metrics:
# It's OK to write nothing
await buf.write({})
assert buf.avg_size == 0
many_small = [
asyncio.create_task(buf.write(small_payload)) for _ in range(9)
]
buf.allow_process.set()
many_small = asyncio.gather(*many_small)
# Puts that do not breach the limit do not block
await many_small
assert metrics.keys() == {("my_label", "count")} # non-blocking only
buf.allow_process.clear()
many_small = [
asyncio.create_task(buf.write(small_payload)) for _ in range(11)
]
assert buf.memory_limiter
while buf.memory_limiter.available:
await asyncio.sleep(0.1)
new_put = asyncio.create_task(buf.write(small_payload))
with pytest.raises(asyncio.TimeoutError):
await wait_for(asyncio.shield(new_put), 0.1)
buf.allow_process.set()
await asyncio.gather(new_put, *many_small)
while not buf.memory_limiter.empty:
await asyncio.sleep(0.1)
buf.allow_process.clear()
big_tasks = [
asyncio.create_task(buf.write(big_payload))
for big_payload in big_payloads
]
small = asyncio.create_task(buf.write(small_payload))
with pytest.raises(asyncio.TimeoutError):
await wait_for(asyncio.shield(asyncio.gather(*big_tasks)), 0.1)
with pytest.raises(asyncio.TimeoutError):
await wait_for(asyncio.shield(small), 0.1)
# Puts only return once we're below memory limit
buf.allow_process.set()
await asyncio.gather(*big_tasks)
await small
# Once the big write is through, we can write without blocking again
before_count = metrics["my_label", "count"]
before_seconds = metrics["my_label", "seconds"]
assert before_seconds > 0
await buf.write(small_payload)
assert metrics["my_label", "count"] == before_count + 1
assert metrics["my_label", "seconds"] == before_seconds
assert buf.avg_size > 0
| BufferTest |
python | django-haystack__django-haystack | test_haystack/elasticsearch_tests/test_elasticsearch_backend.py | {
"start": 50953,
"end": 53666
} | class ____(TestCase):
fixtures = ["base_data.json", "bulk_data.json"]
def setUp(self):
super().setUp()
# Wipe it clean.
clear_elasticsearch_index()
self.old_ui = connections["elasticsearch"].get_unified_index()
self.ui = UnifiedIndex()
self.smmi = ElasticsearchMockModelSearchIndex()
self.sammi = ElasticsearchAnotherMockModelSearchIndex()
self.ui.build(indexes=[self.smmi, self.sammi])
connections["elasticsearch"]._index = self.ui
self.sqs = SearchQuerySet("elasticsearch")
self.smmi.update(using="elasticsearch")
self.sammi.update(using="elasticsearch")
def tearDown(self):
# Restore.
connections["elasticsearch"]._index = self.old_ui
super().tearDown()
def test_more_like_this(self):
mlt = self.sqs.more_like_this(MockModel.objects.get(pk=1))
self.assertEqual(mlt.count(), 4)
self.assertEqual(
set([result.pk for result in mlt]), set(["2", "6", "16", "23"])
)
self.assertEqual(len([result.pk for result in mlt]), 4)
alt_mlt = self.sqs.filter(name="daniel3").more_like_this(
MockModel.objects.get(pk=2)
)
self.assertEqual(alt_mlt.count(), 6)
self.assertEqual(
set([result.pk for result in alt_mlt]),
set(["2", "6", "16", "23", "1", "11"]),
)
self.assertEqual(len([result.pk for result in alt_mlt]), 6)
alt_mlt_with_models = self.sqs.models(MockModel).more_like_this(
MockModel.objects.get(pk=1)
)
self.assertEqual(alt_mlt_with_models.count(), 4)
self.assertEqual(
set([result.pk for result in alt_mlt_with_models]),
set(["2", "6", "16", "23"]),
)
self.assertEqual(len([result.pk for result in alt_mlt_with_models]), 4)
if hasattr(MockModel.objects, "defer"):
# Make sure MLT works with deferred bits.
mi = MockModel.objects.defer("foo").get(pk=1)
deferred = self.sqs.models(MockModel).more_like_this(mi)
self.assertEqual(deferred.count(), 4)
self.assertEqual(
set([result.pk for result in deferred]), set(["2", "6", "16", "23"])
)
self.assertEqual(len([result.pk for result in deferred]), 4)
# Ensure that swapping the ``result_class`` works.
self.assertTrue(
isinstance(
self.sqs.result_class(MockSearchResult).more_like_this(
MockModel.objects.get(pk=1)
)[0],
MockSearchResult,
)
)
| LiveElasticsearchMoreLikeThisTestCase |
python | Pylons__pyramid | src/pyramid/interfaces.py | {
"start": 25798,
"end": 25907
} | class ____(Interface):
"""*Internal only* marker interface for exception views."""
| IExceptionViewClassifier |
python | facebook__pyre-check | pyre_extensions/__init__.py | {
"start": 4344,
"end": 4382
} | class ____(Generic[_T]):
pass
| Unpack |
python | PrefectHQ__prefect | src/integrations/prefect-azure/prefect_azure/workers/container_instance.py | {
"start": 19025,
"end": 37572
} | class ____(
BaseWorker[
AzureContainerJobConfiguration,
AzureContainerVariables,
AzureContainerWorkerResult,
]
):
"""
A Prefect worker that runs flows in an Azure Container Instance.
"""
type: str = "azure-container-instance"
job_configuration = AzureContainerJobConfiguration
job_configuration_variables = AzureContainerVariables
_logo_url = "https://cdn.sanity.io/images/3ugk85nk/production/54e3fa7e00197a4fbd1d82ed62494cb58d08c96a-250x250.png" # noqa
_display_name = "Azure Container Instances"
_description = (
"Execute flow runs within containers on Azure's Container Instances "
"service. Requires an Azure account."
)
_documentation_url = "https://docs.prefect.io/integrations/prefect-azure"
async def run(
self,
flow_run: "FlowRun",
configuration: AzureContainerJobConfiguration,
task_status: Optional[anyio.abc.TaskStatus] = None,
):
"""
Run a flow in an Azure Container Instance.
Args:
flow_run: The flow run to run.
configuration: The configuration for the flow run.
task_status: The task status object for the current task. Used
to provide an identifier that can be used to cancel the task.
Returns:
The result of the flow run.
"""
run_start_time = datetime.datetime.now(datetime.timezone.utc)
prefect_client = get_client()
# Get the flow, so we can use its name in the container group name
# to make it easier to identify and debug.
flow = await prefect_client.read_flow(flow_run.flow_id)
# Slugify flow.name and ensure that the generated name won't be too long
# for the max deployment name length (64) including "prefect-"
slugified_flow_name = slugify(
flow.name,
max_length=55 - len(str(flow_run.id)),
regex_pattern=r"[^a-zA-Z0-9-]+",
)
container_group_name = f"{slugified_flow_name}-{flow_run.id}"
self._logger.info(
f"{self._log_prefix}: Preparing to run command {configuration.command} "
f"in container {configuration.image})..."
)
aci_client = configuration.aci_credentials.get_container_client(
configuration.subscription_id.get_secret_value()
)
resource_client = configuration.aci_credentials.get_resource_client(
configuration.subscription_id.get_secret_value()
)
created_container_group: Union[ContainerGroup, None] = None
try:
self._logger.info(f"{self._log_prefix}: Creating container group...")
created_container_group = await self._provision_container_group(
aci_client,
resource_client,
configuration,
container_group_name,
)
# Both the flow ID and container group name will be needed to
# cancel the flow run if needed.
identifier = f"{flow_run.id}:{container_group_name}"
if self._provisioning_succeeded(created_container_group):
self._logger.info(f"{self._log_prefix}: Running command...")
if task_status is not None:
task_status.started(value=identifier)
status_code = await run_sync_in_worker_thread(
self._watch_task_and_get_exit_code,
aci_client,
configuration,
created_container_group,
run_start_time,
)
self._logger.info(f"{self._log_prefix}: Completed command run.")
else:
raise RuntimeError(f"{self._log_prefix}: Container creation failed.")
finally:
if configuration.keep_container_group:
self._logger.info(f"{self._log_prefix}: Stopping container group...")
aci_client.container_groups.stop(
resource_group_name=configuration.resource_group_name,
container_group_name=container_group_name,
)
else:
await self._wait_for_container_group_deletion(
aci_client, configuration, container_group_name
)
return AzureContainerWorkerResult(
identifier=created_container_group.name, status_code=status_code
)
def _wait_for_task_container_start(
self,
client: ContainerInstanceManagementClient,
configuration: AzureContainerJobConfiguration,
container_group_name: str,
creation_status_poller: LROPoller[DeploymentExtended],
) -> Optional[ContainerGroup]:
"""
Wait for the result of group and container creation.
Args:
creation_status_poller: Poller returned by the Azure SDK.
Raises:
RuntimeError: Raised if the timeout limit is exceeded before the
container starts.
Returns:
A `ContainerGroup` representing the current status of the group being
watched, or None if creation failed.
"""
t0 = time.time()
timeout = configuration.task_start_timeout_seconds
while not creation_status_poller.done():
elapsed_time = time.time() - t0
if timeout and elapsed_time > timeout:
raise RuntimeError(
(
f"Timed out after {elapsed_time}s while watching waiting for "
"container start."
)
)
time.sleep(configuration.task_watch_poll_interval)
deployment = creation_status_poller.result()
provisioning_succeeded = (
deployment.properties.provisioning_state
== ContainerGroupProvisioningState.SUCCEEDED
)
if provisioning_succeeded:
return self._get_container_group(
client, configuration.resource_group_name, container_group_name
)
else:
return None
async def _provision_container_group(
self,
aci_client: ContainerInstanceManagementClient,
resource_client: ResourceManagementClient,
configuration: AzureContainerJobConfiguration,
container_group_name: str,
):
"""
Create a container group and wait for it to start.
Args:
aci_client: An authenticated ACI client.
resource_client: An authenticated resource client.
configuration: The job configuration.
container_group_name: The name of the container group to create.
Returns:
A `ContainerGroup` representing the container group that was created.
"""
properties = DeploymentProperties(
mode=DeploymentMode.INCREMENTAL,
template=configuration.arm_template,
parameters={"container_group_name": {"value": container_group_name}},
)
deployment = Deployment(properties=properties)
creation_status_poller = await run_sync_in_worker_thread(
resource_client.deployments.begin_create_or_update,
resource_group_name=configuration.resource_group_name,
deployment_name=f"prefect-{container_group_name}",
parameters=deployment,
)
created_container_group = await run_sync_in_worker_thread(
self._wait_for_task_container_start,
aci_client,
configuration,
container_group_name,
creation_status_poller,
)
return created_container_group
def _watch_task_and_get_exit_code(
self,
client: ContainerInstanceManagementClient,
configuration: AzureContainerJobConfiguration,
container_group: ContainerGroup,
run_start_time: datetime.datetime,
) -> int:
"""
Waits until the container finishes running and obtains its exit code.
Args:
client: An initialized Azure `ContainerInstanceManagementClient`
container_group: The `ContainerGroup` in which the container resides.
Returns:
An `int` representing the container's exit code.
"""
status_code = -1
running_container = self._get_container(container_group)
current_state = running_container.instance_view.current_state.state
# get any logs the container has already generated
last_log_time = run_start_time
if configuration.stream_output:
last_log_time = self._get_and_stream_output(
client=client,
configuration=configuration,
container_group=container_group,
last_log_time=last_log_time,
)
# set exit code if flow run already finished:
if current_state == ContainerRunState.TERMINATED:
status_code = running_container.instance_view.current_state.exit_code
while current_state != ContainerRunState.TERMINATED:
try:
container_group = self._get_container_group(
client,
configuration.resource_group_name,
container_group.name,
)
except ResourceNotFoundError:
self._logger.exception(
f"{self._log_prefix}: Container group was deleted before flow run "
"completed, likely due to flow cancellation."
)
# since the flow was cancelled, exit early instead of raising an
# exception
return status_code
container = self._get_container(container_group)
current_state = container.instance_view.current_state.state
if current_state == ContainerRunState.TERMINATED:
status_code = container.instance_view.current_state.exit_code
# break instead of waiting for next loop iteration because
# trying to read logs from a terminated container raises an exception
break
if configuration.stream_output:
last_log_time = self._get_and_stream_output(
client=client,
configuration=configuration,
container_group=container_group,
last_log_time=last_log_time,
)
time.sleep(configuration.task_watch_poll_interval)
return status_code
async def _wait_for_container_group_deletion(
self,
aci_client: ContainerInstanceManagementClient,
configuration: AzureContainerJobConfiguration,
container_group_name: str,
):
"""
Wait for the container group to be deleted.
Args:
aci_client: An authenticated ACI client.
configuration: The job configuration.
container_group_name: The name of the container group to delete.
"""
self._logger.info(f"{self._log_prefix}: Deleting container...")
deletion_status_poller = await run_sync_in_worker_thread(
aci_client.container_groups.begin_delete,
resource_group_name=configuration.resource_group_name,
container_group_name=container_group_name,
)
t0 = time.time()
timeout = CONTAINER_GROUP_DELETION_TIMEOUT_SECONDS
while not deletion_status_poller.done():
elapsed_time = time.time() - t0
if timeout and elapsed_time > timeout:
raise RuntimeError(
(
f"Timed out after {elapsed_time}s while waiting for deletion of"
f" container group {container_group_name}. To verify the group "
"has been deleted, check the Azure Portal or run "
f"az container show --name {container_group_name} --resource-group {configuration.resource_group_name}" # noqa
)
)
await anyio.sleep(configuration.task_watch_poll_interval)
self._logger.info(f"{self._log_prefix}: Container deleted.")
def _get_container(self, container_group: ContainerGroup) -> Container:
"""
Extracts the job container from a container group.
"""
return container_group.containers[0]
@staticmethod
def _get_container_group(
client: ContainerInstanceManagementClient,
resource_group_name: str,
container_group_name: str,
) -> ContainerGroup:
"""
Gets the container group from Azure.
"""
return client.container_groups.get(
resource_group_name=resource_group_name,
container_group_name=container_group_name,
)
def _get_and_stream_output(
self,
client: ContainerInstanceManagementClient,
configuration: AzureContainerJobConfiguration,
container_group: ContainerGroup,
last_log_time: datetime.datetime,
) -> datetime.datetime:
"""
Fetches logs output from the job container and writes all entries after
a given time to stderr.
Args:
client: An initialized `ContainerInstanceManagementClient`
container_group: The container group that holds the job container.
last_log_time: The timestamp of the last output line already streamed.
Returns:
The time of the most recent output line written by this call.
"""
logs = self._get_logs(
client=client, configuration=configuration, container_group=container_group
)
return self._stream_output(logs, last_log_time)
def _get_logs(
self,
client: ContainerInstanceManagementClient,
configuration: AzureContainerJobConfiguration,
container_group: ContainerGroup,
max_lines: int = 100,
) -> str:
"""
Gets the most container logs up to a given maximum.
Args:
client: An initialized `ContainerInstanceManagementClient`
container_group: The container group that holds the job container.
max_lines: The number of log lines to pull. Defaults to 100.
Returns:
A string containing the requested log entries, one per line.
"""
container = self._get_container(container_group)
logs: Union[Logs, None] = None
try:
logs = client.containers.list_logs(
resource_group_name=configuration.resource_group_name,
container_group_name=container_group.name,
container_name=container.name,
tail=max_lines,
timestamps=True,
)
except HttpResponseError:
# Trying to get logs when the container is under heavy CPU load sometimes
# results in an error, but we won't want to raise an exception and stop
# monitoring the flow. Instead, log the error and carry on so we can try to
# get all missed logs on the next check.
self._logger.warning(
f"{self._log_prefix}: Unable to retrieve logs from container "
f"{container.name}. Trying again in "
f"{configuration.task_watch_poll_interval}s"
)
return logs.content if logs else ""
def _stream_output(
self, log_content: Union[str, None], last_log_time: datetime.datetime
) -> datetime.datetime:
"""
Writes each entry from a string of log lines to stderr.
Args:
log_content: A string containing Azure container logs.
last_log_time: The timestamp of the last output line already streamed.
Returns:
The time of the most recent output line written by this call.
"""
if not log_content:
# nothing to stream
return last_log_time
log_lines = log_content.split("\n")
last_written_time = last_log_time
for log_line in log_lines:
# skip if the line is blank or whitespace
if not log_line.strip():
continue
line_parts = log_line.split(" ")
# timestamp should always be before first space in line
line_timestamp = line_parts[0]
line = " ".join(line_parts[1:])
try:
line_time = dateutil.parser.parse(line_timestamp)
# Ensure line_time is timezone-aware for comparison
if line_time.tzinfo is None:
# Assume same timezone as last_written_time
line_time = line_time.replace(tzinfo=last_written_time.tzinfo)
if line_time > last_written_time:
self._write_output_line(line)
last_written_time = line_time
except dateutil.parser.ParserError as e:
self._logger.debug(
(
f"{self._log_prefix}: Unable to parse timestamp from Azure "
"log line: %s"
),
log_line,
exc_info=e,
)
return last_written_time
@property
def _log_prefix(self) -> str:
"""
Internal property for generating a prefix for logs where `name` may be null
"""
if self.name is not None:
return f"AzureContainerInstanceJob {self.name!r}"
else:
return "AzureContainerInstanceJob"
@staticmethod
def _provisioning_succeeded(container_group: Union[ContainerGroup, None]) -> bool:
"""
Determines whether ACI container group provisioning was successful.
Args:
container_group: a container group returned by the Azure SDK.
Returns:
True if provisioning was successful, False otherwise.
"""
if not container_group:
return False
return (
container_group.provisioning_state
== ContainerGroupProvisioningState.SUCCEEDED
and len(container_group.containers) == 1
)
@staticmethod
def _write_output_line(line: str):
"""
Writes a line of output to stderr.
"""
print(line, file=sys.stderr)
| AzureContainerWorker |
python | apache__airflow | providers/google/tests/unit/google/cloud/triggers/test_kubernetes_engine.py | {
"start": 16410,
"end": 20610
} | class ____:
def test_serialize(self, job_trigger):
classpath, kwargs_dict = job_trigger.serialize()
assert classpath == TRIGGER_GKE_JOB_PATH
assert kwargs_dict == {
"cluster_url": CLUSTER_URL,
"ssl_ca_cert": SSL_CA_CERT,
"job_name": JOB_NAME,
"job_namespace": NAMESPACE,
"pod_names": [
POD_NAME,
],
"pod_namespace": NAMESPACE,
"base_container_name": BASE_CONTAINER_NAME,
"gcp_conn_id": GCP_CONN_ID,
"poll_interval": POLL_INTERVAL,
"impersonation_chain": IMPERSONATION_CHAIN,
"get_logs": GET_LOGS,
"do_xcom_push": XCOM_PUSH,
}
@pytest.mark.asyncio
@mock.patch(f"{TRIGGER_GKE_JOB_PATH}.hook")
async def test_run_success(self, mock_hook, job_trigger):
mock_job = mock.MagicMock()
mock_job.metadata.name = JOB_NAME
mock_job.metadata.namespace = NAMESPACE
mock_hook.wait_until_job_complete.side_effect = mock.AsyncMock(return_value=mock_job)
mock_pod = mock.MagicMock()
mock_pod.metadata.name = POD_NAME
mock_pod.metadata.namespace = NAMESPACE
mock_hook.get_pod.side_effect = mock.AsyncMock(return_value=mock_pod)
mock_is_job_failed = mock_hook.is_job_failed
mock_is_job_failed.return_value = False
mock_job_dict = mock_job.to_dict.return_value
event_actual = await job_trigger.run().asend(None)
mock_hook.wait_until_job_complete.assert_called_once_with(
name=JOB_NAME, namespace=NAMESPACE, poll_interval=POLL_INTERVAL
)
mock_job.to_dict.assert_called_once()
mock_is_job_failed.assert_called_once_with(job=mock_job)
assert event_actual == TriggerEvent(
{
"name": JOB_NAME,
"namespace": NAMESPACE,
"pod_names": [
POD_NAME,
],
"pod_namespace": NAMESPACE,
"status": "success",
"message": "Job completed successfully",
"job": mock_job_dict,
"xcom_result": None,
}
)
@pytest.mark.asyncio
@mock.patch(f"{TRIGGER_GKE_JOB_PATH}.hook")
async def test_run_fail(self, mock_hook, job_trigger):
mock_job = mock.MagicMock()
mock_job.metadata.name = JOB_NAME
mock_job.metadata.namespace = NAMESPACE
mock_hook.wait_until_job_complete.side_effect = mock.AsyncMock(return_value=mock_job)
mock_pod = mock.MagicMock()
mock_pod.metadata.name = POD_NAME
mock_pod.metadata.namespace = NAMESPACE
mock_hook.get_pod.side_effect = mock.AsyncMock(return_value=mock_pod)
mock_is_job_failed = mock_hook.is_job_failed
mock_is_job_failed.return_value = "Error"
mock_job_dict = mock_job.to_dict.return_value
event_actual = await job_trigger.run().asend(None)
mock_hook.wait_until_job_complete.assert_called_once_with(
name=JOB_NAME, namespace=NAMESPACE, poll_interval=POLL_INTERVAL
)
mock_job.to_dict.assert_called_once()
mock_is_job_failed.assert_called_once_with(job=mock_job)
assert event_actual == TriggerEvent(
{
"name": JOB_NAME,
"namespace": NAMESPACE,
"pod_names": [
POD_NAME,
],
"pod_namespace": NAMESPACE,
"status": "error",
"message": "Job failed with error: Error",
"job": mock_job_dict,
"xcom_result": None,
}
)
@mock.patch(f"{GKE_TRIGGERS_PATH}.GKEKubernetesAsyncHook")
def test_hook(self, mock_hook, job_trigger):
hook_expected = mock_hook.return_value
hook_actual = job_trigger.hook
mock_hook.assert_called_once_with(
cluster_url=CLUSTER_URL,
ssl_ca_cert=SSL_CA_CERT,
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
assert hook_actual == hook_expected
| TestGKEStartJobTrigger |
python | django__django | tests/admin_scripts/complex_app/management/commands/duplicate.py | {
"start": 54,
"end": 156
} | class ____(BaseCommand):
def handle(self, **options):
self.stdout.write("complex_app")
| Command |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/garply/package.py | {
"start": 240,
"end": 473
} | class ____(Package):
"""Toy package for testing dependencies"""
homepage = "https://www.example.com"
has_code = False
version("3.0.0")
def install(self, spec, prefix):
garply_h = """#ifndef GARPLY_H_
| Garply |
python | django__django | tests/admin_widgets/widgetadmin.py | {
"start": 971,
"end": 1589
} | class ____(admin.ModelAdmin):
filter_vertical = ("students",)
filter_horizontal = ("alumni",)
site = WidgetAdmin(name="widget-admin")
site.register(User)
site.register(Car, CarAdmin)
site.register(CarTire, CarTireAdmin)
site.register(Member)
site.register(Band)
site.register(Event, EventAdmin)
site.register(Album, AlbumAdmin)
site.register(ReleaseEvent, search_fields=["name"])
site.register(VideoStream, autocomplete_fields=["release_event"])
site.register(Inventory)
site.register(Bee)
site.register(Advisor)
site.register(School, SchoolAdmin)
site.register(Student)
site.register(Profile)
| SchoolAdmin |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_bytes.py | {
"start": 885,
"end": 960
} | class ____:
def __bytes__(self):
raise NotImplementedError
| Bytes5 |
python | tornadoweb__tornado | tornado/test/ioloop_test.py | {
"start": 17894,
"end": 20513
} | class ____(AsyncTestCase):
def test_add_future_threads(self):
with futures.ThreadPoolExecutor(1) as pool:
def dummy():
pass
self.io_loop.add_future(
pool.submit(dummy), lambda future: self.stop(future)
)
future = self.wait()
self.assertTrue(future.done())
self.assertIsNone(future.result())
@gen_test
def test_run_in_executor_gen(self):
event1 = threading.Event()
event2 = threading.Event()
def sync_func(self_event, other_event):
self_event.set()
other_event.wait()
# Note that return value doesn't actually do anything,
# it is just passed through to our final assertion to
# make sure it is passed through properly.
return self_event
# Run two synchronous functions, which would deadlock if not
# run in parallel.
res = yield [
IOLoop.current().run_in_executor(None, sync_func, event1, event2),
IOLoop.current().run_in_executor(None, sync_func, event2, event1),
]
self.assertEqual([event1, event2], res)
@gen_test
def test_run_in_executor_native(self):
event1 = threading.Event()
event2 = threading.Event()
def sync_func(self_event, other_event):
self_event.set()
other_event.wait()
return self_event
# Go through an async wrapper to ensure that the result of
# run_in_executor works with await and not just gen.coroutine
# (simply passing the underlying concurrent future would do that).
async def async_wrapper(self_event, other_event):
return await IOLoop.current().run_in_executor(
None, sync_func, self_event, other_event
)
res = yield [async_wrapper(event1, event2), async_wrapper(event2, event1)]
self.assertEqual([event1, event2], res)
@gen_test
def test_set_default_executor(self):
count = [0]
class MyExecutor(futures.ThreadPoolExecutor):
def submit(self, func, *args): # type: ignore[override]
count[0] += 1
return super().submit(func, *args)
event = threading.Event()
def sync_func():
event.set()
executor = MyExecutor(1)
loop = IOLoop.current()
loop.set_default_executor(executor)
yield loop.run_in_executor(None, sync_func)
self.assertEqual(1, count[0])
self.assertTrue(event.is_set())
| TestIOLoopFutures |
python | walkccc__LeetCode | solutions/9. Palindrome Number/9.py | {
"start": 0,
"end": 194
} | class ____:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
rev = 0
y = x
while y:
rev = rev * 10 + y % 10
y //= 10
return rev == x
| Solution |
python | dask__distributed | distributed/tests/test_nanny.py | {
"start": 18180,
"end": 22803
} | class ____(worker.Worker):
async def start_unsafe(self):
raise ValueError("broken")
@gen_cluster(nthreads=[])
async def test_worker_start_exception(s):
nanny = Nanny(s.address, worker_class=BrokenWorker)
with captured_logger(logger="distributed.nanny", level=logging.WARNING) as logs:
with raises_with_cause(
RuntimeError,
"Nanny failed to start",
RuntimeError,
"BrokenWorker failed to start",
):
async with nanny:
pass
assert nanny.status == Status.failed
# ^ NOTE: `Nanny.close` sets it to `closed`, then `Server.start._close_on_failure` sets it to `failed`
assert nanny.process is None
assert "Restarting worker" not in logs.getvalue()
# Avoid excessive spewing. (It's also printed once extra within the subprocess, which is okay.)
assert logs.getvalue().count("ValueError: broken") == 1, logs.getvalue()
@gen_cluster(nthreads=[])
async def test_worker_start_exception_while_killing(s):
nanny = Nanny(s.address, worker_class=BrokenWorker)
async def try_to_kill_nanny():
while not nanny.process or nanny.process.status != Status.starting:
await asyncio.sleep(0)
await nanny.kill()
kill_task = asyncio.create_task(try_to_kill_nanny())
with captured_logger(logger="distributed.nanny", level=logging.WARNING) as logs:
with raises_with_cause(
RuntimeError,
"Nanny failed to start",
RuntimeError,
"BrokenWorker failed to start",
):
async with nanny:
pass
await kill_task
assert nanny.status == Status.failed
# ^ NOTE: `Nanny.close` sets it to `closed`, then `Server.start._close_on_failure` sets it to `failed`
assert nanny.process is None
assert "Restarting worker" not in logs.getvalue()
# Avoid excessive spewing. (It's also printed once extra within the subprocess, which is okay.)
assert logs.getvalue().count("ValueError: broken") == 1, logs.getvalue()
@gen_cluster(nthreads=[])
async def test_failure_during_worker_initialization(s):
with captured_logger(logger="distributed.nanny", level=logging.WARNING) as logs:
with pytest.raises(RuntimeError):
await Nanny(s.address, foo="bar")
assert "Restarting worker" not in logs.getvalue()
@gen_cluster(client=True, Worker=Nanny)
async def test_environ_plugin(c, s, a, b):
from dask.distributed import Environ
await c.register_plugin(Environ({"ABC": 123}))
async with Nanny(s.address, name="new") as n:
results = await c.run(os.getenv, "ABC")
assert results[a.worker_address] == "123"
assert results[b.worker_address] == "123"
assert results[n.worker_address] == "123"
@pytest.mark.parametrize(
"modname",
[
# numpy is always imported, and for a good reason:
# https://github.com/dask/distributed/issues/5729
"scipy",
pytest.param("pandas", marks=pytest.mark.xfail(reason="distributed#5723")),
],
)
@gen_cluster(client=True, Worker=Nanny, nthreads=[("", 1)])
async def test_no_unnecessary_imports_on_worker(c, s, a, modname):
"""
Regression test against accidentally importing unnecessary modules at worker startup.
Importing modules like pandas slows down worker startup, especially if workers are
loading their software environment from NFS or other non-local filesystems.
It also slightly increases memory footprint.
"""
def assert_no_import(dask_worker):
assert modname not in sys.modules
await c.wait_for_workers(1)
await c.run(assert_no_import)
@pytest.mark.slow
@gen_cluster(client=True, Worker=Nanny)
async def test_repeated_restarts(c, s, a, b):
for _ in range(3):
await c.restart()
assert len(s.workers) == 2
@pytest.mark.slow
@gen_cluster(
client=True,
Worker=Nanny,
worker_kwargs={"memory_limit": "1 GiB"},
nthreads=[("127.0.0.1", 1)],
)
async def test_restart_memory(c, s, n):
# First kill nanny with restart
await c.restart()
# then kill nanny with memory
from dask.distributed import KilledWorker
np = pytest.importorskip("numpy")
s.allowed_failures = 1
future = c.submit(np.ones, 300_000_000, dtype="f8")
with pytest.raises(KilledWorker):
await future
while not s.workers:
await asyncio.sleep(0.1)
msgs = s.get_events("worker-restart-memory")
assert len(msgs)
msg = msgs[0][1]
assert isinstance(msg, dict)
assert {"worker", "pid", "rss"}.issubset(set(msg))
| BrokenWorker |
python | plotly__plotly.py | plotly/graph_objs/volume/_slices.py | {
"start": 233,
"end": 3811
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "volume"
_path_str = "volume.slices"
_valid_props = {"x", "y", "z"}
@property
def x(self):
"""
The 'x' property is an instance of X
that may be specified as:
- An instance of :class:`plotly.graph_objs.volume.slices.X`
- A dict of string/value properties that will be passed
to the X constructor
Returns
-------
plotly.graph_objs.volume.slices.X
"""
return self["x"]
@x.setter
def x(self, val):
self["x"] = val
@property
def y(self):
"""
The 'y' property is an instance of Y
that may be specified as:
- An instance of :class:`plotly.graph_objs.volume.slices.Y`
- A dict of string/value properties that will be passed
to the Y constructor
Returns
-------
plotly.graph_objs.volume.slices.Y
"""
return self["y"]
@y.setter
def y(self, val):
self["y"] = val
@property
def z(self):
"""
The 'z' property is an instance of Z
that may be specified as:
- An instance of :class:`plotly.graph_objs.volume.slices.Z`
- A dict of string/value properties that will be passed
to the Z constructor
Returns
-------
plotly.graph_objs.volume.slices.Z
"""
return self["z"]
@z.setter
def z(self, val):
self["z"] = val
@property
def _prop_descriptions(self):
return """\
x
:class:`plotly.graph_objects.volume.slices.X` instance
or dict with compatible properties
y
:class:`plotly.graph_objects.volume.slices.Y` instance
or dict with compatible properties
z
:class:`plotly.graph_objects.volume.slices.Z` instance
or dict with compatible properties
"""
def __init__(self, arg=None, x=None, y=None, z=None, **kwargs):
"""
Construct a new Slices object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.volume.Slices`
x
:class:`plotly.graph_objects.volume.slices.X` instance
or dict with compatible properties
y
:class:`plotly.graph_objects.volume.slices.Y` instance
or dict with compatible properties
z
:class:`plotly.graph_objects.volume.slices.Z` instance
or dict with compatible properties
Returns
-------
Slices
"""
super().__init__("slices")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.volume.Slices
constructor must be a dict or
an instance of :class:`plotly.graph_objs.volume.Slices`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("x", arg, x)
self._set_property("y", arg, y)
self._set_property("z", arg, z)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Slices |
python | ray-project__ray | python/ray/dashboard/modules/version.py | {
"start": 527,
"end": 630
} | class ____:
version: str
ray_version: str
ray_commit: str
session_name: str
| VersionResponse |
python | nmslib__hnswlib | python_bindings/LazyIndex.py | {
"start": 190,
"end": 1727
} | class ____(hnswlib.Index):
def __init__(self, space, dim,max_elements=1024, ef_construction=200, M=16):
super().__init__(space, dim)
self.init_max_elements=max_elements
self.init_ef_construction=ef_construction
self.init_M=M
def init_index(self, max_elements=0,M=0,ef_construction=0):
if max_elements>0:
self.init_max_elements=max_elements
if ef_construction>0:
self.init_ef_construction=ef_construction
if M>0:
self.init_M=M
super().init_index(self.init_max_elements, self.init_M, self.init_ef_construction)
def add_items(self, data, ids=None, num_threads=-1):
if self.max_elements==0:
self.init_index()
return super().add_items(data,ids, num_threads)
def get_items(self, ids=None):
if self.max_elements==0:
return []
return super().get_items(ids)
def knn_query(self, data,k=1, num_threads=-1):
if self.max_elements==0:
return [], []
return super().knn_query(data, k, num_threads)
def resize_index(self, size):
if self.max_elements==0:
return self.init_index(size)
else:
return super().resize_index(size)
def set_ef(self, ef):
if self.max_elements==0:
self.init_ef_construction=ef
return
super().set_ef(ef)
def get_max_elements(self):
return self.max_elements
def get_current_count(self):
return self.element_count
| LazyIndex |
python | openai__openai-python | src/openai/pagination.py | {
"start": 552,
"end": 1112
} | class ____(BaseSyncPage[_T], BasePage[_T], Generic[_T]):
"""Note: no pagination actually occurs yet, this is for forwards-compatibility."""
data: List[_T]
object: str
@override
def _get_page_items(self) -> List[_T]:
data = self.data
if not data:
return []
return data
@override
def next_page_info(self) -> None:
"""
This page represents a response that isn't actually paginated at the API level
so there will never be a next page.
"""
return None
| SyncPage |
python | plotly__plotly.py | plotly/graph_objs/scatter/marker/_gradient.py | {
"start": 233,
"end": 4892
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter.marker"
_path_str = "scatter.marker.gradient"
_valid_props = {"color", "colorsrc", "type", "typesrc"}
@property
def color(self):
"""
Sets the final color of the gradient fill: the center color for
radial, the right for horizontal, or the bottom for vertical.
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def colorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `color`.
The 'colorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["colorsrc"]
@colorsrc.setter
def colorsrc(self, val):
self["colorsrc"] = val
@property
def type(self):
"""
Sets the type of gradient used to fill the markers
The 'type' property is an enumeration that may be specified as:
- One of the following enumeration values:
['radial', 'horizontal', 'vertical', 'none']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["type"]
@type.setter
def type(self, val):
self["type"] = val
@property
def typesrc(self):
"""
Sets the source reference on Chart Studio Cloud for `type`.
The 'typesrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["typesrc"]
@typesrc.setter
def typesrc(self, val):
self["typesrc"] = val
@property
def _prop_descriptions(self):
return """\
color
Sets the final color of the gradient fill: the center
color for radial, the right for horizontal, or the
bottom for vertical.
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
type
Sets the type of gradient used to fill the markers
typesrc
Sets the source reference on Chart Studio Cloud for
`type`.
"""
def __init__(
self, arg=None, color=None, colorsrc=None, type=None, typesrc=None, **kwargs
):
"""
Construct a new Gradient object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.scatter.marker.Gradient`
color
Sets the final color of the gradient fill: the center
color for radial, the right for horizontal, or the
bottom for vertical.
colorsrc
Sets the source reference on Chart Studio Cloud for
`color`.
type
Sets the type of gradient used to fill the markers
typesrc
Sets the source reference on Chart Studio Cloud for
`type`.
Returns
-------
Gradient
"""
super().__init__("gradient")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.scatter.marker.Gradient
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scatter.marker.Gradient`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("colorsrc", arg, colorsrc)
self._set_property("type", arg, type)
self._set_property("typesrc", arg, typesrc)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Gradient |
python | pypa__packaging | src/packaging/pylock.py | {
"start": 8076,
"end": 8238
} | class ____(PylockValidationError):
def __init__(self, key: str) -> None:
super().__init__("Missing required value", context=key)
| _PylockRequiredKeyError |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/workspace/workspace.py | {
"start": 1677,
"end": 2538
} | class ____:
code_location_entries: Mapping[str, CodeLocationEntry]
@cached_property
def asset_graph(self) -> "RemoteWorkspaceAssetGraph":
from dagster._core.definitions.assets.graph.remote_asset_graph import (
RemoteWorkspaceAssetGraph,
)
return RemoteWorkspaceAssetGraph.build(self)
def with_code_location(self, name: str, entry: CodeLocationEntry) -> "CurrentWorkspace":
return CurrentWorkspace(code_location_entries={**self.code_location_entries, name: entry})
def location_status_from_location_entry(
entry: CodeLocationEntry,
) -> CodeLocationStatusEntry:
return CodeLocationStatusEntry(
location_name=entry.origin.location_name,
load_status=entry.load_status,
update_timestamp=entry.update_timestamp,
version_key=entry.version_key,
)
| CurrentWorkspace |
python | cherrypy__cherrypy | cherrypy/_cptools.py | {
"start": 5002,
"end": 6896
} | class ____(Tool):
"""Tool which is called 'before main', that may skip normal handlers.
If the tool successfully handles the request (by setting
response.body), if should return True. This will cause CherryPy to
skip any 'normal' page handler. If the tool did not handle the
request, it should return False to tell CherryPy to continue on and
call the normal page handler. If the tool is declared AS a page
handler (see the 'handler' method), returning False will raise
NotFound.
"""
def __init__(self, callable, name=None):
"""Initialize a handler tool."""
Tool.__init__(self, 'before_handler', callable, name)
def handler(self, *args, **kwargs):
"""Use this tool as a CherryPy page handler.
For example::
class Root:
nav = tools.staticdir.handler(section="/nav", dir="nav",
root=absDir)
"""
@expose
def handle_func(*a, **kw):
handled = self.callable(*args, **self._merged_args(kwargs))
if not handled:
raise cherrypy.NotFound()
return cherrypy.serving.response.body
return handle_func
def _wrapper(self, **kwargs):
if self.callable(**kwargs):
cherrypy.serving.request.handler = None
def _setup(self):
"""Wire this tool into ``cherrypy.request``.
The standard CherryPy request object will automatically call
this method when the tool is "turned on" in config.
"""
conf = self._merged_args()
p = conf.pop('priority', None)
if p is None:
p = getattr(self.callable, 'priority', self._priority)
cherrypy.serving.request.hooks.attach(
self._point,
self._wrapper,
priority=p,
**conf,
)
| HandlerTool |
python | sympy__sympy | sympy/physics/quantum/qubit.py | {
"start": 11053,
"end": 13462
} | class ____(IntQubitState, Qubit):
"""A qubit ket that store integers as binary numbers in qubit values.
The differences between this class and ``Qubit`` are:
* The form of the constructor.
* The qubit values are printed as their corresponding integer, rather
than the raw qubit values. The internal storage format of the qubit
values in the same as ``Qubit``.
Parameters
==========
values : int, tuple
If a single argument, the integer we want to represent in the qubit
values. This integer will be represented using the fewest possible
number of qubits.
If a pair of integers and the second value is more than one, the first
integer gives the integer to represent in binary form and the second
integer gives the number of qubits to use.
List of zeros and ones is also accepted to generate qubit by bit pattern.
nqubits : int
The integer that represents the number of qubits.
This number should be passed with keyword ``nqubits=N``.
You can use this in order to avoid ambiguity of Qubit-style tuple of bits.
Please see the example below for more details.
Examples
========
Create a qubit for the integer 5:
>>> from sympy.physics.quantum.qubit import IntQubit
>>> from sympy.physics.quantum.qubit import Qubit
>>> q = IntQubit(5)
>>> q
|5>
We can also create an ``IntQubit`` by passing a ``Qubit`` instance.
>>> q = IntQubit(Qubit('101'))
>>> q
|5>
>>> q.as_int()
5
>>> q.nqubits
3
>>> q.qubit_values
(1, 0, 1)
We can go back to the regular qubit form.
>>> Qubit(q)
|101>
Please note that ``IntQubit`` also accepts a ``Qubit``-style list of bits.
So, the code below yields qubits 3, not a single bit ``1``.
>>> IntQubit(1, 1)
|3>
To avoid ambiguity, use ``nqubits`` parameter.
Use of this keyword is recommended especially when you provide the values by variables.
>>> IntQubit(1, nqubits=1)
|1>
>>> a = 1
>>> IntQubit(a, nqubits=1)
|1>
"""
@classmethod
def dual_class(self):
return IntQubitBra
def _eval_innerproduct_IntQubitBra(self, bra, **hints):
return Qubit._eval_innerproduct_QubitBra(self, bra)
| IntQubit |
python | numpy__numpy | numpy/_core/tests/test_arrayprint.py | {
"start": 45115,
"end": 50569
} | class ____:
def test_ctx_mgr(self):
# test that context manager actually works
with np.printoptions(precision=2):
s = str(np.array([2.0]) / 3)
assert_equal(s, '[0.67]')
def test_ctx_mgr_restores(self):
# test that print options are actually restored
opts = np.get_printoptions()
with np.printoptions(precision=opts['precision'] - 1,
linewidth=opts['linewidth'] - 4):
pass
assert_equal(np.get_printoptions(), opts)
def test_ctx_mgr_exceptions(self):
# test that print options are restored even if an exception is raised
opts = np.get_printoptions()
try:
with np.printoptions(precision=2, linewidth=11):
raise ValueError
except ValueError:
pass
assert_equal(np.get_printoptions(), opts)
def test_ctx_mgr_as_smth(self):
opts = {"precision": 2}
with np.printoptions(**opts) as ctx:
saved_opts = ctx.copy()
assert_equal({k: saved_opts[k] for k in opts}, opts)
@pytest.mark.parametrize("dtype", "bhilqpBHILQPefdgFDG")
@pytest.mark.parametrize("value", [0, 1])
def test_scalar_repr_numbers(dtype, value):
# Test NEP 51 scalar repr (and legacy option) for numeric types
dtype = np.dtype(dtype)
scalar = np.array(value, dtype=dtype)[()]
assert isinstance(scalar, np.generic)
string = str(scalar)
repr_string = string.strip("()") # complex may have extra brackets
representation = repr(scalar)
if dtype.char == "g":
assert representation == f"np.longdouble('{repr_string}')"
elif dtype.char == 'G':
assert representation == f"np.clongdouble('{repr_string}')"
else:
normalized_name = np.dtype(f"{dtype.kind}{dtype.itemsize}").type.__name__
assert representation == f"np.{normalized_name}({repr_string})"
with np.printoptions(legacy="1.25"):
assert repr(scalar) == string
@pytest.mark.parametrize("scalar, legacy_repr, representation", [
(np.True_, "True", "np.True_"),
(np.bytes_(b'a'), "b'a'", "np.bytes_(b'a')"),
(np.str_('a'), "'a'", "np.str_('a')"),
(np.datetime64("2012"),
"numpy.datetime64('2012')", "np.datetime64('2012')"),
(np.timedelta64(1), "numpy.timedelta64(1)", "np.timedelta64(1)"),
(np.void((True, 2), dtype="?,<i8"),
"(True, 2)",
"np.void((True, 2), dtype=[('f0', '?'), ('f1', '<i8')])"),
(np.void((1, 2), dtype="<f8,>f4"),
"(1., 2.)",
"np.void((1.0, 2.0), dtype=[('f0', '<f8'), ('f1', '>f4')])"),
(np.void(b'a'), r"void(b'\x61')", r"np.void(b'\x61')"),
])
def test_scalar_repr_special(scalar, legacy_repr, representation):
# Test NEP 51 scalar repr (and legacy option) for numeric types
assert repr(scalar) == representation
with np.printoptions(legacy="1.25"):
assert repr(scalar) == legacy_repr
def test_scalar_void_float_str():
# Note that based on this currently we do not print the same as a tuple
# would, since the tuple would include the repr() inside for floats, but
# we do not do that.
scalar = np.void((1.0, 2.0), dtype=[('f0', '<f8'), ('f1', '>f4')])
assert str(scalar) == "(1.0, 2.0)"
@pytest.mark.skipif(IS_WASM, reason="wasm doesn't support asyncio")
@pytest.mark.skipif(sys.version_info < (3, 11),
reason="asyncio.barrier was added in Python 3.11")
def test_printoptions_asyncio_safe():
asyncio = pytest.importorskip("asyncio")
b = asyncio.Barrier(2)
async def legacy_113():
np.set_printoptions(legacy='1.13', precision=12)
await b.wait()
po = np.get_printoptions()
assert po['legacy'] == '1.13'
assert po['precision'] == 12
orig_linewidth = po['linewidth']
with np.printoptions(linewidth=34, legacy='1.21'):
po = np.get_printoptions()
assert po['legacy'] == '1.21'
assert po['precision'] == 12
assert po['linewidth'] == 34
po = np.get_printoptions()
assert po['linewidth'] == orig_linewidth
assert po['legacy'] == '1.13'
assert po['precision'] == 12
async def legacy_125():
np.set_printoptions(legacy='1.25', precision=7)
await b.wait()
po = np.get_printoptions()
assert po['legacy'] == '1.25'
assert po['precision'] == 7
orig_linewidth = po['linewidth']
with np.printoptions(linewidth=6, legacy='1.13'):
po = np.get_printoptions()
assert po['legacy'] == '1.13'
assert po['precision'] == 7
assert po['linewidth'] == 6
po = np.get_printoptions()
assert po['linewidth'] == orig_linewidth
assert po['legacy'] == '1.25'
assert po['precision'] == 7
async def main():
await asyncio.gather(legacy_125(), legacy_125())
loop = asyncio.new_event_loop()
asyncio.run(main())
loop.close()
@pytest.mark.skipif(IS_WASM, reason="wasm doesn't support threads")
@pytest.mark.thread_unsafe(reason="test is already explicitly multi-threaded")
def test_multithreaded_array_printing():
# the dragon4 implementation uses a static scratch space for performance
# reasons this test makes sure it is set up in a thread-safe manner
run_threaded(TestPrintOptions().test_floatmode, 500)
| TestContextManager |
python | apache__airflow | airflow-core/src/airflow/triggers/base.py | {
"start": 5421,
"end": 6144
} | class ____(BaseModel):
"""
Something that a trigger can fire when its conditions are met.
Events must have a uniquely identifying value that would be the same
wherever the trigger is run; this is to ensure that if the same trigger
is being run in two locations (for HA reasons) that we can deduplicate its
events.
"""
payload: Any = None
"""
The payload for the event to send back to the task.
Must be natively JSON-serializable, or registered with the airflow serialization code.
"""
def __init__(self, payload, **kwargs):
super().__init__(payload=payload, **kwargs)
def __repr__(self) -> str:
return f"TriggerEvent<{self.payload!r}>"
| TriggerEvent |
python | ray-project__ray | python/ray/serve/gradio_integrations.py | {
"start": 473,
"end": 968
} | class ____(ASGIAppReplicaWrapper):
"""User-facing class that wraps a Gradio App in a Serve Deployment."""
def __init__(self, builder: Callable[[], Blocks]):
"""Builds and wraps an ASGI app from the provided builder.
The builder should take no arguments and return a Gradio App (of type Interface
or Blocks).
"""
io: Blocks = builder()
super().__init__(routes.App.create_app(io))
GradioServer = serve.deployment(GradioIngress)
| GradioIngress |
python | euske__pdfminer | pdfminer/ccitt.py | {
"start": 18771,
"end": 23474
} | class ____(unittest.TestCase):
def get_parser(self, bits):
parser = CCITTG4Parser(len(bits))
parser._curline = [int(c) for c in bits]
parser._reset_line()
return parser
def test_b1(self):
parser = self.get_parser('00000')
parser._do_vertical(0)
self.assertEqual(parser._curpos, 0)
return
def test_b2(self):
parser = self.get_parser('10000')
parser._do_vertical(-1)
self.assertEqual(parser._curpos, 0)
return
def test_b3(self):
parser = self.get_parser('000111')
parser._do_pass()
self.assertEqual(parser._curpos, 3)
self.assertEqual(parser._get_bits(), '111')
return
def test_b4(self):
parser = self.get_parser('00000')
parser._do_vertical(+2)
self.assertEqual(parser._curpos, 2)
self.assertEqual(parser._get_bits(), '11')
return
def test_b5(self):
parser = self.get_parser('11111111100')
parser._do_horizontal(0, 3)
self.assertEqual(parser._curpos, 3)
parser._do_vertical(1)
self.assertEqual(parser._curpos, 10)
self.assertEqual(parser._get_bits(), '0001111111')
return
def test_e1(self):
parser = self.get_parser('10000')
parser._do_vertical(0)
self.assertEqual(parser._curpos, 1)
parser._do_vertical(0)
self.assertEqual(parser._curpos, 5)
self.assertEqual(parser._get_bits(), '10000')
return
def test_e2(self):
parser = self.get_parser('10011')
parser._do_vertical(0)
self.assertEqual(parser._curpos, 1)
parser._do_vertical(2)
self.assertEqual(parser._curpos, 5)
self.assertEqual(parser._get_bits(), '10000')
return
def test_e3(self):
parser = self.get_parser('011111')
parser._color = 0
parser._do_vertical(0)
self.assertEqual(parser._color, 1)
self.assertEqual(parser._curpos, 1)
parser._do_vertical(-2)
self.assertEqual(parser._color, 0)
self.assertEqual(parser._curpos, 4)
parser._do_vertical(0)
self.assertEqual(parser._curpos, 6)
self.assertEqual(parser._get_bits(), '011100')
return
def test_e4(self):
parser = self.get_parser('10000')
parser._do_vertical(0)
self.assertEqual(parser._curpos, 1)
parser._do_vertical(-2)
self.assertEqual(parser._curpos, 3)
parser._do_vertical(0)
self.assertEqual(parser._curpos, 5)
self.assertEqual(parser._get_bits(), '10011')
return
def test_e5(self):
parser = self.get_parser('011000')
parser._color = 0
parser._do_vertical(0)
self.assertEqual(parser._curpos, 1)
parser._do_vertical(3)
self.assertEqual(parser._curpos, 6)
self.assertEqual(parser._get_bits(), '011111')
return
def test_e6(self):
parser = self.get_parser('11001')
parser._do_pass()
self.assertEqual(parser._curpos, 4)
parser._do_vertical(0)
self.assertEqual(parser._curpos, 5)
self.assertEqual(parser._get_bits(), '11111')
return
def test_e7(self):
parser = self.get_parser('0000000000')
parser._curpos = 2
parser._color = 1
parser._do_horizontal(2, 6)
self.assertEqual(parser._curpos, 10)
self.assertEqual(parser._get_bits(), '1111000000')
return
def test_e8(self):
parser = self.get_parser('001100000')
parser._curpos = 1
parser._color = 0
parser._do_vertical(0)
self.assertEqual(parser._curpos, 2)
parser._do_horizontal(7, 0)
self.assertEqual(parser._curpos, 9)
self.assertEqual(parser._get_bits(), '101111111')
return
def test_m1(self):
parser = self.get_parser('10101')
parser._do_pass()
self.assertEqual(parser._curpos, 2)
parser._do_pass()
self.assertEqual(parser._curpos, 4)
self.assertEqual(parser._get_bits(), '1111')
return
def test_m2(self):
parser = self.get_parser('101011')
parser._do_vertical(-1)
parser._do_vertical(-1)
parser._do_vertical(1)
parser._do_horizontal(1, 1)
self.assertEqual(parser._get_bits(), '011101')
return
def test_m3(self):
parser = self.get_parser('10111011')
parser._do_vertical(-1)
parser._do_pass()
parser._do_vertical(1)
parser._do_vertical(1)
self.assertEqual(parser._get_bits(), '00000001')
return
## CCITTFaxDecoder
##
| TestCCITTG4Parser |
python | django__django | tests/select_related_onetoone/models.py | {
"start": 1344,
"end": 1463
} | class ____(Parent1):
parent2 = models.OneToOneField(Parent2, models.CASCADE)
value = models.IntegerField()
| Child2 |
python | google__pytype | pytype/tests/test_final.py | {
"start": 85,
"end": 3006
} | class ____(test_base.BaseTest):
"""Test @final."""
def test_subclass(self):
err = self.CheckWithErrors("""
from typing_extensions import final
@final
class A:
pass
class B(A): # final-error[e]
pass
""")
self.assertErrorSequences(err, {"e": ["final class", "A"]})
def test_subclass_with_other_bases(self):
err = self.CheckWithErrors("""
from typing_extensions import final
@final
class A:
pass
class B(list, A): # final-error[e]
pass
""")
self.assertErrorSequences(err, {"e": ["final class", "A"]})
def test_override_method_in_base(self):
err = self.CheckWithErrors("""
from typing_extensions import final
class A:
@final
def f(self):
pass
class B(A): # final-error[e]
def f(self):
pass
""")
self.assertErrorSequences(
err, {"e": ["Class B", "overrides", "final method f", "base class A"]}
)
def test_override_method_in_mro(self):
err = self.CheckWithErrors("""
from typing_extensions import final
class A:
@final
def f(self):
pass
class B(A):
pass
class C(B): # final-error[e]
def f(self):
pass
""")
self.assertErrorSequences(
err, {"e": ["Class C", "overrides", "final method f", "base class A"]}
)
def test_output_class(self):
ty = self.Infer("""
from typing_extensions import final
@final
class A:
pass
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import final
@final
class A: ...
""",
)
def test_output_method(self):
ty = self.Infer("""
from typing_extensions import final
class A:
@final
def f(self):
pass
@final
@classmethod
def g(cls):
pass
""")
self.assertTypesMatchPytd(
ty,
"""
from typing import final, Type
class A:
@final
def f(self) -> None:
pass
@final
@classmethod
def g(cls: Type[A]) -> None:
pass
""",
)
def test_multiple_inheritance(self):
self.CheckWithErrors("""
from typing_extensions import final
class A:
@final
def f(self):
return 0
class B:
def f(self):
return ""
class C(B, A): # final-error
pass
""")
def test_multiple_inheritance_pyi(self):
with self.DepTree([(
"foo.pyi",
"""
class B:
def f(self) -> str: ...
""",
)]):
self.CheckWithErrors("""
from typing_extensions import final
import foo
class A:
@final
def f(self):
return "A"
class C(foo.B, A): # final-error
pass
""")
| TestFinalDecorator |
python | weaviate__weaviate-python-client | weaviate/auth.py | {
"start": 1832,
"end": 2415
} | class ____:
"""Using a preexisting bearer/access token for authentication.
The expiration time of access tokens is given in seconds.
Only the access token is required. However, when no refresh token is
given, the authentication will expire once the lifetime of the
access token is up.
"""
access_token: str
expires_in: int = 60
refresh_token: Optional[str] = None
def __post_init__(self) -> None:
if self.expires_in and self.expires_in < 0:
_Warnings.auth_negative_expiration_time(self.expires_in)
@dataclass
| _BearerToken |
python | ijl__orjson | test/test_enum.py | {
"start": 378,
"end": 429
} | class ____(float, enum.Enum):
ONE = 1.1
| FloatEnum |
python | pytorch__pytorch | test/dynamo/test_subclasses.py | {
"start": 12046,
"end": 12903
} | class ____:
def __init__(self) -> None:
self.graphs = []
self.example_inputs = []
def __call__(self, gm: torch.fx.GraphModule, example_inputs):
self.graphs.append(gm)
self.example_inputs.append(example_inputs)
return gm
GLOBAL_TEST_SUBCLASSES = {
MockSubclass,
DummyNDim,
SigmoidToExpSubclass,
BaseTorchFunction,
}
# Returns True if the function recompiles between inputs1 and inputs2 with the
# specified dynamic setting.
def _recompiles_for_inputs(fn, inputs1, inputs2, dynamic=True):
compile_count = [0]
def counter(gm, example_inputs):
compile_count[0] += 1
return gm
compiled_f = torch.compile(fn, fullgraph=True, backend=counter, dynamic=dynamic)
compiled_f(*inputs1)
compiled_f(*inputs2)
return compile_count[0] > 1
| EagerRecordGraphAndInputs |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_cond_format04.py | {
"start": 315,
"end": 1533
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("cond_format04.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with conditional formatting."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
format1 = workbook.add_format({"num_format": 2, "dxf_index": 1})
format2 = workbook.add_format({"num_format": "0.000", "dxf_index": 0})
worksheet.write("A1", 10)
worksheet.write("A2", 20)
worksheet.write("A3", 30)
worksheet.write("A4", 40)
worksheet.conditional_format(
"A1",
{
"type": "cell",
"format": format1,
"criteria": ">",
"value": 2,
},
)
worksheet.conditional_format(
"A2",
{
"type": "cell",
"format": format2,
"criteria": "<",
"value": 8,
},
)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | astropy__astropy | astropy/table/mixins/tests/test_dask.py | {
"start": 147,
"end": 2041
} | class ____:
def setup_method(self, method):
self.t = Table()
self.t["a"] = da.arange(10)
def test_add_row(self):
self.t.add_row(self.t[0])
assert_equal(self.t["a"].compute(), np.hstack([np.arange(10), 0]))
def test_get_column(self):
assert isinstance(self.t["a"], da.Array)
assert_equal(self.t["a"].compute(), np.arange(10))
def test_slicing_row_single(self):
sub = self.t[5]
assert isinstance(sub["a"], da.Array)
assert not hasattr(sub["a"], "info") # should be a plain dask array
assert sub["a"].compute() == 5
def test_slicing_row_range(self):
sub = self.t[5:]
assert isinstance(sub["a"], da.Array)
assert hasattr(sub["a"], "info") # should be a mixin column
assert_equal(sub["a"].compute(), np.arange(5, 10))
def test_slicing_column_range(self):
sub = self.t[("a",)]
assert isinstance(sub["a"], da.Array)
assert hasattr(sub["a"], "info") # should be a mixin column
assert_equal(sub["a"].compute(), np.arange(10))
def test_pformat(self):
assert self.t.pformat() == [
" a ",
"---",
" 0",
" 1",
" 2",
" 3",
" 4",
" 5",
" 6",
" 7",
" 8",
" 9",
]
def test_info_preserved(self):
self.t["a"].info.description = "A dask column"
sub = self.t[1:3]
assert sub["a"].info.name == "a"
assert sub["a"].info.description == "A dask column"
col = self.t["a"].copy()
assert col.info.name == "a"
assert col.info.description == "A dask column"
self.t.add_row(self.t[0])
assert self.t["a"].info.name == "a"
assert self.t["a"].info.description == "A dask column"
| TestDaskHandler |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/lexers/base.py | {
"start": 1095,
"end": 1736
} | class ____(Lexer):
"""
Lexer that doesn't do any tokenizing and returns the whole input as one
token.
:param style: The style string for this lexer.
"""
def __init__(self, style: str = "") -> None:
self.style = style
def lex_document(self, document: Document) -> Callable[[int], StyleAndTextTuples]:
lines = document.lines
def get_line(lineno: int) -> StyleAndTextTuples:
"Return the tokens for the given line."
try:
return [(self.style, lines[lineno])]
except IndexError:
return []
return get_line
| SimpleLexer |
python | django-crispy-forms__django-crispy-forms | crispy_forms/bootstrap.py | {
"start": 22502,
"end": 24531
} | class ____(Container):
"""
Tab object. It wraps fields in a div whose default class is "tab-pane" and
takes a name as first argument.
Attributes
----------
template : str
The default template which this Layout Object will be rendered
with.
css_class : str, optional
CSS classes to be applied to the ``<div>``. By default "".
Parameters
----------
name : str
The name of the container.
*fields : str, LayoutObject
Any number of fields as positional arguments to be rendered within
the container.
css_id : str, optional
A DOM id for the layout object which will be added to the ``<div>`` if
provided. By default None.
css_class : str, optional
Additional CSS classes to be applied in addition to those declared by
the class itself. By default None.
template : str, optional
Overrides the default template, if provided. By default None.
**kwargs : dict, optional
Additional attributes are passed to ``flatatt`` and converted into
key="value", pairs. These attributes are added to the ``<div>``.
Examples
--------
Example::
Tab('tab_name', 'form_field_1', 'form_field_2', 'form_field_3')
"""
css_class = "tab-pane"
link_template = "%s/layout/tab-link.html"
def render_link(self, template_pack=TEMPLATE_PACK, **kwargs):
"""
Render the link for the tab-pane. It must be called after render so css_class is updated
with active if needed.
"""
link_template = self.link_template % template_pack
return render_to_string(link_template, {"link": self})
def render(self, form, context, template_pack=TEMPLATE_PACK, **kwargs):
if self.active:
if "active" not in self.css_class:
self.css_class += " active"
else:
self.css_class = self.css_class.replace("active", "")
return super().render(form, context, template_pack)
| Tab |
python | django__django | tests/staticfiles_tests/test_management.py | {
"start": 23906,
"end": 24885
} | class ____(CollectionTestCase):
@override_settings(
STORAGES={
**settings.STORAGES,
STATICFILES_STORAGE_ALIAS: {
"BACKEND": "staticfiles_tests.storage.NeverCopyRemoteStorage"
},
}
)
def test_skips_newer_files_in_remote_storage(self):
"""
collectstatic skips newer files in a remote storage.
run_collectstatic() in setUp() copies the static files, then files are
always skipped after NeverCopyRemoteStorage is activated since
NeverCopyRemoteStorage.get_modified_time() returns a datetime in the
future to simulate an unmodified file.
"""
stdout = StringIO()
self.run_collectstatic(stdout=stdout, verbosity=2)
output = stdout.getvalue()
self.assertIn("Skipping 'test.txt' (not modified)", output)
@unittest.skipUnless(symlinks_supported(), "Must be able to symlink to run this test.")
| TestCollectionNeverCopyStorage |
python | pytest-dev__pytest-cov | tests/test_pytest_cov.py | {
"start": 50889,
"end": 59419
} | class ____(coverage.CoveragePlugin):
pass
def coverage_init(reg, options):
reg.add_file_tracer(ExamplePlugin())
"""
)
testdir.makepyprojecttoml(f"""
[tool.coverage.run]
plugins = ["coverageplugin"]
concurrency = ["thread", "multiprocessing"]
{prop.conf}
""")
result = testdir.runpytest('-v', f'--cov={script.dirpath()}', script, *opts.split() + prop.args)
result.stdout.fnmatch_lines(
[
f'test_1* {prop.result}*',
]
)
@xdist_params
def test_dynamic_context(pytester, testdir, opts, prop):
script = testdir.makepyfile(test_1=prop.code)
testdir.makepyprojecttoml(f"""
[tool.coverage.run]
dynamic_context = "test_function"
{prop.conf}
""")
result = testdir.runpytest('-v', f'--cov={script.dirpath()}', script, *opts.split() + prop.args)
if opts:
result.stderr.fnmatch_lines(['pytest_cov.DistCovError: Detected dynamic_context=test_function*'])
else:
result.stdout.fnmatch_lines(
[
'* CentralCovContextWarning: Detected dynamic_context=test_function*',
f'test_1* {prop.result}*',
]
)
@xdist_params
def test_simple(pytester, testdir, opts, prop):
script = testdir.makepyfile(test_1=prop.code)
testdir.makepyprojecttoml(f"""
[tool.coverage.run]
{prop.conf}
""")
result = testdir.runpytest('-v', f'--cov={script.dirpath()}', script, *opts.split() + prop.args)
result.stdout.fnmatch_lines(
[
f'test_1* {prop.result}*',
]
)
@xdist_params
def test_do_not_append_coverage(pytester, testdir, opts, prop):
script = testdir.makepyfile(test_1=prop.code)
testdir.tmpdir.join('.coveragerc').write(prop.fullconf)
result = testdir.runpytest('-v', f'--cov={script.dirpath()}', script, *opts.split() + prop.args)
result.stdout.fnmatch_lines(
[
f'test_1* {prop.result}*',
]
)
script2 = testdir.makepyfile(test_2=prop.code2)
result = testdir.runpytest('-v', f'--cov={script2.dirpath()}', script2, *opts.split() + prop.args)
result.stdout.fnmatch_lines(
[
'test_1* 0%',
f'test_2* {prop.result2}*',
]
)
@pytest.mark.skipif('sys.platform == "win32" and platform.python_implementation() == "PyPy"')
def test_append_coverage_subprocess(testdir):
testdir.makepyprojecttoml("""
[tool.coverage.run]
patch = ["subprocess"]
""")
scripts = testdir.makepyfile(parent_script=SCRIPT_PARENT, child_script=SCRIPT_CHILD)
parent_script = scripts.dirpath().join('parent_script.py')
result = testdir.runpytest(
'-v',
f'--cov={scripts.dirpath()}',
'--cov-append',
'--cov-report=term-missing',
'--dist=load',
'--tx=2*popen',
max_worker_restart_0,
parent_script,
)
result.stdout.fnmatch_lines(
[
'*_ coverage: platform *, python * _*',
f'child_script* {CHILD_SCRIPT_RESULT}*',
f'parent_script* {PARENT_SCRIPT_RESULT}*',
]
)
assert result.ret == 0
def test_double_cov(testdir):
script = testdir.makepyfile(SCRIPT_SIMPLE)
result = testdir.runpytest('-v', '--assert=plain', '--cov', f'--cov={script.dirpath()}', script)
result.stdout.fnmatch_lines(['*_ coverage: platform *, python * _*', f'test_double_cov* {SCRIPT_SIMPLE_RESULT}*', '*1 passed*'])
assert result.ret == 0
def test_double_cov2(testdir):
script = testdir.makepyfile(SCRIPT_SIMPLE)
result = testdir.runpytest('-v', '--assert=plain', '--cov', '--cov', script)
result.stdout.fnmatch_lines(['*_ coverage: platform *, python * _*', f'test_double_cov2* {SCRIPT_SIMPLE_RESULT}*', '*1 passed*'])
assert result.ret == 0
def test_cov_reset(testdir):
script = testdir.makepyfile(SCRIPT_SIMPLE)
result = testdir.runpytest('-v', '--assert=plain', f'--cov={script.dirpath()}', '--cov-reset', script)
assert 'coverage: platform' not in result.stdout.str()
def test_cov_reset_then_set(testdir):
script = testdir.makepyfile(SCRIPT_SIMPLE)
result = testdir.runpytest('-v', '--assert=plain', f'--cov={script.dirpath()}', '--cov-reset', f'--cov={script.dirpath()}', script)
result.stdout.fnmatch_lines(['*_ coverage: platform *, python * _*', f'test_cov_reset_then_set* {SCRIPT_SIMPLE_RESULT}*', '*1 passed*'])
@pytest.mark.skipif('sys.platform == "win32" and platform.python_implementation() == "PyPy"')
def test_cov_and_no_cov(testdir):
script = testdir.makepyfile(SCRIPT_SIMPLE)
result = testdir.runpytest('-v', '--cov', '--no-cov', '-n', '1', '-s', script)
assert 'Coverage disabled via --no-cov switch!' not in result.stdout.str()
assert 'Coverage disabled via --no-cov switch!' not in result.stderr.str()
assert result.ret == 0
def find_labels(text, pattern):
all_labels = collections.defaultdict(set)
lines = text.splitlines()
for lineno, line in enumerate(lines, start=1):
labels = re.findall(pattern, line)
for label in labels:
all_labels[label].add(lineno)
return all_labels
# The contexts and their labels in contextful.py
EXPECTED_CONTEXTS = {
'': 'c0',
'test_contexts.py::test_01|run': 'r1',
'test_contexts.py::test_02|run': 'r2',
'test_contexts.py::OldStyleTests::test_03|setup': 's3',
'test_contexts.py::OldStyleTests::test_03|run': 'r3',
'test_contexts.py::OldStyleTests::test_04|run': 'r4',
'test_contexts.py::OldStyleTests::test_04|teardown': 't4',
'test_contexts.py::test_05|setup': 's5',
'test_contexts.py::test_05|run': 'r5',
'test_contexts.py::test_06|setup': 's6',
'test_contexts.py::test_06|run': 'r6',
'test_contexts.py::test_07|setup': 's7',
'test_contexts.py::test_07|run': 'r7',
'test_contexts.py::test_08|run': 'r8',
'test_contexts.py::test_08|setup': 's7',
'test_contexts.py::test_09[1]|setup': 's9-1',
'test_contexts.py::test_09[1]|run': 'r9-1',
'test_contexts.py::test_09[2]|setup': 's9-2',
'test_contexts.py::test_09[2]|run': 'r9-2',
'test_contexts.py::test_09[3]|setup': 's9-3',
'test_contexts.py::test_09[3]|run': 'r9-3',
'test_contexts.py::test_10|run': 'r10',
'test_contexts.py::test_11[1-101]|run': 'r11-1',
'test_contexts.py::test_11[2-202]|run': 'r11-2',
'test_contexts.py::test_12[one]|run': 'r12-1',
'test_contexts.py::test_12[two]|run': 'r12-2',
'test_contexts.py::test_13[3-1]|run': 'r13-1',
'test_contexts.py::test_13[3-2]|run': 'r13-2',
'test_contexts.py::test_13[4-1]|run': 'r13-3',
'test_contexts.py::test_13[4-2]|run': 'r13-4',
}
@xdist_params
def test_contexts(pytester, testdir, opts):
with Path(__file__).parent.joinpath('contextful.py').open() as f:
contextful_tests = f.read()
script = testdir.makepyfile(contextful_tests)
result = testdir.runpytest('-v', f'--cov={script.dirpath()}', '--cov-context=test', script, *opts.split())
assert result.ret == 0
result.stdout.fnmatch_lines(
[
'test_contexts* 100%*',
]
)
data = coverage.CoverageData('.coverage')
data.read()
assert data.measured_contexts() == set(EXPECTED_CONTEXTS)
measured = data.measured_files()
assert len(measured) == 1
test_context_path = next(iter(measured))
assert test_context_path.lower() == os.path.abspath('test_contexts.py').lower() # noqa: PTH100
line_data = find_labels(contextful_tests, r'[crst]\d+(?:-\d+)?')
for context, label in EXPECTED_CONTEXTS.items():
if context == '':
continue
data.set_query_context(context)
actual = set(data.lines(test_context_path))
assert line_data[label] == actual, f'Wrong lines for context {context!r}'
def test_contexts_no_cover(testdir):
script = testdir.makepyfile("""
import pytest
def foobar():
return 1
def test_with_coverage():
foobar()
@pytest.mark.no_cover()
def test_without_coverage():
foobar()
""")
result = testdir.runpytest(
'-v',
'--cov-context=test',
'--cov=test_contexts_no_cover',
script,
)
result.stdout.fnmatch_lines(
[
'test_contexts_no_cover.py 8 1 88%',
'TOTAL 8 1 88%',
]
)
assert result.stderr.lines == []
assert result.ret == 0
def test_issue_417(testdir):
# https://github.com/pytest-dev/pytest-cov/issues/417
whatever = testdir.maketxtfile(whatever='')
testdir.inline_genitems(whatever)
| ExamplePlugin |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/data_table_add_row_auto_height.py | {
"start": 125,
"end": 764
} | class ____(App[None]):
def compose(self):
table = DataTable()
self.column = table.add_column("N")
table.add_column("Column", width=10)
table.add_row(3, "hey there", height=None)
table.add_row(1, Text("hey there"), height=None)
table.add_row(5, Text("long string", overflow="fold"), height=None)
table.add_row(2, Panel.fit("Hello\nworld"), height=None)
table.add_row(4, "1\n2\n3\n4\n5\n6\n7", height=None)
yield table
def key_s(self):
self.query_one(DataTable).sort(self.column)
if __name__ == "__main__":
AutoHeightRowsApp().run()
| AutoHeightRowsApp |
python | PyCQA__pylint | tests/functional/i/invalid/invalid_length/invalid_length_returned.py | {
"start": 524,
"end": 586
} | class ____:
"""Length through the metaclass."""
| ThirdGoodLen |
python | spyder-ide__spyder | spyder/widgets/sidebardialog.py | {
"start": 1222,
"end": 2215
} | class ____(QWidget):
"""Base class for pages used in SidebarDialog's"""
# Signals
show_this_page = Signal()
# Constants
MAX_WIDTH = 620
MIN_HEIGHT = 550
def __init__(self, parent):
QWidget.__init__(self, parent)
# Set dimensions
self.setMaximumWidth(self.MAX_WIDTH)
self.setMinimumHeight(self.MIN_HEIGHT)
def initialize(self):
"""Initialize page."""
self.setup_page()
def get_name(self):
"""Return page name."""
raise NotImplementedError
def get_icon(self):
"""Return page icon."""
QIcon()
def setup_page(self):
"""Setup widget to be shown in the page."""
raise NotImplementedError
@staticmethod
def create_icon(name):
"""Create an icon by name using Spyder's icon manager."""
return ima.icon(name)
def sizeHint(self):
"""Default page size."""
return QSize(self.MAX_WIDTH, self.MIN_HEIGHT)
| SidebarPage |
python | pydata__xarray | xarray/core/datatree_render.py | {
"start": 2013,
"end": 9268
} | class ____:
def __init__(
self,
node: DataTree,
style=None,
childiter: type = list,
maxlevel: int | None = None,
maxchildren: int | None = None,
):
"""
Render tree starting at `node`.
Keyword Args:
style (AbstractStyle): Render Style.
childiter: Child iterator. Note, due to the use of node.children.values(),
Iterables that change the order of children cannot be used
(e.g., `reversed`).
maxlevel: Limit rendering to this depth.
maxchildren: Limit number of children at each node.
:any:`RenderDataTree` is an iterator, returning a tuple with 3 items:
`pre`
tree prefix.
`fill`
filling for multiline entries.
`node`
:any:`NodeMixin` object.
It is up to the user to assemble these parts to a whole.
Examples
--------
>>> from xarray import Dataset
>>> from xarray.core.datatree import DataTree
>>> from xarray.core.datatree_render import RenderDataTree
>>> root = DataTree.from_dict(
... {
... "/": Dataset({"a": 0, "b": 1}),
... "/sub0": Dataset({"c": 2, "d": 3}),
... "/sub0/sub0B": Dataset({"e": 4}),
... "/sub0/sub0A": Dataset({"f": 5, "g": 6}),
... "/sub1": Dataset({"h": 7}),
... },
... name="root",
... )
# Simple one line:
>>> for pre, _, node in RenderDataTree(root):
... print(f"{pre}{node.name}")
...
root
├── sub0
│ ├── sub0B
│ └── sub0A
└── sub1
# Multiline:
>>> for pre, fill, node in RenderDataTree(root):
... print(f"{pre}{node.name}")
... for variable in node.variables:
... print(f"{fill}{variable}")
...
root
a
b
├── sub0
│ c
│ d
│ ├── sub0B
│ │ e
│ └── sub0A
│ f
│ g
└── sub1
h
:any:`by_attr` simplifies attribute rendering and supports multiline:
>>> print(RenderDataTree(root).by_attr())
root
├── sub0
│ ├── sub0B
│ └── sub0A
└── sub1
# `maxlevel` limits the depth of the tree:
>>> print(RenderDataTree(root, maxlevel=2).by_attr("name"))
root
├── sub0
└── sub1
# `maxchildren` limits the number of children per node
>>> print(RenderDataTree(root, maxchildren=1).by_attr("name"))
root
├── sub0
│ ├── sub0B
│ ...
...
"""
if style is None:
style = ContStyle()
if not isinstance(style, AbstractStyle):
style = style()
self.node = node
self.style = style
self.childiter = childiter
self.maxlevel = maxlevel
self.maxchildren = maxchildren
def __iter__(self) -> Iterator[Row]:
return self.__next(self.node, tuple())
def __next(
self,
node: DataTree,
continues: tuple[bool, ...],
level: int = 0,
) -> Iterator[Row]:
yield RenderDataTree.__item(node, continues, self.style)
children = node.children.values()
level += 1
if children and (self.maxlevel is None or level < self.maxlevel):
nchildren = len(children)
children = self.childiter(children)
for i, (child, is_last) in enumerate(_is_last(children)):
if (
self.maxchildren is None
or i < ceil(self.maxchildren / 2)
or i >= ceil(nchildren - self.maxchildren / 2)
):
yield from self.__next(
child,
continues + (not is_last,),
level=level,
)
if (
self.maxchildren is not None
and nchildren > self.maxchildren
and i == ceil(self.maxchildren / 2)
):
yield RenderDataTree.__item("...", continues, self.style)
@staticmethod
def __item(
node: DataTree | str, continues: tuple[bool, ...], style: AbstractStyle
) -> Row:
if not continues:
return Row("", "", node)
else:
items = [style.vertical if cont else style.empty for cont in continues]
indent = "".join(items[:-1])
branch = style.cont if continues[-1] else style.end
pre = indent + branch
fill = "".join(items)
return Row(pre, fill, node)
def __str__(self) -> str:
return str(self.node)
def __repr__(self) -> str:
classname = self.__class__.__name__
args = [
repr(self.node),
f"style={self.style!r}",
f"childiter={self.childiter!r}",
]
return f"{classname}({', '.join(args)})"
def by_attr(self, attrname: str = "name") -> str:
"""
Return rendered tree with node attribute `attrname`.
Examples
--------
>>> from xarray import Dataset
>>> from xarray.core.datatree import DataTree
>>> from xarray.core.datatree_render import RenderDataTree
>>> root = DataTree.from_dict(
... {
... "/sub0/sub0B": Dataset({"foo": 4, "bar": 109}),
... "/sub0/sub0A": None,
... "/sub1/sub1A": None,
... "/sub1/sub1B": Dataset({"bar": 8}),
... "/sub1/sub1C/sub1Ca": None,
... },
... name="root",
... )
>>> print(RenderDataTree(root).by_attr("name"))
root
├── sub0
│ ├── sub0B
│ └── sub0A
└── sub1
├── sub1A
├── sub1B
└── sub1C
└── sub1Ca
"""
def get() -> Iterator[str]:
for pre, fill, node in self:
if isinstance(node, str):
yield f"{fill}{node}"
continue
attr = (
attrname(node)
if callable(attrname)
else getattr(node, attrname, "")
)
if isinstance(attr, list | tuple):
lines = attr
else:
lines = str(attr).split("\n")
yield f"{pre}{lines[0]}"
for line in lines[1:]:
yield f"{fill}{line}"
return "\n".join(get())
def _is_last(iterable: Iterable) -> Iterator[tuple[DataTree, bool]]:
iter_ = iter(iterable)
try:
nextitem = next(iter_)
except StopIteration:
pass
else:
item = nextitem
while True:
try:
nextitem = next(iter_)
yield item, False
except StopIteration:
yield nextitem, True
break
item = nextitem
| RenderDataTree |
python | django__django | tests/forms_tests/models.py | {
"start": 2878,
"end": 3235
} | class ____(models.Model):
multi_choice = models.ManyToManyField(
ChoiceOptionModel,
blank=False,
related_name="not_relevant",
default=choice_default,
)
multi_choice_optional = models.ManyToManyField(
ChoiceOptionModel,
blank=True,
related_name="not_relevant2",
)
| OptionalMultiChoiceModel |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 47571,
"end": 48287
} | class ____:
xlAverage = -4106 # from enum XlConsolidationFunction
xlCount = -4112 # from enum XlConsolidationFunction
xlCountNums = -4113 # from enum XlConsolidationFunction
xlMax = -4136 # from enum XlConsolidationFunction
xlMin = -4139 # from enum XlConsolidationFunction
xlProduct = -4149 # from enum XlConsolidationFunction
xlStDev = -4155 # from enum XlConsolidationFunction
xlStDevP = -4156 # from enum XlConsolidationFunction
xlSum = -4157 # from enum XlConsolidationFunction
xlUnknown = 1000 # from enum XlConsolidationFunction
xlVar = -4164 # from enum XlConsolidationFunction
xlVarP = -4165 # from enum XlConsolidationFunction
| ConsolidationFunction |
python | takluyver__flit | flit/tomlify.py | {
"start": 353,
"end": 2281
} | class ____(configparser.ConfigParser):
optionxform = staticmethod(str)
def convert(path):
cp = configparser.ConfigParser()
with path.open(encoding='utf-8') as f:
cp.read_file(f)
ep_file = Path('entry_points.txt')
metadata = OrderedDict()
for name, value in cp['metadata'].items():
if name in metadata_list_fields:
metadata[name] = [l for l in value.splitlines() if l.strip()]
elif name == 'entry-points-file':
ep_file = Path(value)
else:
metadata[name] = value
if 'scripts' in cp:
scripts = OrderedDict(cp['scripts'])
else:
scripts = {}
entrypoints = CaseSensitiveConfigParser()
if ep_file.is_file():
with ep_file.open(encoding='utf-8') as f:
entrypoints.read_file(f)
written_entrypoints = False
with Path('pyproject.toml').open('w', encoding='utf-8') as f:
f.write(TEMPLATE.format(metadata=tomli_w.dumps(metadata)))
if scripts:
f.write('\n[tool.flit.scripts]\n')
f.write(tomli_w.dumps(scripts))
for groupname, group in entrypoints.items():
if not dict(group):
continue
if '.' in groupname:
groupname = f'"{groupname}"'
f.write(f'\n[tool.flit.entrypoints.{groupname}]\n')
f.write(tomli_w.dumps(OrderedDict(group)))
written_entrypoints = True
print("Written 'pyproject.toml'")
files = str(path)
if written_entrypoints:
files += ' and ' + str(ep_file)
print("Please check the new file, then remove", files)
def main(argv=None):
ap = argparse.ArgumentParser()
ap.add_argument('-f', '--ini-file', type=Path, default='flit.ini')
args = ap.parse_args(argv)
os.chdir(str(args.ini_file.parent))
convert(Path(args.ini_file.name))
if __name__ == '__main__':
main()
| CaseSensitiveConfigParser |
python | kamyu104__LeetCode-Solutions | Python/add-bold-tag-in-string.py | {
"start": 904,
"end": 1953
} | class ____(object):
def addBoldTag(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: str
"""
_trie = lambda: collections.defaultdict(_trie)
trie = _trie()
for i, word in enumerate(words):
functools.reduce(dict.__getitem__, word, trie).setdefault("_end")
lookup = [False] * len(s)
for i in xrange(len(s)):
curr = trie
k = -1
for j in xrange(i, len(s)):
if s[j] not in curr:
break
curr = curr[s[j]]
if "_end" in curr:
k = j
for j in xrange(i, k+1):
lookup[j] = True
result = []
for i in xrange(len(s)):
if lookup[i] and (i == 0 or not lookup[i-1]):
result.append("<b>")
result.append(s[i])
if lookup[i] and (i == len(s)-1 or not lookup[i+1]):
result.append("</b>")
return "".join(result)
| Solution2 |
python | pandas-dev__pandas | asv_bench/benchmarks/timeseries.py | {
"start": 2464,
"end": 2781
} | class ____:
params = [None, "US/Eastern"]
param_names = "tz"
def setup(self, tz):
idx = date_range(start="1/1/2000", periods=1000, freq="h", tz=tz)
self.df = DataFrame(np.random.randn(1000, 2), index=idx)
def time_reset_datetimeindex(self, tz):
self.df.reset_index()
| ResetIndex |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 6736,
"end": 8396
} | class ____(Protocol[ContextT]):
"""Extra data used during serialization."""
@property
def include(self) -> IncExCall:
"""The `include` argument set during serialization."""
...
@property
def exclude(self) -> IncExCall:
"""The `exclude` argument set during serialization."""
...
@property
def context(self) -> ContextT:
"""The current serialization context."""
...
@property
def mode(self) -> Literal['python', 'json'] | str:
"""The serialization mode set during serialization."""
...
@property
def by_alias(self) -> bool:
"""The `by_alias` argument set during serialization."""
...
@property
def exclude_unset(self) -> bool:
"""The `exclude_unset` argument set during serialization."""
...
@property
def exclude_defaults(self) -> bool:
"""The `exclude_defaults` argument set during serialization."""
...
@property
def exclude_none(self) -> bool:
"""The `exclude_none` argument set during serialization."""
...
@property
def exclude_computed_fields(self) -> bool:
"""The `exclude_computed_fields` argument set during serialization."""
...
@property
def serialize_as_any(self) -> bool:
"""The `serialize_as_any` argument set during serialization."""
...
@property
def round_trip(self) -> bool:
"""The `round_trip` argument set during serialization."""
...
def mode_is_json(self) -> bool: ...
def __str__(self) -> str: ...
def __repr__(self) -> str: ...
| SerializationInfo |
python | dagster-io__dagster | python_modules/libraries/dagster-deltalake-polars/dagster_deltalake_polars/deltalake_polars_type_handler.py | {
"start": 512,
"end": 2299
} | class ____(DeltalakeBaseArrowTypeHandler[PolarsTypes]):
def from_arrow(
self,
obj: Union[ds.Dataset, pa.RecordBatchReader],
target_type: type[PolarsTypes],
) -> PolarsTypes:
if isinstance(obj, pa.RecordBatchReader):
return pl.DataFrame(obj.read_all())
elif isinstance(obj, ds.Dataset):
df = pl.scan_pyarrow_dataset(obj)
if target_type == pl.DataFrame:
return df.collect()
else:
return df
else:
raise NotImplementedError("Unsupported objected passed of type: %s", type(obj))
def to_arrow(self, obj: PolarsTypes) -> tuple[pa.RecordBatchReader, dict[str, Any]]:
if isinstance(obj, pl.LazyFrame):
obj = obj.collect()
return obj.to_arrow().to_reader(), {}
def load_input(
self,
context: InputContext,
table_slice: TableSlice,
connection: TableConnection,
) -> PolarsTypes:
"""Loads the input as a Polars DataFrame or LazyFrame."""
dataset = _table_reader(table_slice, connection)
if table_slice.columns is not None:
if context.dagster_type.typing_type == pl.LazyFrame:
return self.from_arrow(dataset, context.dagster_type.typing_type).select(
table_slice.columns
)
else:
scanner = dataset.scanner(columns=table_slice.columns)
return self.from_arrow(scanner.to_reader(), context.dagster_type.typing_type)
else:
return self.from_arrow(dataset, context.dagster_type.typing_type)
@property
def supported_types(self) -> Sequence[type[object]]:
return [pl.DataFrame, pl.LazyFrame]
| DeltaLakePolarsTypeHandler |
python | euske__pdfminer | pdfminer/layout.py | {
"start": 4127,
"end": 4340
} | class ____(LTCurve):
def __init__(self, linewidth, bbox):
(x0, y0, x1, y1) = bbox
LTCurve.__init__(self, linewidth, [(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
return
## LTImage
##
| LTRect |
python | sqlalchemy__sqlalchemy | test/orm/declarative/test_tm_future_annotations.py | {
"start": 1562,
"end": 5162
} | class ____(fixtures.TestBase):
@testing.combinations(
("Mapped[Address]", 'Mapped["Address"]'),
('Mapped["Address"]', 'Mapped["Address"]'),
("Mapped['Address']", "Mapped['Address']"),
("Mapped[Address | None]", 'Mapped["Address | None"]'),
("Mapped[None | Address]", 'Mapped["None | Address"]'),
('Mapped["Address | None"]', 'Mapped["Address | None"]'),
("Mapped['None | Address']", "Mapped['None | Address']"),
('Mapped["Address" | "None"]', 'Mapped["Address" | "None"]'),
('Mapped["None" | "Address"]', 'Mapped["None" | "Address"]'),
("Mapped[A_]", 'Mapped["A_"]'),
("Mapped[_TypingLiteral]", 'Mapped["_TypingLiteral"]'),
("Mapped[datetime.datetime]", 'Mapped["datetime.datetime"]'),
("Mapped[List[Edge]]", 'Mapped[List["Edge"]]'),
(
"Mapped[collections.abc.MutableSequence[B]]",
'Mapped[collections.abc.MutableSequence["B"]]',
),
("Mapped[typing.Sequence[B]]", 'Mapped[typing.Sequence["B"]]'),
("Mapped[dict[str, str]]", 'Mapped[dict["str", "str"]]'),
("Mapped[Dict[str, str]]", 'Mapped[Dict["str", "str"]]'),
("Mapped[list[str]]", 'Mapped[list["str"]]'),
("Mapped[dict[str, str] | None]", "Mapped[dict[str, str] | None]"),
("Mapped[Optional[anno_str_mc]]", 'Mapped[Optional["anno_str_mc"]]'),
(
"Mapped[Optional[Dict[str, str]]]",
'Mapped[Optional[Dict["str", "str"]]]',
),
(
"Mapped[Optional[Union[Decimal, float]]]",
'Mapped[Optional[Union["Decimal", "float"]]]',
),
(
"Mapped[Optional[Union[list[int], list[str]]]]",
"Mapped[Optional[Union[list[int], list[str]]]]",
),
("Mapped[TestType[str]]", 'Mapped[TestType["str"]]'),
("Mapped[TestType[str, str]]", 'Mapped[TestType["str", "str"]]'),
("Mapped[Union[A, None]]", 'Mapped[Union["A", "None"]]'),
("Mapped[Union[Decimal, float]]", 'Mapped[Union["Decimal", "float"]]'),
(
"Mapped[Union[Decimal, float, None]]",
'Mapped[Union["Decimal", "float", "None"]]',
),
(
"Mapped[Union[Dict[str, str], None]]",
"Mapped[Union[Dict[str, str], None]]",
),
("Mapped[Union[float, Decimal]]", 'Mapped[Union["float", "Decimal"]]'),
(
"Mapped[Union[list[int], list[str]]]",
"Mapped[Union[list[int], list[str]]]",
),
(
"Mapped[Union[list[int], list[str], None]]",
"Mapped[Union[list[int], list[str], None]]",
),
(
"Mapped[Union[None, Dict[str, str]]]",
"Mapped[Union[None, Dict[str, str]]]",
),
(
"Mapped[Union[None, list[int], list[str]]]",
"Mapped[Union[None, list[int], list[str]]]",
),
("Mapped[A | None]", 'Mapped["A | None"]'),
("Mapped[Decimal | float]", 'Mapped["Decimal | float"]'),
("Mapped[Decimal | float | None]", 'Mapped["Decimal | float | None"]'),
(
"Mapped[list[int] | list[str] | None]",
"Mapped[list[int] | list[str] | None]",
),
("Mapped[None | dict[str, str]]", "Mapped[None | dict[str, str]]"),
(
"Mapped[None | list[int] | list[str]]",
"Mapped[None | list[int] | list[str]]",
),
)
def test_cleanup_mapped_str_annotation(self, given, expected):
eq_(_cleanup_mapped_str_annotation(given, __name__), expected)
| AnnoUtilTest |
python | sphinx-doc__sphinx | sphinx/writers/text.py | {
"start": 1450,
"end": 9236
} | class ____:
"""Represents a table, handling cells that can span multiple lines
or rows, like::
+-----------+-----+
| AAA | BBB |
+-----+-----+ |
| | XXX | |
| +-----+-----+
| DDD | CCC |
+-----+-----------+
This class can be used in two ways, either:
- With absolute positions: call ``table[line, col] = Cell(...)``,
this overwrites any existing cell(s) at these positions.
- With relative positions: call the ``add_row()`` and
``add_cell(Cell(...))`` as needed.
Cells spanning multiple rows or multiple columns (having a
colspan or rowspan greater than one) are automatically referenced
by all the table cells they cover. This is a useful
representation as we can simply check
``if self[x, y] is self[x, y+1]`` to recognize a rowspan.
Colwidth is not automatically computed, it has to be given, either
at construction time, or during the table construction.
Example usage::
table = Table([6, 6])
table.add_cell(Cell("foo"))
table.add_cell(Cell("bar"))
table.set_separator()
table.add_row()
table.add_cell(Cell("FOO"))
table.add_cell(Cell("BAR"))
print(table)
+--------+--------+
| foo | bar |
|========|========|
| FOO | BAR |
+--------+--------+
"""
def __init__(self, colwidth: list[int] | None = None) -> None:
self.lines: list[list[Cell]] = []
self.separator = 0
self.colwidth: list[int] = colwidth if colwidth is not None else []
self.current_line = 0
self.current_col = 0
def add_row(self) -> None:
"""Add a row to the table, to use with ``add_cell()``. It is not needed
to call ``add_row()`` before the first ``add_cell()``.
"""
self.current_line += 1
self.current_col = 0
def set_separator(self) -> None:
"""Sets the separator below the current line."""
self.separator = len(self.lines)
def add_cell(self, cell: Cell) -> None:
"""Add a cell to the current line, to use with ``add_row()``. To add
a cell spanning multiple lines or rows, simply set the
``cell.colspan`` or ``cell.rowspan`` BEFORE inserting it into
the table.
"""
while self[self.current_line, self.current_col]:
self.current_col += 1
self[self.current_line, self.current_col] = cell
self.current_col += cell.colspan
def __getitem__(self, pos: tuple[int, int]) -> Cell:
line, col = pos
self._ensure_has_line(line + 1)
self._ensure_has_column(col + 1)
return self.lines[line][col]
def __setitem__(self, pos: tuple[int, int], cell: Cell) -> None:
line, col = pos
self._ensure_has_line(line + cell.rowspan)
self._ensure_has_column(col + cell.colspan)
for dline in range(cell.rowspan):
for dcol in range(cell.colspan):
self.lines[line + dline][col + dcol] = cell
cell.row = line
cell.col = col
def _ensure_has_line(self, line: int) -> None:
while len(self.lines) < line:
self.lines.append([])
def _ensure_has_column(self, col: int) -> None:
for line in self.lines:
while len(line) < col:
line.append(Cell())
def __repr__(self) -> str:
return '\n'.join(map(repr, self.lines))
def cell_width(self, cell: Cell, source: list[int]) -> int:
"""Give the cell width, according to the given source (either
``self.colwidth`` or ``self.measured_widths``).
This takes into account cells spanning multiple columns.
"""
if cell.row is None or cell.col is None:
msg = 'Cell co-ordinates have not been set'
raise ValueError(msg)
width = 0
for i in range(self[cell.row, cell.col].colspan):
width += source[cell.col + i]
return width + (cell.colspan - 1) * 3
@property
def cells(self) -> Iterator[Cell]:
seen: set[Cell] = set()
for line in self.lines:
for cell in line:
if cell and cell not in seen:
yield cell
seen.add(cell)
def rewrap(self) -> None:
"""Call ``cell.wrap()`` on all cells, and measure each column width
after wrapping (result written in ``self.measured_widths``).
"""
self.measured_widths = self.colwidth[:]
for cell in self.cells:
cell.wrap(width=self.cell_width(cell, self.colwidth))
if not cell.wrapped:
continue
if cell.row is None or cell.col is None:
msg = 'Cell co-ordinates have not been set'
raise ValueError(msg)
width = math.ceil(max(column_width(x) for x in cell.wrapped) / cell.colspan)
for col in range(cell.col, cell.col + cell.colspan):
self.measured_widths[col] = max(self.measured_widths[col], width)
def physical_lines_for_line(self, line: list[Cell]) -> int:
"""For a given line, compute the number of physical lines it spans
due to text wrapping.
"""
physical_lines = 1
for cell in line:
physical_lines = max(physical_lines, len(cell.wrapped))
return physical_lines
def __str__(self) -> str:
out = []
self.rewrap()
def writesep(char: str = '-', lineno: int | None = None) -> str:
"""Called on the line *before* lineno.
Called with no *lineno* for the last sep.
"""
out: list[str] = []
for colno, width in enumerate(self.measured_widths):
if (
lineno is not None
and lineno > 0
and self[lineno, colno] is self[lineno - 1, colno]
):
out.append(' ' * (width + 2))
else:
out.append(char * (width + 2))
head = '+' if out[0][0] == '-' else '|'
tail = '+' if out[-1][0] == '-' else '|'
glue = [
'+' if left[0] == '-' or right[0] == '-' else '|'
for left, right in pairwise(out)
]
glue.append(tail)
return head + ''.join(chain.from_iterable(zip(out, glue, strict=False)))
for lineno, line in enumerate(self.lines):
if self.separator and lineno == self.separator:
out.append(writesep('=', lineno))
else:
out.append(writesep('-', lineno))
for physical_line in range(self.physical_lines_for_line(line)):
linestr = ['|']
for colno, cell in enumerate(line):
if cell.col != colno:
continue
if lineno != cell.row: # NoQA: SIM114
physical_text = ''
elif physical_line >= len(cell.wrapped):
physical_text = ''
else:
physical_text = cell.wrapped[physical_line]
adjust_len = len(physical_text) - column_width(physical_text)
linestr.append(
' '
+ physical_text.ljust(
self.cell_width(cell, self.measured_widths)
+ 1
+ adjust_len,
)
+ '|',
)
out.append(''.join(linestr))
out.append(writesep('-'))
return '\n'.join(out)
| Table |
python | streamlit__streamlit | lib/streamlit/testing/v1/element_tree.py | {
"start": 9141,
"end": 9326
} | class ____(AlertBase):
def __init__(self, proto: AlertProto, root: ElementTree) -> None:
super().__init__(proto, root)
self.type = "error"
@dataclass(repr=False)
| Error |
python | optuna__optuna | tests/test_convert_positional_args.py | {
"start": 207,
"end": 4759
} | class ____:
@convert_positional_args(
previous_positional_arg_names=["self", "a", "b"],
deprecated_version="9.9.9",
removed_version="9.9.9",
)
def simple_method(self, a: int, *, b: int, c: int = 1) -> None:
pass
def test_convert_positional_args_decorator() -> None:
previous_positional_arg_names: list[str] = []
decorator_converter = convert_positional_args(
previous_positional_arg_names=previous_positional_arg_names,
deprecated_version="9.9.9",
removed_version="9.9.9",
)
decorated_func = decorator_converter(_sample_func)
assert decorated_func.__name__ == _sample_func.__name__
def test_convert_positional_args_future_warning_for_methods() -> None:
simple_class = _SimpleClass()
with pytest.warns(FutureWarning) as record:
simple_class.simple_method(1, 2, c=3) # type: ignore
simple_class.simple_method(1, b=2, c=3) # No warning.
simple_class.simple_method(a=1, b=2, c=3) # No warning.
assert len(record) == 1
for warn in record.list:
assert isinstance(warn.message, FutureWarning)
assert "simple_method" in str(warn.message)
def test_convert_positional_args_future_warning() -> None:
previous_positional_arg_names: list[str] = ["a", "b"]
decorator_converter = convert_positional_args(
previous_positional_arg_names=previous_positional_arg_names,
deprecated_version="9.9.9",
removed_version="9.9.9",
)
assert callable(decorator_converter)
decorated_func = decorator_converter(_sample_func)
with pytest.warns(FutureWarning) as record:
decorated_func(1, 2, c=3) # type: ignore
decorated_func(1, b=2, c=3) # type: ignore
decorated_func(a=1, b=2, c=3) # No warning.
assert len(record) == 2
for warn in record.list:
assert isinstance(warn.message, FutureWarning)
assert _sample_func.__name__ in str(warn.message)
def test_convert_positional_args_mypy_type_inference() -> None:
previous_positional_arg_names: list[str] = []
decorator_converter = convert_positional_args(
previous_positional_arg_names=previous_positional_arg_names,
deprecated_version="9.9.9",
removed_version="9.9.9",
)
assert callable(decorator_converter)
class _Sample:
def __init__(self) -> None:
pass
def method(self) -> bool:
return True
def _func_sample() -> _Sample:
return _Sample()
def _func_none() -> None:
pass
ret_none = decorator_converter(_func_none)()
assert ret_none is None
ret_sample = decorator_converter(_func_sample)()
assert isinstance(ret_sample, _Sample)
assert ret_sample.method()
@pytest.mark.parametrize(
"previous_positional_arg_names, raise_error",
[(["a", "b", "c", "d"], True), (["a", "d"], True), (["b", "a"], False)],
)
def test_convert_positional_args_invalid_previous_positional_arg_names(
previous_positional_arg_names: list[str], raise_error: bool
) -> None:
decorator_converter = convert_positional_args(
previous_positional_arg_names=previous_positional_arg_names,
deprecated_version="9.9.9",
removed_version="9.9.9",
)
assert callable(decorator_converter)
if raise_error:
with pytest.raises(AssertionError) as record:
decorator_converter(_sample_func)
res = re.findall(r"({.+?}|set\(\))", str(record.value))
assert len(res) == 2
assert eval(res[0]) == set(previous_positional_arg_names)
assert eval(res[1]) == set(["a", "b", "c"])
else:
decorator_converter(_sample_func)
def test_convert_positional_args_invalid_positional_args() -> None:
previous_positional_arg_names: list[str] = ["a", "b"]
decorator_converter = convert_positional_args(
previous_positional_arg_names=previous_positional_arg_names,
deprecated_version="9.9.9",
removed_version="9.9.9",
)
assert callable(decorator_converter)
decorated_func = decorator_converter(_sample_func)
with pytest.warns(FutureWarning):
with pytest.raises(TypeError) as record:
decorated_func(1, 2, 3) # type: ignore
assert str(record.value) == "_sample_func() takes 2 positional arguments but 3 were given."
with pytest.raises(TypeError) as record:
decorated_func(1, 3, b=2) # type: ignore
assert str(record.value) == "_sample_func() got multiple values for arguments {'b'}."
| _SimpleClass |
python | doocs__leetcode | solution/0500-0599/0524.Longest Word in Dictionary through Deleting/Solution.py | {
"start": 0,
"end": 506
} | class ____:
def findLongestWord(self, s: str, dictionary: List[str]) -> str:
def check(s: str, t: str) -> bool:
m, n = len(s), len(t)
i = j = 0
while i < m and j < n:
if s[i] == t[j]:
i += 1
j += 1
return i == m
ans = ""
for t in dictionary:
if check(t, s) and (len(ans) < len(t) or (len(ans) == len(t) and ans > t)):
ans = t
return ans
| Solution |
python | jazzband__django-model-utils | model_utils/models.py | {
"start": 553,
"end": 1303
} | class ____(models.Model):
"""
An abstract base class model that provides self-updating
``created`` and ``modified`` fields.
"""
created = AutoCreatedField(_('created'))
modified = AutoLastModifiedField(_('modified'))
def save(self, *args: Any, **kwargs: Any) -> None:
"""
Overriding the save method in order to make sure that
modified field is updated even if it is not given as
a parameter to the update field argument.
"""
update_fields = kwargs.get('update_fields', None)
if update_fields:
kwargs['update_fields'] = set(update_fields).union({'modified'})
super().save(*args, **kwargs)
class Meta:
abstract = True
| TimeStampedModel |
python | great-expectations__great_expectations | contrib/capitalone_dataprofiler_expectations/capitalone_dataprofiler_expectations/expectations/expect_profile_numeric_columns_diff_greater_than_or_equal_to_threshold.py | {
"start": 5626,
"end": 13784
} | class ____(
ProfileNumericColumnsDiffExpectation
):
"""Expect a statistic's value for a given column of a DataProfiler difference report to be greater than or equal to the specified threshold.
This expectation takes the difference report between the data it is called on and a DataProfiler profile of the same schema loaded from a provided path.
This function builds upon the custom ProfileNumericColumnsDiff Expectation of Capital One's DataProfiler Expectations.
Each numerical column will be checked against a user provided dictionary of columns paired with dictionaries of statistics containing a threshold value.
It is expected that a statistics value for a given column is greater than or equal to the specified threshold.
Args:
profile_path (str): A path to a saved DataProfiler profile object on the local filesystem.
limit_check_report_keys (dict): A dict, containing column names as keys and dicts as values that contain statistics as keys and ints or floats as values
denoting the threshold that the statistic delta is expectated to exceed.
mostly (float - optional): a value indicating the lower bound percentage of successful values that must be present to evaluate to success=True.
validator.expect_profile_numerical_columns_diff_greater_than_threshold(
profile_path = "C:/path_to/my_profile.pkl",
limit_check_report_keys = {
"column_one": {
"min": 0
},
"*": {
"*": 1
},
}
)
Note: In limit_check_report_keys, "*" in place of a column denotes a general operator in which the value it stores will be applied to every column in the data that has no explicit key.
"*" in place of a statistic denotes a general operator in which the bounds it stores will be applied to every statistic for the given column that has no explicit key.
"""
example_profile_data = [
[2, 5, "10", "ten", 25],
[4, 10, "20", "twenty", 50],
[6, 15, "30", "thirty", 75],
[8, 20, "40", "forty", 100],
[10, 25, "50", "fifty", 125],
]
example_profile_columns = [
"by_2",
"by_5",
"str_by_10",
"words_by_10",
"by_25",
]
df = pd.DataFrame(example_profile_data, columns=example_profile_columns)
profiler_opts = dp.ProfilerOptions()
profiler_opts.structured_options.multiprocess.is_enabled = False
example_profile = dp.Profiler(df, options=profiler_opts)
profile_path = "/example_profiles/expect_profile_diff_less_than_threshold_profile.pkl"
dir_path = os.path.dirname(os.path.abspath(__file__)) # noqa: PTH120, PTH100
profile_path = dir_path + profile_path
example_profile.save(filepath=profile_path)
examples = [
{
"data": {
"by_2": [4, 6, 8, 10, 12],
"by_5": [10, 15, 20, 25, 30],
"str_by_10": ["20", "30", "40", "50", "60"],
"words_by_10": ["twenty", "thirty", "forty", "fifty", "sixty"],
"by_25": [50, 75, 100, 125, 150],
},
"tests": [
{
"title": "profile_min_delta_above_threshold",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"profile_path": profile_path,
"limit_check_report_keys": {
"*": {
"min": 0,
},
},
},
"out": {"success": True},
},
{
"title": "profile_min_delta_equal_to_threshold",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"profile_path": profile_path,
"limit_check_report_keys": {
"by_2": {
"min": 2,
},
},
},
"out": {"success": True},
},
{
"title": "profile_all_stats_below_delta_threshold",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"profile_path": profile_path,
"limit_check_report_keys": {
"*": {"*": 100},
"by_2": {
"min": 4,
},
},
},
"out": {"success": False},
},
{
"title": "checking_single_failure_in_one_column",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"profile_path": profile_path,
"limit_check_report_keys": {
"*": {"*": -20},
"by_2": {"min": 3},
},
},
"out": {"success": False},
},
{
"title": "single_failure_still_mostly_successful",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"profile_path": profile_path,
"limit_check_report_keys": {
"*": {"*": -20},
"by_2": {"min": 3},
},
"mostly": 0.75,
},
"out": {"success": True},
},
{
"title": "using_default_limit_check_report_keys_for_no_diff",
"exact_match_out": False,
"include_in_gallery": True,
"in": {
"profile_path": profile_path,
"mostly": 1.0,
},
"out": {"success": False},
},
],
},
]
profile_metric = "data_profiler.profile_numeric_columns_diff_greater_than_or_equal_to_threshold"
success_keys = (
"profile_path",
"limit_check_report_keys",
"numerical_diff_statistics",
"mostly",
)
default_limit_check_report_keys = {
"*": {
"min": 0,
"max": 0,
"sum": 0,
"mean": 0,
"median": 0,
"median_absolute_deviation": 0,
"variance": 0,
"stddev": 0,
"unique_count": 0,
"unique_ratio": 0,
"gini_impurity": 0,
"unalikeability": 0,
"sample_size": 0,
"null_count": 0,
}
}
numerical_diff_statistics = list(default_limit_check_report_keys["*"].keys())
default_kwarg_values = {
"limit_check_report_keys": default_limit_check_report_keys,
"numerical_diff_statistics": numerical_diff_statistics,
"mostly": 1.0,
}
library_metadata = {
"requirements": ["dataprofiler", "tensorflow", "scikit-learn", "numpy"],
"maturity": "experimental", # "concept_only", "experimental", "beta", or "production"
"tags": [
"dataprofiler",
"dataassistance",
], # Tags for this Expectation in the Gallery
"contributors": [ # Github handles for all contributors to this Expectation.
"@stevensecreti", # Don't forget to add your github handle here!
],
}
if __name__ == "__main__":
diagnostics_report = (
ExpectProfileNumericColumnsDiffGreaterThanOrEqualToThreshold().run_diagnostics()
)
print(diagnostics_report.generate_checklist())
| ExpectProfileNumericColumnsDiffGreaterThanOrEqualToThreshold |
python | mlflow__mlflow | examples/pytorch/torchscript/MNIST/mnist_torchscript.py | {
"start": 218,
"end": 6193
} | class ____(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout(0.25)
self.dropout2 = nn.Dropout(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.conv2(x)
x = F.relu(x)
x = F.max_pool2d(x, 2)
x = self.dropout1(x)
x = torch.flatten(x, 1)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x)
x = F.log_softmax(x, dim=1)
return x
def train(args, model, device, train_loader, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(train_loader):
data = data.to(device)
target = target.to(device)
optimizer.zero_grad()
output = model(data)
loss = F.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % args.log_interval == 0:
print(
"Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}".format(
epoch,
batch_idx * len(data),
len(train_loader.dataset),
100.0 * batch_idx / len(train_loader),
loss.item(),
)
)
if args.dry_run:
break
def test(model, device, test_loader):
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data = data.to(device)
target = target.to(device)
output = model(data)
test_loss += F.nll_loss(output, target, reduction="sum").item() # sum up batch loss
pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability
correct += pred.eq(target.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print(
"\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n".format(
test_loss,
correct,
len(test_loader.dataset),
100.0 * correct / len(test_loader.dataset),
)
)
def main():
# Training settings
parser = argparse.ArgumentParser(description="PyTorch MNIST Example")
parser.add_argument(
"--batch-size",
type=int,
default=64,
metavar="N",
help="input batch size for training (default: 64)",
)
parser.add_argument(
"--test-batch-size",
type=int,
default=1000,
metavar="N",
help="input batch size for testing (default: 1000)",
)
parser.add_argument(
"--epochs",
type=int,
default=14,
metavar="N",
help="number of epochs to train (default: 14)",
)
parser.add_argument(
"--lr",
type=float,
default=1.0,
metavar="LR",
help="learning rate (default: 1.0)",
)
parser.add_argument(
"--gamma",
type=float,
default=0.7,
metavar="M",
help="Learning rate step gamma (default: 0.7)",
)
parser.add_argument(
"--no-cuda", action="store_true", default=False, help="disables CUDA training"
)
parser.add_argument(
"--dry-run",
action="store_true",
default=False,
help="quickly check a single pass",
)
parser.add_argument("--seed", type=int, default=1, metavar="S", help="random seed (default: 1)")
parser.add_argument(
"--log-interval",
type=int,
default=10,
metavar="N",
help="how many batches to wait before logging training status",
)
parser.add_argument(
"--save-model",
action="store_true",
default=False,
help="For Saving the current model",
)
args = parser.parse_args()
use_cuda = not args.no_cuda and torch.cuda.is_available()
torch.manual_seed(args.seed)
device = torch.device("cuda" if use_cuda else "cpu")
train_kwargs = {"batch_size": args.batch_size}
test_kwargs = {"batch_size": args.test_batch_size}
if use_cuda:
cuda_kwargs = {"num_workers": 1, "pin_memory": True, "shuffle": True}
train_kwargs.update(cuda_kwargs)
test_kwargs.update(cuda_kwargs)
transform = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
)
dataset1 = datasets.MNIST("../data", train=True, download=True, transform=transform)
dataset2 = datasets.MNIST("../data", train=False, transform=transform)
train_loader = torch.utils.data.DataLoader(dataset1, **train_kwargs)
test_loader = torch.utils.data.DataLoader(dataset2, **test_kwargs)
model = Net().to(device)
scripted_model = torch.jit.script(model) # scripting the model
optimizer = optim.Adadelta(model.parameters(), lr=args.lr)
scheduler = StepLR(optimizer, step_size=1, gamma=args.gamma)
for epoch in range(1, args.epochs + 1):
train(args, scripted_model, device, train_loader, optimizer, epoch)
scheduler.step()
test(scripted_model, device, test_loader)
with mlflow.start_run():
mlflow.pytorch.log_model(scripted_model, name="model") # logging scripted model
model_path = mlflow.get_artifact_uri("model")
loaded_pytorch_model = mlflow.pytorch.load_model(model_path) # loading scripted model
model.eval()
with torch.no_grad():
test_datapoint, test_target = next(iter(test_loader))
prediction = loaded_pytorch_model(test_datapoint[0].unsqueeze(0).to(device))
actual = test_target[0].item()
predicted = torch.argmax(prediction).item()
print(f"\nPREDICTION RESULT: ACTUAL: {actual!s}, PREDICTED: {predicted!s}")
if __name__ == "__main__":
main()
| Net |
python | getsentry__sentry | src/sentry/grouping/enhancer/actions.py | {
"start": 2462,
"end": 6138
} | class ____(EnhancementAction):
"""
An action which sets either a frame's `contributes` value or its `in_app` value.
May optionally set the value for all frames above or below it in the stacktrace as well.
"""
def __init__(self, key: str, flag: bool, range: str | None) -> None:
self.key = key # The type of change (`app` or `group`)
self.flag = flag # True for `+app/+group` rules, False for `-app/-group` rules
self.range = range # None (apply the action to this frame), "up", or "down"
self.is_classifier = key == "app"
self.sets_contributes = key == "group"
def __str__(self) -> str:
return "{}{}{}".format(
{"up": "^", "down": "v", None: ""}.get(self.range),
"+" if self.flag else "-",
self.key,
)
def _to_config_structure(self, version: int) -> int:
"""
Convert the action into an integer by
- converting the combination of its boolean value (if it's a `+app/+group` rule or a
`-app/-group` rule) and its range (if it applies to this frame, frames above, or
frames below) into a number (see `ACTION_FLAGS`) and then multiplying that number by
2^ACTION_BITSIZE
- converting its type (app or group) into a number (using the index in `ACTIONS`)
- bitwise or-ing those two numbers
"""
return ACTIONS.index(self.key) | (ACTION_FLAGS[self.flag, self.range] << ACTION_BITSIZE)
def _slice_to_range(self, seq: list[Any], idx: int) -> list[Any]:
if self.range is None:
return [seq[idx]]
elif self.range == "down":
return seq[:idx]
elif self.range == "up":
return seq[idx + 1 :]
return []
def _in_app_changed(self, frame: dict[str, Any]) -> bool:
orig_in_app = get_path(frame, "data", "orig_in_app")
if orig_in_app is not None:
if orig_in_app == -1:
orig_in_app = None
return orig_in_app != frame.get("in_app")
else:
return False
def apply_modifications_to_frame(
self,
frames: Sequence[dict[str, Any]],
match_frames: list[MatchFrame],
idx: int,
rule: Any | None = None,
) -> None:
# Change a frame or many to be in_app
if self.key == "app":
for match_frame in self._slice_to_range(match_frames, idx):
match_frame["in_app"] = self.flag
def update_frame_components_contributions(
self,
components: list[BaseGroupingComponent],
frames: list[dict[str, Any]],
idx: int,
rule: EnhancementRule | None = None,
) -> None:
rule_hint = "stack trace rule"
if rule:
rule_hint = f"{rule_hint} ({rule.text})"
sliced_components = self._slice_to_range(components, idx)
sliced_frames = self._slice_to_range(frames, idx)
for component, frame in zip(sliced_components, sliced_frames):
if self.key == "group" and self.flag != component.contributes:
component.update(
contributes=self.flag,
hint="{} by {}".format(self.flag and "un-ignored" or "ignored", rule_hint),
)
# The in app flag was set by `apply_modifications_to_frame`
# but we want to add a hint if there is none yet.
elif self.key == "app" and self._in_app_changed(frame):
component.update(
hint="marked {} by {}".format(self.flag and "in-app" or "out of app", rule_hint)
)
| FlagAction |
python | pytest-dev__pytest | src/_pytest/capture.py | {
"start": 22194,
"end": 28893
} | class ____:
"""The capture plugin.
Manages that the appropriate capture method is enabled/disabled during
collection and each test phase (setup, call, teardown). After each of
those points, the captured output is obtained and attached to the
collection/runtest report.
There are two levels of capture:
* global: enabled by default and can be suppressed by the ``-s``
option. This is always enabled/disabled during collection and each test
phase.
* fixture: when a test function or one of its fixture depend on the
``capsys`` or ``capfd`` fixtures. In this case special handling is
needed to ensure the fixtures take precedence over the global capture.
"""
def __init__(self, method: _CaptureMethod) -> None:
self._method: Final = method
self._global_capturing: MultiCapture[str] | None = None
self._capture_fixture: CaptureFixture[Any] | None = None
def __repr__(self) -> str:
return (
f"<CaptureManager _method={self._method!r} _global_capturing={self._global_capturing!r} "
f"_capture_fixture={self._capture_fixture!r}>"
)
def is_capturing(self) -> str | bool:
if self.is_globally_capturing():
return "global"
if self._capture_fixture:
return f"fixture {self._capture_fixture.request.fixturename}"
return False
# Global capturing control
def is_globally_capturing(self) -> bool:
return self._method != "no"
def start_global_capturing(self) -> None:
assert self._global_capturing is None
self._global_capturing = _get_multicapture(self._method)
self._global_capturing.start_capturing()
def stop_global_capturing(self) -> None:
if self._global_capturing is not None:
self._global_capturing.pop_outerr_to_orig()
self._global_capturing.stop_capturing()
self._global_capturing = None
def resume_global_capture(self) -> None:
# During teardown of the python process, and on rare occasions, capture
# attributes can be `None` while trying to resume global capture.
if self._global_capturing is not None:
self._global_capturing.resume_capturing()
def suspend_global_capture(self, in_: bool = False) -> None:
if self._global_capturing is not None:
self._global_capturing.suspend_capturing(in_=in_)
def suspend(self, in_: bool = False) -> None:
# Need to undo local capsys-et-al if it exists before disabling global capture.
self.suspend_fixture()
self.suspend_global_capture(in_)
def resume(self) -> None:
self.resume_global_capture()
self.resume_fixture()
def read_global_capture(self) -> CaptureResult[str]:
assert self._global_capturing is not None
return self._global_capturing.readouterr()
# Fixture Control
def set_fixture(self, capture_fixture: CaptureFixture[Any]) -> None:
if self._capture_fixture:
current_fixture = self._capture_fixture.request.fixturename
requested_fixture = capture_fixture.request.fixturename
capture_fixture.request.raiseerror(
f"cannot use {requested_fixture} and {current_fixture} at the same time"
)
self._capture_fixture = capture_fixture
def unset_fixture(self) -> None:
self._capture_fixture = None
def activate_fixture(self) -> None:
"""If the current item is using ``capsys`` or ``capfd``, activate
them so they take precedence over the global capture."""
if self._capture_fixture:
self._capture_fixture._start()
def deactivate_fixture(self) -> None:
"""Deactivate the ``capsys`` or ``capfd`` fixture of this item, if any."""
if self._capture_fixture:
self._capture_fixture.close()
def suspend_fixture(self) -> None:
if self._capture_fixture:
self._capture_fixture._suspend()
def resume_fixture(self) -> None:
if self._capture_fixture:
self._capture_fixture._resume()
# Helper context managers
@contextlib.contextmanager
def global_and_fixture_disabled(self) -> Generator[None]:
"""Context manager to temporarily disable global and current fixture capturing."""
do_fixture = self._capture_fixture and self._capture_fixture._is_started()
if do_fixture:
self.suspend_fixture()
do_global = self._global_capturing and self._global_capturing.is_started()
if do_global:
self.suspend_global_capture()
try:
yield
finally:
if do_global:
self.resume_global_capture()
if do_fixture:
self.resume_fixture()
@contextlib.contextmanager
def item_capture(self, when: str, item: Item) -> Generator[None]:
self.resume_global_capture()
self.activate_fixture()
try:
yield
finally:
self.deactivate_fixture()
self.suspend_global_capture(in_=False)
out, err = self.read_global_capture()
item.add_report_section(when, "stdout", out)
item.add_report_section(when, "stderr", err)
# Hooks
@hookimpl(wrapper=True)
def pytest_make_collect_report(
self, collector: Collector
) -> Generator[None, CollectReport, CollectReport]:
if isinstance(collector, File):
self.resume_global_capture()
try:
rep = yield
finally:
self.suspend_global_capture()
out, err = self.read_global_capture()
if out:
rep.sections.append(("Captured stdout", out))
if err:
rep.sections.append(("Captured stderr", err))
else:
rep = yield
return rep
@hookimpl(wrapper=True)
def pytest_runtest_setup(self, item: Item) -> Generator[None]:
with self.item_capture("setup", item):
return (yield)
@hookimpl(wrapper=True)
def pytest_runtest_call(self, item: Item) -> Generator[None]:
with self.item_capture("call", item):
return (yield)
@hookimpl(wrapper=True)
def pytest_runtest_teardown(self, item: Item) -> Generator[None]:
with self.item_capture("teardown", item):
return (yield)
@hookimpl(tryfirst=True)
def pytest_keyboard_interrupt(self) -> None:
self.stop_global_capturing()
@hookimpl(tryfirst=True)
def pytest_internalerror(self) -> None:
self.stop_global_capturing()
| CaptureManager |
python | doocs__leetcode | solution/2300-2399/2375.Construct Smallest Number From DI String/Solution.py | {
"start": 0,
"end": 786
} | class ____:
def smallestNumber(self, pattern: str) -> str:
def dfs(u):
nonlocal ans
if ans:
return
if u == len(pattern) + 1:
ans = ''.join(t)
return
for i in range(1, 10):
if not vis[i]:
if u and pattern[u - 1] == 'I' and int(t[-1]) >= i:
continue
if u and pattern[u - 1] == 'D' and int(t[-1]) <= i:
continue
vis[i] = True
t.append(str(i))
dfs(u + 1)
vis[i] = False
t.pop()
vis = [False] * 10
t = []
ans = None
dfs(0)
return ans
| Solution |
python | sympy__sympy | sympy/assumptions/predicates/sets.py | {
"start": 5201,
"end": 6014
} | class ____(Predicate):
"""
Hermitian predicate.
Explanation
===========
``ask(Q.hermitian(x))`` is true iff ``x`` belongs to the set of
Hermitian operators.
Examples
========
>>> from sympy import Q, ask, Matrix, I, Symbol
>>> ask(Q.hermitian(2))
True
>>> ask(Q.hermitian(I))
False
>>> A = Matrix([[1, I], [-I, 1]])
>>> ask(Q.hermitian(A))
True
>>> x = Symbol('x', real=True)
>>> ask(Q.hermitian(x))
True
References
==========
.. [1] https://mathworld.wolfram.com/HermitianOperator.html
"""
name = 'hermitian'
handler = Dispatcher(
"HermitianHandler",
doc=("Handler for Q.hermitian.\n\n"
"Test that an expression belongs to the field of Hermitian operators.")
)
| HermitianPredicate |
python | readthedocs__readthedocs.org | readthedocs/embed/v3/tests/test_access.py | {
"start": 4242,
"end": 4568
} | class ____(TestEmbedAPIV3Access):
def get(self, *args, **kwargs):
return self.client.get(*args, HTTP_HOST="docs.readthedocs.io", **kwargs)
def test_get_content_private_version_logged_in_user(self):
"""This test is skipped, since the proxied API on .org doesn't log in users."""
| TestProxiedEmbedAPIV3Access |
python | cython__cython | Cython/Debugger/libpython.py | {
"start": 5207,
"end": 5749
} | class ____:
'''Similar to io.StringIO, but can truncate the output by raising a
StringTruncated exception'''
def __init__(self, maxlen=None):
self._val = ''
self.maxlen = maxlen
def write(self, data):
if self.maxlen:
if len(data) + len(self._val) > self.maxlen:
# Truncation:
self._val += data[0:self.maxlen - len(self._val)]
raise StringTruncated()
self._val += data
def getvalue(self):
return self._val
| TruncatedStringIO |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_internal/index/sources.py | {
"start": 1354,
"end": 2955
} | class ____:
"""Scans directory and caches results"""
def __init__(self, path: str) -> None:
self._path = path
self._page_candidates: List[str] = []
self._project_name_to_urls: Dict[str, List[str]] = defaultdict(list)
self._scanned_directory = False
def _scan_directory(self) -> None:
"""Scans directory once and populates both page_candidates
and project_name_to_urls at the same time
"""
for entry in os.scandir(self._path):
url = path_to_url(entry.path)
if _is_html_file(url):
self._page_candidates.append(url)
continue
# File must have a valid wheel or sdist name,
# otherwise not worth considering as a package
try:
project_filename = parse_wheel_filename(entry.name)[0]
except (InvalidWheelFilename, InvalidVersion):
try:
project_filename = parse_sdist_filename(entry.name)[0]
except (InvalidSdistFilename, InvalidVersion):
continue
self._project_name_to_urls[project_filename].append(url)
self._scanned_directory = True
@property
def page_candidates(self) -> List[str]:
if not self._scanned_directory:
self._scan_directory()
return self._page_candidates
@property
def project_name_to_urls(self) -> Dict[str, List[str]]:
if not self._scanned_directory:
self._scan_directory()
return self._project_name_to_urls
| _FlatDirectoryToUrls |
python | Farama-Foundation__Gymnasium | gymnasium/envs/box2d/lunar_lander.py | {
"start": 33295,
"end": 33876
} | class ____:
def __init__(self):
raise error.Error(
"Error initializing LunarLanderContinuous Environment.\n"
"Currently, we do not support initializing this mode of environment by calling the class directly.\n"
"To use this environment, instead create it by specifying the continuous keyword in gym.make, i.e.\n"
'gym.make("LunarLander-v3", continuous=True)'
)
if __name__ == "__main__":
env = gym.make("LunarLander-v3", render_mode="rgb_array")
demo_heuristic_lander(env, render=True)
| LunarLanderContinuous |
python | allegroai__clearml | clearml/backend_api/services/v2_20/models.py | {
"start": 120080,
"end": 124808
} | class ____(Response):
"""
Response of models.publish_many endpoint.
:param succeeded:
:type succeeded: Sequence[dict]
:param failed:
:type failed: Sequence[dict]
"""
_service = "models"
_action = "publish_many"
_version = "2.20"
_schema = {
"definitions": {},
"properties": {
"failed": {
"items": {
"properties": {
"error": {
"description": "Error info",
"properties": {
"codes": {
"items": {"type": "integer"},
"type": "array",
},
"data": {
"additionalProperties": True,
"type": "object",
},
"msg": {"type": "string"},
},
"type": "object",
},
"id": {
"description": "ID of the failed entity",
"type": "string",
},
},
"type": "object",
},
"type": ["array", "null"],
},
"succeeded": {
"items": {
"properties": {
"id": {
"description": "ID of the succeeded entity",
"type": "string",
},
"published_task": {
"description": "Result of publishing of the model's associated task (if exists). Returned only if the task was published successfully as part of the model publishing.",
"properties": {
"data": {
"description": "Data returned from the task publishing operation.",
"properties": {
"fields": {
"additionalProperties": True,
"description": "Updated fields names and values",
"type": "object",
},
"updated": {
"description": "Number of tasks updated (0 or 1)",
"enum": [0, 1],
"type": "integer",
},
},
"type": "object",
},
"id": {"description": "Task id", "type": "string"},
},
"type": "object",
},
"updated": {
"description": "Indicates whether the model was updated",
"type": "boolean",
},
},
"type": "object",
},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(
self, succeeded: Optional[List[dict]] = None, failed: Optional[List[dict]] = None, **kwargs: Any
) -> None:
super(PublishManyResponse, self).__init__(**kwargs)
self.succeeded = succeeded
self.failed = failed
@schema_property("succeeded")
def succeeded(self) -> Optional[List[dict]]:
return self._property_succeeded
@succeeded.setter
def succeeded(self, value: Optional[List[dict]]) -> None:
if value is None:
self._property_succeeded = None
return
self.assert_isinstance(value, "succeeded", (list, tuple))
self.assert_isinstance(value, "succeeded", (dict,), is_array=True)
self._property_succeeded = value
@schema_property("failed")
def failed(self) -> Optional[List[dict]]:
return self._property_failed
@failed.setter
def failed(self, value: Optional[List[dict]]) -> None:
if value is None:
self._property_failed = None
return
self.assert_isinstance(value, "failed", (list, tuple))
self.assert_isinstance(value, "failed", (dict,), is_array=True)
self._property_failed = value
| PublishManyResponse |
python | Delgan__loguru | loguru/_colorizer.py | {
"start": 1912,
"end": 1987
} | class ____:
TEXT = 1
ANSI = 2
LEVEL = 3
CLOSING = 4
| TokenType |
python | tornadoweb__tornado | maint/scripts/custom_fixers/fix_future_imports.py | {
"start": 380,
"end": 2175
} | class ____(fixer_base.BaseFix):
BM_compatible = True
PATTERN = """import_from< 'from' module_name="__future__" 'import' any >"""
def start_tree(self, tree, filename):
self.found_future_import = False
def new_future_import(self, old):
new = FromImport("__future__",
[Name("absolute_import", prefix=" "), Comma(),
Name("division", prefix=" "), Comma(),
Name("print_function", prefix=" ")])
if old is not None:
new.prefix = old.prefix
return new
def transform(self, node, results):
self.found_future_import = True
return self.new_future_import(node)
def finish_tree(self, tree, filename):
if self.found_future_import:
return
if not isinstance(tree, pytree.Node):
# Empty files (usually __init__.py) show up as a single Leaf
# instead of a Node, so leave them alone
return
first_stmt = tree.children[0]
if is_docstring(first_stmt):
# Skip a line and add the import after the docstring
tree.insert_child(1, Newline())
pos = 2
elif first_stmt.prefix:
# No docstring, but an initial comment (perhaps a #! line).
# Transfer the initial comment to a new blank line.
newline = Newline()
newline.prefix = first_stmt.prefix
first_stmt.prefix = ""
tree.insert_child(0, newline)
pos = 1
else:
# No comments or docstring, just insert at the start
pos = 0
tree.insert_child(pos, self.new_future_import(None))
tree.insert_child(pos + 1, Newline()) # terminates the import stmt
| FixFutureImports |
python | apache__airflow | helm-tests/tests/helm_tests/dagprocessor/test_labels_service_account.py | {
"start": 900,
"end": 3986
} | class ____:
"""Tests dag-processor service account labels."""
AIRFLOW_VERSION = "3.0.0"
TEMPLATE_FILE = "templates/dag-processor/dag-processor-serviceaccount.yaml"
def test_should_add_global_labels(self):
"""Test adding only .Values.labels."""
docs = render_chart(
values={
"airflowVersion": self.AIRFLOW_VERSION,
"labels": {"test_global_label": "test_global_label_value"},
},
show_only=[self.TEMPLATE_FILE],
)
assert "test_global_label" in jmespath.search("metadata.labels", docs[0])
assert jmespath.search("metadata.labels", docs[0])["test_global_label"] == "test_global_label_value"
def test_should_add_component_specific_labels(self):
"""Test adding only .Values.dagProcessor.labels."""
docs = render_chart(
values={
"airflowVersion": self.AIRFLOW_VERSION,
"dagProcessor": {
"labels": {"test_component_label": "test_component_label_value"},
},
},
show_only=[self.TEMPLATE_FILE],
)
assert "test_component_label" in jmespath.search("metadata.labels", docs[0])
assert (
jmespath.search("metadata.labels", docs[0])["test_component_label"]
== "test_component_label_value"
)
def test_should_merge_global_and_component_specific_labels(self):
"""Test adding both .Values.labels and .Values.dagProcessor.labels."""
docs = render_chart(
values={
"airflowVersion": self.AIRFLOW_VERSION,
"labels": {"test_global_label": "test_global_label_value"},
"dagProcessor": {
"labels": {"test_component_label": "test_component_label_value"},
},
},
show_only=[self.TEMPLATE_FILE],
)
assert "test_global_label" in jmespath.search("metadata.labels", docs[0])
assert jmespath.search("metadata.labels", docs[0])["test_global_label"] == "test_global_label_value"
assert "test_component_label" in jmespath.search("metadata.labels", docs[0])
assert (
jmespath.search("metadata.labels", docs[0])["test_component_label"]
== "test_component_label_value"
)
def test_component_specific_labels_should_override_global_labels(self):
"""Test that component-specific labels take precedence over global labels with the same key."""
docs = render_chart(
values={
"airflowVersion": self.AIRFLOW_VERSION,
"labels": {"common_label": "global_value"},
"dagProcessor": {
"labels": {"common_label": "component_value"},
},
},
show_only=[self.TEMPLATE_FILE],
)
assert "common_label" in jmespath.search("metadata.labels", docs[0])
assert jmespath.search("metadata.labels", docs[0])["common_label"] == "component_value"
| TestDagProcessorServiceAccount |
python | apache__airflow | task-sdk/tests/task_sdk/execution_time/test_context.py | {
"start": 15947,
"end": 21072
} | class ____:
@pytest.fixture(autouse=True)
def clear_cache(self):
_AssetRefResolutionMixin._asset_ref_cache = {}
yield
_AssetRefResolutionMixin._asset_ref_cache = {}
@pytest.fixture
def event_data(self):
return [
{
"asset": {
"name": "1",
"uri": "1",
"extra": {},
},
"extra": {},
"source_task_id": "t1",
"source_dag_id": "d1",
"source_run_id": "r1",
"source_map_index": -1,
"source_aliases": [],
"timestamp": "2025-01-01T00:00:12Z",
},
{
"asset": {
"name": "1",
"uri": "1",
"extra": {},
},
"extra": {},
"source_task_id": "t2",
"source_dag_id": "d1",
"source_run_id": "r1",
"source_map_index": -1,
"source_aliases": [
{"name": "a"},
{"name": "b"},
],
"timestamp": "2025-01-01T00:05:43Z",
},
{
"asset": {
"name": "2",
"uri": "2",
"extra": {},
},
"extra": {},
"source_task_id": "t2",
"source_dag_id": "d1",
"source_run_id": "r1",
"source_map_index": -1,
"source_aliases": [],
"timestamp": "2025-01-01T00:06:07Z",
},
]
@pytest.fixture
def accessor(self, event_data):
return TriggeringAssetEventsAccessor.build(
AssetEventDagRunReferenceResult.model_validate(d) for d in event_data
)
@pytest.mark.parametrize(
("key", "result_indexes"),
[
(Asset("1"), [0, 1]),
(Asset("2"), [2]),
(AssetAlias("a"), [1]),
(AssetAlias("b"), [1]),
],
)
def test_getitem(self, event_data, accessor, key, result_indexes):
expected = [AssetEventDagRunReferenceResult.model_validate(event_data[i]) for i in result_indexes]
assert accessor[key] == expected
@pytest.mark.parametrize(
("name", "resolved_asset", "result_indexes"),
[
("1", AssetResult(name="1", uri="1", group="whatever"), [0, 1]),
("2", AssetResult(name="2", uri="2", group="whatever"), [2]),
],
)
def test_getitem_name_ref(
self,
mock_supervisor_comms,
event_data,
accessor,
name,
resolved_asset,
result_indexes,
):
mock_supervisor_comms.send.return_value = resolved_asset
expected = [AssetEventDagRunReferenceResult.model_validate(event_data[i]) for i in result_indexes]
assert accessor[Asset.ref(name=name)] == expected
mock_supervisor_comms.send.assert_called_once_with(GetAssetByName(name=name, type="GetAssetByName"))
assert _AssetRefResolutionMixin._asset_ref_cache
@pytest.mark.parametrize(
("uri", "resolved_asset", "result_indexes"),
[
("1", AssetResult(name="1", uri="1", group="whatever"), [0, 1]),
("2", AssetResult(name="2", uri="2", group="whatever"), [2]),
],
)
def test_getitem_uri_ref(
self,
mock_supervisor_comms,
event_data,
accessor,
uri,
resolved_asset,
result_indexes,
):
mock_supervisor_comms.send.return_value = resolved_asset
expected = [AssetEventDagRunReferenceResult.model_validate(event_data[i]) for i in result_indexes]
assert accessor[Asset.ref(uri=uri)] == expected
mock_supervisor_comms.send.assert_called_once_with(GetAssetByUri(uri=uri))
assert _AssetRefResolutionMixin._asset_ref_cache
def test_source_task_instance_xcom_pull(self, mock_supervisor_comms, accessor):
events = accessor[Asset("2")]
assert len(events) == 1
source = events[0].source_task_instance
assert source == AssetEventSourceTaskInstance(dag_id="d1", task_id="t2", run_id="r1", map_index=-1)
mock_supervisor_comms.reset_mock()
mock_supervisor_comms.send.side_effect = [
XComResult(key=BaseXCom.XCOM_RETURN_KEY, value="__example_xcom_value__"),
]
assert source.xcom_pull() == "__example_xcom_value__"
mock_supervisor_comms.send.assert_called_once_with(
msg=GetXCom(
key=BaseXCom.XCOM_RETURN_KEY,
dag_id="d1",
run_id="r1",
task_id="t2",
map_index=-1,
),
)
TEST_ASSET = Asset(name="test_uri", uri="test://test")
TEST_ASSET_ALIAS = AssetAlias(name="name")
TEST_ASSET_REFS = [Asset.ref(name="test_uri"), Asset.ref(uri="test://test/")]
TEST_INLETS = [TEST_ASSET, TEST_ASSET_ALIAS] + TEST_ASSET_REFS
| TestTriggeringAssetEventsAccessor |
python | Textualize__textual | src/textual/events.py | {
"start": 1052,
"end": 1508
} | class ____(Event, bubble=False, verbose=True):
"""Sent by Textual to invoke a callback
(see [call_next][textual.message_pump.MessagePump.call_next] and
[call_later][textual.message_pump.MessagePump.call_later]).
"""
def __init__(self, callback: CallbackType) -> None:
self.callback = callback
super().__init__()
def __rich_repr__(self) -> rich.repr.Result:
yield "callback", self.callback
@dataclass
| Callback |
python | pytorch__pytorch | test/distributed/checkpoint/test_hf_safetensor_e2e.py | {
"start": 893,
"end": 1131
} | class ____(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.linear_1 = torch.nn.Linear(5, 5)
self.linear_2 = torch.nn.Linear(5, 1)
self.emb = torch.nn.EmbeddingBag(5, 10)
| MyTestModule |
python | donnemartin__interactive-coding-challenges | bit_manipulation/bit/test_bit.py | {
"start": 18,
"end": 1208
} | class ____(unittest.TestCase):
def test_bit(self):
number = int('10001110', base=2)
bit = Bit(number)
self.assertEqual(bit.get_bit(index=3), True)
expected = int('10011110', base=2)
self.assertEqual(bit.set_bit(index=4), expected)
bit = Bit(number)
expected = int('10000110', base=2)
self.assertEqual(bit.clear_bit(index=3), expected)
bit = Bit(number)
expected = int('00000110', base=2)
self.assertEqual(bit.clear_bits_msb_to_index(index=3), expected)
bit = Bit(number)
expected = int('10000000', base=2)
self.assertEqual(bit.clear_bits_index_to_lsb(index=3), expected)
bit = Bit(number)
self.assertEqual(bit.update_bit(index=3, value=1), number)
bit = Bit(number)
expected = int('10000110', base=2)
self.assertEqual(bit.update_bit(index=3, value=0), expected)
bit = Bit(number)
expected = int('10001111', base=2)
self.assertEqual(bit.update_bit(index=0, value=1), expected)
print('Success: test_bit')
def main():
test = TestBit()
test.test_bit()
if __name__ == '__main__':
main()
| TestBit |
python | kubernetes-client__python | kubernetes/client/models/v1_ingress_backend.py | {
"start": 383,
"end": 4165
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'resource': 'V1TypedLocalObjectReference',
'service': 'V1IngressServiceBackend'
}
attribute_map = {
'resource': 'resource',
'service': 'service'
}
def __init__(self, resource=None, service=None, local_vars_configuration=None): # noqa: E501
"""V1IngressBackend - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._resource = None
self._service = None
self.discriminator = None
if resource is not None:
self.resource = resource
if service is not None:
self.service = service
@property
def resource(self):
"""Gets the resource of this V1IngressBackend. # noqa: E501
:return: The resource of this V1IngressBackend. # noqa: E501
:rtype: V1TypedLocalObjectReference
"""
return self._resource
@resource.setter
def resource(self, resource):
"""Sets the resource of this V1IngressBackend.
:param resource: The resource of this V1IngressBackend. # noqa: E501
:type: V1TypedLocalObjectReference
"""
self._resource = resource
@property
def service(self):
"""Gets the service of this V1IngressBackend. # noqa: E501
:return: The service of this V1IngressBackend. # noqa: E501
:rtype: V1IngressServiceBackend
"""
return self._service
@service.setter
def service(self, service):
"""Sets the service of this V1IngressBackend.
:param service: The service of this V1IngressBackend. # noqa: E501
:type: V1IngressServiceBackend
"""
self._service = service
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1IngressBackend):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1IngressBackend):
return True
return self.to_dict() != other.to_dict()
| V1IngressBackend |
python | pytorch__pytorch | torch/_inductor/runtime/caching/context.py | {
"start": 7010,
"end": 7156
} | class ____(TypedDict):
inductor_configs: bool
torch_determinism_configs: bool
cuda_matmul_precision_configs: bool
| SelectedRuntimeContext |
python | run-llama__llama_index | llama-index-core/llama_index/core/evaluation/retrieval/metrics.py | {
"start": 7920,
"end": 9723
} | class ____(BaseRetrievalMetric):
"""
Recall metric.
Attributes:
metric_name (str): The name of the metric.
"""
metric_name: ClassVar[str] = "recall"
def compute(
self,
query: Optional[str] = None,
expected_ids: Optional[List[str]] = None,
retrieved_ids: Optional[List[str]] = None,
expected_texts: Optional[List[str]] = None,
retrieved_texts: Optional[List[str]] = None,
**kwargs: Any,
) -> RetrievalMetricResult:
"""
Compute recall based on the provided inputs and selected method.
Parameters
----------
query (Optional[str]): The query string (not used in the current implementation).
expected_ids (Optional[List[str]]): Expected document IDs.
retrieved_ids (Optional[List[str]]): Retrieved document IDs.
expected_texts (Optional[List[str]]): Expected texts (not used in the current implementation).
retrieved_texts (Optional[List[str]]): Retrieved texts (not used in the current implementation).
Raises
------
ValueError: If the necessary IDs are not provided.
Returns
-------
RetrievalMetricResult: The result with the computed recall score.
"""
# Checking for the required arguments
if (
retrieved_ids is None
or expected_ids is None
or not retrieved_ids
or not expected_ids
):
raise ValueError("Retrieved ids and expected ids must be provided")
retrieved_set = set(retrieved_ids)
expected_set = set(expected_ids)
recall = len(retrieved_set & expected_set) / len(expected_set)
return RetrievalMetricResult(score=recall)
| Recall |
python | kamyu104__LeetCode-Solutions | Python/linked-list-cycle-ii.py | {
"start": 247,
"end": 677
} | class ____(object):
# @param head, a ListNode
# @return a list node
def detectCycle(self, head):
fast, slow = head, head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
if fast is slow:
fast = head
while fast is not slow:
fast, slow = fast.next, slow.next
return fast
return None
| Solution |
python | getsentry__sentry | src/sentry/digests/backends/base.py | {
"start": 805,
"end": 10600
} | class ____(Service):
"""
A digest backend coordinates the addition of records to timelines, as well
as scheduling their digestion (processing.) This allows for summarizations
of activity that was recorded as having occurred during a window of time.
A timeline is the central abstraction for digests. A timeline is a
reverse-chronological set of records. Timelines are identified by a unique
key. Records within a timeline are also identified by a key that is unique
with respect to the timeline they are a part of.
A timeline can be in one of two states: "waiting" or "ready".
When the first record is added to a timeline, the timeline transitions to
the "ready" state, and the digest is immediately available to be digested
and delivered. (This immediate state change to "ready" allows notifications
to be delivered with lower latency.)
After delivery, the digest transitions to the "waiting" state for the
duration of the delay interval. If more items are added to the digest
during this waiting period, the schedule is extended incrementally (up to
the value defined by the maximum delay option) to allow grouping the more
items into a single notification.
When the "waiting" period is over, the timeline transitions back to the
"ready" state, which causes the timeline to be again digested and
delivered. After the timeline is digested, it transitions back to the
"waiting" state if it contained records. If the timeline did not contain
any records when it was digested, it can be deleted (although deletion may
be preempted by a new record being added to the timeline, requiring it to
be transitioned to "waiting" instead.)
"""
__all__ = ("add", "delete", "digest", "enabled", "maintenance", "schedule", "validate")
def __init__(self, **options: Any) -> None:
# The ``minimum_delay`` option defines the default minimum amount of
# time (in seconds) to wait between scheduling digests for delivery
# after the initial scheduling.
self.minimum_delay = options.pop("minimum_delay", 60 * 5)
# The ``maximum_delay`` option defines the default maximum amount of
# time (in seconds) to wait between scheduling digests for delivery.
self.maximum_delay = options.pop("maximum_delay", 60 * 30)
# The ``increment_delay`` option defines how long each observation of
# an event should delay scheduling (up until the ``maximum_delay``
# after the last time a digest was processed.)
self.increment_delay = options.pop("increment_delay", 30)
# The ``codec`` option provides the strategy for encoding and decoding
# records in the timeline.
self.codec = load(options.pop("codec", DEFAULT_CODEC))
# The ``capacity`` option defines the maximum number of items that
# should be contained within a timeline. (Whether this is a hard or
# soft limit is backend dependent -- see the ``truncation_chance`` option.)
self.capacity = options.pop("capacity", None)
if self.capacity is not None and self.capacity < 1:
raise ValueError("Timeline capacity must be at least 1 if used.")
# The ``truncation_chance`` option defines the probability that an
# ``add`` operation will trigger a truncation of the timeline to keep
# it's size close to the defined capacity. A value of 1 will cause the
# timeline to be truncated on every ``add`` operation (effectively
# making it a hard limit), while a lower probability will increase the
# chance of the timeline growing past it's intended capacity, but
# increases the performance of ``add`` operations (by avoiding
# truncation, which is a potentially expensive operation, especially on
# large data sets.)
if self.capacity:
self.truncation_chance = options.pop("truncation_chance", 1.0 / self.capacity)
else:
if options.get("truncation_chance") is not None:
raise TypeError(
'No timeline capacity has been set, "truncation_chance" must be None.'
)
else:
self.truncation_chance = 0.0
def enabled(self, project: Project) -> bool:
"""
Check if a project has digests enabled.
"""
return True
def add(
self,
key: str,
record: Record,
increment_delay: int | None = None,
maximum_delay: int | None = None,
timestamp: float | None = None,
) -> bool:
"""
Add a record to a timeline.
Adding a record to a timeline also causes it to be added to the
schedule, if it is not already present.
If another record exists in the timeline with the same record key, it
will be overwritten.
The return value this function indicates whether or not the timeline is
ready for immediate digestion.
"""
raise NotImplementedError
def digest(self, key: str, minimum_delay: int | None = None) -> Any:
"""
Extract records from a timeline for processing.
This method acts as a context manager. The target of the ``as`` clause
is an iterator contains all of the records contained within the digest.
If the context manager successfully exits, all records that were part
of the digest are removed from the timeline and the timeline is placed
back in the "waiting" state. If an exception is raised during the
execution of the context manager, all records are preserved and no
state change occurs so that the next invocation will contain all
records that the were included previously, as well as any records that
were added in between invocations. (This means that the caller must
either retry the digest operation until it succeeds, or wait for the
operation to be rescheduled as part of the maintenance process for the
items to be processed.)
Typically, the block that is surrounded by context manager includes all
of the processing logic necessary to summarize the timeline contents
(since this process is generally has no side effects), while any
irrevocable action -- such as sending an email -- should occur after
the context manager has exited, to ensure that action is performed at
most once.
For example::
with timelines.digest('project:1') as records:
message = build_digest_email(records)
message.send_async()
"""
raise NotImplementedError
def schedule(self, deadline: float, timestamp: float | None = None) -> Iterable[ScheduleEntry]:
"""
Identify timelines that are ready for processing.
This method moves all timelines that are ready to be digested from the
waiting state to the ready state if their schedule time is prior to the
deadline. This method returns an iterator of schedule entries that were
moved.
"""
raise NotImplementedError
def maintenance(self, deadline: float, timestamp: float | None = None) -> None:
"""
Identify timelines that appear to be stuck in the ready state.
This method moves all timelines that are in the ready state back to the
waiting state if their schedule time is prior to the deadline. (This
does not reschedule any tasks directly, and should generally be
performed as part of the scheduler task, before the ``schedule``
call.)
This is designed to handle the situation where task execution is
managed separately from scheduling.
A digest task may not be able to be successfully retried after a failure
(e.g. if the process executing the task can no longer communicate with
the messaging broker) which can result in a task remaining in the ready
state without an execution plan.
This may cause issues when asynchronously processing timelines and
there is a severe backlog of timelines to be digested. Timelines in the
"ready" state that were scheduled for execution prior to the deadline
may still have outstanding tasks associated with them -- remember that
without the ability to interrogate the queue, we are unable to identify
if these tasks have finished but were unable to be removed from the
schedule, failed outright, or are still pending. As part of
maintenance, those timelines are moved back to the "waiting" state for
rescheduling, and if a pending task for a timeline that was previously
in the "ready" state but is now back in the "waiting" state actually
executes, it will fail to be executed. The timeline will later be moved
back to the "ready" state and rescheduled -- so it's contents will
eventually be processed -- but this may be significantly delayed from
the originally scheduled time. Both the queue backlog as well as the
frequency of the digest task raising an exception when a timeline is in
an invalid state should be monitored. If these exceptions happen
frequently -- especially during periods of abnormal queue growth -- the
frequency of maintenance tasks should be decreased, or the deadline
should be pushed further towards the past (execution grace period
increased) or both.
"""
raise NotImplementedError
def delete(self, key: str) -> None:
"""
Delete a timeline and all of it's contents from the database.
"""
raise NotImplementedError
| Backend |
python | pydantic__pydantic | tests/mypy/outputs/mypy-plugin-strict_ini/plugin_fail.py | {
"start": 3924,
"end": 4797
} | class ____(BaseModel):
undefined: Undefined # noqa F821
# MYPY: error: Name "Undefined" is not defined [name-defined]
UndefinedAnnotationModel()
# MYPY: error: Missing named argument "undefined" for "UndefinedAnnotationModel" [call-arg]
Model.model_construct(x=1)
# MYPY: error: Missing named argument "y" for "model_construct" of "Model" [call-arg]
Model.model_construct(_fields_set={'x'}, x=1, y='2')
Model.model_construct(x='1', y='2')
# MYPY: error: Argument "x" to "model_construct" of "Model" has incompatible type "str"; expected "int" [arg-type]
# Strict mode fails
inheriting = InheritingModel(x='1', y='1')
# MYPY: error: Argument "x" to "InheritingModel" has incompatible type "str"; expected "int" [arg-type]
Model(x='1', y='2')
# MYPY: error: Argument "x" to "Model" has incompatible type "str"; expected "int" [arg-type]
| UndefinedAnnotationModel |
python | pandas-dev__pandas | pandas/core/arrays/_mixins.py | {
"start": 2138,
"end": 17063
} | class ____(NDArrayBacked, ExtensionArray):
"""
ExtensionArray that is backed by a single NumPy ndarray.
"""
_ndarray: np.ndarray
# scalar used to denote NA value inside our self._ndarray, e.g. -1
# for Categorical, iNaT for Period. Outside of object dtype,
# self.isna() should be exactly locations in self._ndarray with
# _internal_fill_value.
_internal_fill_value: Any
def _box_func(self, x):
"""
Wrap numpy type in our dtype.type if necessary.
"""
return x
def _validate_scalar(self, value):
# used by NDArrayBackedExtensionIndex.insert
raise AbstractMethodError(self)
# ------------------------------------------------------------------------
@overload
def view(self) -> Self: ...
@overload
def view(self, dtype: Dtype | None = ...) -> ArrayLike: ...
def view(self, dtype: Dtype | None = None) -> ArrayLike:
# We handle datetime64, datetime64tz, timedelta64, and period
# dtypes here. Everything else we pass through to the underlying
# ndarray.
if dtype is None or dtype is self.dtype:
return self._from_backing_data(self._ndarray)
if isinstance(dtype, type):
# we sometimes pass non-dtype objects, e.g np.ndarray;
# pass those through to the underlying ndarray
return self._ndarray.view(dtype)
dtype = pandas_dtype(dtype)
arr = self._ndarray
if isinstance(dtype, PeriodDtype):
cls = dtype.construct_array_type()
return cls(arr.view("i8"), dtype=dtype)
elif isinstance(dtype, DatetimeTZDtype):
dt_cls = dtype.construct_array_type()
dt64_values = arr.view(f"M8[{dtype.unit}]")
return dt_cls._simple_new(dt64_values, dtype=dtype)
elif lib.is_np_dtype(dtype, "M") and is_supported_dtype(dtype):
from pandas.core.arrays import DatetimeArray
dt64_values = arr.view(dtype)
return DatetimeArray._simple_new(dt64_values, dtype=dtype)
elif lib.is_np_dtype(dtype, "m") and is_supported_dtype(dtype):
from pandas.core.arrays import TimedeltaArray
td64_values = arr.view(dtype)
return TimedeltaArray._simple_new(td64_values, dtype=dtype)
# error: Argument "dtype" to "view" of "ndarray" has incompatible type
# "ExtensionDtype | dtype[Any]"; expected "dtype[Any] | _HasDType[dtype[Any]]"
return arr.view(dtype=dtype) # type: ignore[arg-type]
def take(
self,
indices: TakeIndexer,
*,
allow_fill: bool = False,
fill_value: Any = None,
axis: AxisInt = 0,
) -> Self:
if allow_fill:
fill_value = self._validate_scalar(fill_value)
new_data = take(
self._ndarray,
indices,
allow_fill=allow_fill,
fill_value=fill_value,
axis=axis,
)
return self._from_backing_data(new_data)
# ------------------------------------------------------------------------
def equals(self, other) -> bool:
if type(self) is not type(other):
return False
if self.dtype != other.dtype:
return False
return bool(array_equivalent(self._ndarray, other._ndarray, dtype_equal=True))
@classmethod
def _from_factorized(cls, values, original):
assert values.dtype == original._ndarray.dtype
return original._from_backing_data(values)
def _values_for_argsort(self) -> np.ndarray:
return self._ndarray
def _values_for_factorize(self):
return self._ndarray, self._internal_fill_value
def _hash_pandas_object(
self, *, encoding: str, hash_key: str, categorize: bool
) -> npt.NDArray[np.uint64]:
from pandas.core.util.hashing import hash_array
values = self._ndarray
return hash_array(
values, encoding=encoding, hash_key=hash_key, categorize=categorize
)
# Signature of "argmin" incompatible with supertype "ExtensionArray"
def argmin(self, axis: AxisInt = 0, skipna: bool = True): # type: ignore[override]
# override base class by adding axis keyword
validate_bool_kwarg(skipna, "skipna")
if not skipna and self._hasna:
raise ValueError("Encountered an NA value with skipna=False")
return nargminmax(self, "argmin", axis=axis)
# Signature of "argmax" incompatible with supertype "ExtensionArray"
def argmax(self, axis: AxisInt = 0, skipna: bool = True): # type: ignore[override]
# override base class by adding axis keyword
validate_bool_kwarg(skipna, "skipna")
if not skipna and self._hasna:
raise ValueError("Encountered an NA value with skipna=False")
return nargminmax(self, "argmax", axis=axis)
def unique(self) -> Self:
new_data = unique(self._ndarray)
return self._from_backing_data(new_data)
@classmethod
@doc(ExtensionArray._concat_same_type)
def _concat_same_type(
cls,
to_concat: Sequence[Self],
axis: AxisInt = 0,
) -> Self:
if not lib.dtypes_all_equal([x.dtype for x in to_concat]):
dtypes = {str(x.dtype) for x in to_concat}
raise ValueError("to_concat must have the same dtype", dtypes)
return super()._concat_same_type(to_concat, axis=axis)
@doc(ExtensionArray.searchsorted)
def searchsorted(
self,
value: NumpyValueArrayLike | ExtensionArray,
side: Literal["left", "right"] = "left",
sorter: NumpySorter | None = None,
) -> npt.NDArray[np.intp] | np.intp:
npvalue = self._validate_setitem_value(value)
return self._ndarray.searchsorted(npvalue, side=side, sorter=sorter)
@doc(ExtensionArray.shift)
def shift(self, periods: int = 1, fill_value=None) -> Self:
# NB: shift is always along axis=0
axis = 0
fill_value = self._validate_scalar(fill_value)
new_values = shift(self._ndarray, periods, axis, fill_value)
return self._from_backing_data(new_values)
def __setitem__(self, key, value) -> None:
if self._readonly:
raise ValueError("Cannot modify read-only array")
key = check_array_indexer(self, key)
value = self._validate_setitem_value(value)
self._ndarray[key] = value
def _validate_setitem_value(self, value):
return value
@overload
def __getitem__(self, key: ScalarIndexer) -> Any: ...
@overload
def __getitem__(
self,
key: SequenceIndexer | PositionalIndexerTuple,
) -> Self: ...
def __getitem__(
self,
key: PositionalIndexer2D,
) -> Self | Any:
if lib.is_integer(key):
# fast-path
result = self._ndarray[key]
if self.ndim == 1:
return self._box_func(result)
result = self._from_backing_data(result)
if getitem_returns_view(self, key):
result._readonly = self._readonly
return result
# error: Incompatible types in assignment (expression has type "ExtensionArray",
# variable has type "Union[int, slice, ndarray]")
key = extract_array(key, extract_numpy=True) # type: ignore[assignment]
key = check_array_indexer(self, key)
result = self._ndarray[key]
if lib.is_scalar(result):
return self._box_func(result)
result = self._from_backing_data(result)
if getitem_returns_view(self, key):
result._readonly = self._readonly
return result
def _pad_or_backfill(
self,
*,
method: FillnaOptions,
limit: int | None = None,
limit_area: Literal["inside", "outside"] | None = None,
copy: bool = True,
) -> Self:
mask = self.isna()
if mask.any():
# (for now) when self.ndim == 2, we assume axis=0
func = missing.get_fill_func(method, ndim=self.ndim)
npvalues = self._ndarray.T
if copy:
npvalues = npvalues.copy()
func(npvalues, limit=limit, limit_area=limit_area, mask=mask.T)
npvalues = npvalues.T
if copy:
new_values = self._from_backing_data(npvalues)
else:
new_values = self
else:
if copy:
new_values = self.copy()
else:
new_values = self
return new_values
@doc(ExtensionArray.fillna)
def fillna(self, value, limit: int | None = None, copy: bool = True) -> Self:
mask = self.isna()
if limit is not None and limit < len(self):
# mypy doesn't like that mask can be an EA which need not have `cumsum`
modify = mask.cumsum() > limit # type: ignore[union-attr]
if modify.any():
# Only copy mask if necessary
mask = mask.copy()
mask[modify] = False
# error: Argument 2 to "check_value_size" has incompatible type
# "ExtensionArray"; expected "ndarray"
value = missing.check_value_size(
value,
mask, # type: ignore[arg-type]
len(self),
)
if mask.any():
# fill with value
if copy:
new_values = self.copy()
else:
new_values = self[:]
new_values[mask] = value
else:
# We validate the fill_value even if there is nothing to fill
self._validate_setitem_value(value)
if not copy:
new_values = self[:]
else:
new_values = self.copy()
return new_values
# ------------------------------------------------------------------------
# Reductions
def _wrap_reduction_result(self, axis: AxisInt | None, result) -> Any:
if axis is None or self.ndim == 1:
return self._box_func(result)
return self._from_backing_data(result)
# ------------------------------------------------------------------------
# __array_function__ methods
def _putmask(self, mask: npt.NDArray[np.bool_], value) -> None:
"""
Analogue to np.putmask(self, mask, value)
Parameters
----------
mask : np.ndarray[bool]
value : scalar or listlike
Raises
------
TypeError
If value cannot be cast to self.dtype.
"""
value = self._validate_setitem_value(value)
np.putmask(self._ndarray, mask, value)
def _where(self: Self, mask: npt.NDArray[np.bool_], value) -> Self:
"""
Analogue to np.where(mask, self, value)
Parameters
----------
mask : np.ndarray[bool]
value : scalar or listlike
Raises
------
TypeError
If value cannot be cast to self.dtype.
"""
value = self._validate_setitem_value(value)
res_values = np.where(mask, self._ndarray, value)
if res_values.dtype != self._ndarray.dtype:
raise AssertionError(
# GH#56410
"Something has gone wrong, please report a bug at "
"github.com/pandas-dev/pandas/"
)
return self._from_backing_data(res_values)
# ------------------------------------------------------------------------
# Index compat methods
def insert(self, loc: int, item) -> Self:
"""
Make new ExtensionArray inserting new item at location. Follows
Python list.append semantics for negative values.
Parameters
----------
loc : int
item : object
Returns
-------
type(self)
"""
loc = validate_insert_loc(loc, len(self))
code = self._validate_scalar(item)
new_vals = np.concatenate(
(
self._ndarray[:loc],
np.asarray([code], dtype=self._ndarray.dtype),
self._ndarray[loc:],
)
)
return self._from_backing_data(new_vals)
# ------------------------------------------------------------------------
# Additional array methods
# These are not part of the EA API, but we implement them because
# pandas assumes they're there.
def value_counts(self, dropna: bool = True) -> Series:
"""
Return a Series containing counts of unique values.
Parameters
----------
dropna : bool, default True
Don't include counts of NA values.
Returns
-------
Series
"""
if self.ndim != 1:
raise NotImplementedError
from pandas import (
Index,
Series,
)
if dropna:
# error: Unsupported operand type for ~ ("ExtensionArray")
values = self[~self.isna()]._ndarray # type: ignore[operator]
else:
values = self._ndarray
result = value_counts(values, sort=False, dropna=dropna)
index_arr = self._from_backing_data(np.asarray(result.index._data))
index = Index(index_arr, name=result.index.name)
return Series(result._values, index=index, name=result.name, copy=False)
def _quantile(
self,
qs: npt.NDArray[np.float64],
interpolation: str,
) -> Self:
# TODO: disable for Categorical if not ordered?
mask = np.asarray(self.isna())
arr = self._ndarray
fill_value = self._internal_fill_value
res_values = quantile_with_mask(arr, mask, fill_value, qs, interpolation)
if res_values.dtype == self._ndarray.dtype:
return self._from_backing_data(res_values)
else:
# e.g. test_quantile_empty we are empty integer dtype and res_values
# has floating dtype
# TODO: technically __init__ isn't defined here.
# Should we raise NotImplementedError and handle this on NumpyEA?
return type(self)(res_values) # type: ignore[call-arg]
# ------------------------------------------------------------------------
# numpy-like methods
@classmethod
def _empty(cls, shape: Shape, dtype: ExtensionDtype) -> Self:
"""
Analogous to np.empty(shape, dtype=dtype)
Parameters
----------
shape : tuple[int]
dtype : ExtensionDtype
"""
# The base implementation uses a naive approach to find the dtype
# for the backing ndarray
arr = cls._from_sequence([], dtype=dtype)
backing = np.empty(shape, dtype=arr._ndarray.dtype)
return arr._from_backing_data(backing)
| NDArrayBackedExtensionArray |
python | viewflow__viewflow | tests/json/test_json__time.py | {
"start": 121,
"end": 250
} | class ____(models.Model):
data = models.JSONField()
time_field = jsonstore.TimeField(blank=True, null=False)
| TimeFieldModel |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_index_tricks.py | {
"start": 8902,
"end": 13542
} | class ____(TestCase):
def test_basic(self):
a = mgrid[-1:1:10j]
b = mgrid[-1:1:0.1]
assert_(a.shape == (10,))
assert_(b.shape == (20,))
assert_(a[0] == -1)
assert_almost_equal(a[-1], 1)
assert_(b[0] == -1)
assert_almost_equal(b[1] - b[0], 0.1, 11)
assert_almost_equal(b[-1], b[0] + 19 * 0.1, 11)
assert_almost_equal(a[1] - a[0], 2.0 / 9.0, 11)
@xfail # (reason="retstep not implemented")
def test_linspace_equivalence(self):
y, st = np.linspace(2, 10, retstep=True)
assert_almost_equal(st, 8 / 49.0)
assert_array_almost_equal(y, mgrid[2:10:50j], 13)
def test_nd(self):
c = mgrid[-1:1:10j, -2:2:10j]
d = mgrid[-1:1:0.1, -2:2:0.2]
assert_(c.shape == (2, 10, 10))
assert_(d.shape == (2, 20, 20))
assert_array_equal(c[0][0, :], -np.ones(10, "d"))
assert_array_equal(c[1][:, 0], -2 * np.ones(10, "d"))
assert_array_almost_equal(c[0][-1, :], np.ones(10, "d"), 11)
assert_array_almost_equal(c[1][:, -1], 2 * np.ones(10, "d"), 11)
assert_array_almost_equal(d[0, 1, :] - d[0, 0, :], 0.1 * np.ones(20, "d"), 11)
assert_array_almost_equal(d[1, :, 1] - d[1, :, 0], 0.2 * np.ones(20, "d"), 11)
def test_sparse(self):
grid_full = mgrid[-1:1:10j, -2:2:10j]
grid_sparse = ogrid[-1:1:10j, -2:2:10j]
# sparse grids can be made dense by broadcasting
grid_broadcast = np.broadcast_arrays(*grid_sparse)
for f, b in zip(grid_full, grid_broadcast):
assert_equal(f, b)
@parametrize(
"start, stop, step, expected",
[
(None, 10, 10j, (200, 10)),
(-10, 20, None, (1800, 30)),
],
)
def test_mgrid_size_none_handling(self, start, stop, step, expected):
# regression test None value handling for
# start and step values used by mgrid;
# internally, this aims to cover previously
# unexplored code paths in nd_grid()
grid = mgrid[start:stop:step, start:stop:step]
# need a smaller grid to explore one of the
# untested code paths
grid_small = mgrid[start:stop:step]
assert_equal(grid.size, expected[0])
assert_equal(grid_small.size, expected[1])
@xfail # (reason="mgrid not implemented")
def test_accepts_npfloating(self):
# regression test for #16466
grid64 = mgrid[0.1:0.33:0.1,]
grid32 = mgrid[np.float32(0.1) : np.float32(0.33) : np.float32(0.1),]
assert_(grid32.dtype == np.float64)
assert_array_almost_equal(grid64, grid32)
# different code path for single slice
grid64 = mgrid[0.1:0.33:0.1]
grid32 = mgrid[np.float32(0.1) : np.float32(0.33) : np.float32(0.1)]
assert_(grid32.dtype == np.float64)
assert_array_almost_equal(grid64, grid32)
@skip(reason="longdouble")
def test_accepts_longdouble(self):
# regression tests for #16945
grid64 = mgrid[0.1:0.33:0.1,]
grid128 = mgrid[np.longdouble(0.1) : np.longdouble(0.33) : np.longdouble(0.1),]
assert_(grid128.dtype == np.longdouble)
assert_array_almost_equal(grid64, grid128)
grid128c_a = mgrid[0 : np.longdouble(1) : 3.4j]
grid128c_b = mgrid[0 : np.longdouble(1) : 3.4j,]
assert_(grid128c_a.dtype == grid128c_b.dtype == np.longdouble)
assert_array_equal(grid128c_a, grid128c_b[0])
# different code path for single slice
grid64 = mgrid[0.1:0.33:0.1]
grid128 = mgrid[np.longdouble(0.1) : np.longdouble(0.33) : np.longdouble(0.1)]
assert_(grid128.dtype == np.longdouble)
assert_array_almost_equal(grid64, grid128)
@skip(reason="longdouble")
def test_accepts_npcomplexfloating(self):
# Related to #16466
assert_array_almost_equal(
mgrid[0.1:0.3:3j,], mgrid[0.1 : 0.3 : np.complex64(3j),]
)
# different code path for single slice
assert_array_almost_equal(
mgrid[0.1:0.3:3j], mgrid[0.1 : 0.3 : np.complex64(3j)]
)
# Related to #16945
grid64_a = mgrid[0.1:0.3:3.3j]
grid64_b = mgrid[0.1:0.3:3.3j,][0]
assert_(grid64_a.dtype == grid64_b.dtype == np.float64)
assert_array_equal(grid64_a, grid64_b)
grid128_a = mgrid[0.1 : 0.3 : np.clongdouble(3.3j)]
grid128_b = mgrid[0.1 : 0.3 : np.clongdouble(3.3j),][0]
assert_(grid128_a.dtype == grid128_b.dtype == np.longdouble)
assert_array_equal(grid64_a, grid64_b)
@xfail # (reason="r_ not implemented")
| TestGrid |
python | openai__openai-python | src/openai/types/fine_tuning/fine_tuning_job.py | {
"start": 873,
"end": 1503
} | class ____(BaseModel):
batch_size: Union[Literal["auto"], int, None] = None
"""Number of examples in each batch.
A larger batch size means that model parameters are updated less frequently, but
with lower variance.
"""
learning_rate_multiplier: Union[Literal["auto"], float, None] = None
"""Scaling factor for the learning rate.
A smaller learning rate may be useful to avoid overfitting.
"""
n_epochs: Union[Literal["auto"], int, None] = None
"""The number of epochs to train the model for.
An epoch refers to one full cycle through the training dataset.
"""
| Hyperparameters |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/components_tests/test_code_references.py | {
"start": 457,
"end": 780
} | class ____(CacheableAssetsDefinition):
def compute_cacheable_data(self):
return []
def build_definitions(self, data):
@dg.asset
def my_asset():
return 1
return [my_asset]
@pytest.mark.skip("Find a way to set up this test with new Tree system")
| MyCacheableAssetsDefinition |
python | scikit-learn__scikit-learn | sklearn/externals/array_api_compat/common/_typing.py | {
"start": 3188,
"end": 3309
} | class ____(DTypesSigned, DTypesUnsigned):
pass
# `__array_namespace_info__.dtypes(kind="real floating")`
| DTypesIntegral |
python | neetcode-gh__leetcode | python/0221-maximal-square.py | {
"start": 0,
"end": 673
} | class ____:
def maximalSquare(self, matrix: List[List[str]]) -> int:
ROWS, COLS = len(matrix), len(matrix[0])
cache = {} # map each (r, c) -> maxLength of square
def helper(r, c):
if r >= ROWS or c >= COLS:
return 0
if (r, c) not in cache:
down = helper(r + 1, c)
right = helper(r, c + 1)
diag = helper(r + 1, c + 1)
cache[(r, c)] = 0
if matrix[r][c] == "1":
cache[(r, c)] = 1 + min(down, right, diag)
return cache[(r, c)]
helper(0, 0)
return max(cache.values()) ** 2
| Solution |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 324460,
"end": 328705
} | class ____(Node):
# Helper node for calling PyDict_Next() inside of a WhileStatNode
# and checking the dictionary size for changes. Created in
# Optimize.py.
child_attrs = ['dict_obj', 'expected_size', 'pos_index_var',
'coerced_key_var', 'coerced_value_var', 'coerced_tuple_var',
'key_target', 'value_target', 'tuple_target', 'is_dict_flag']
coerced_key_var = key_ref = None
coerced_value_var = value_ref = None
coerced_tuple_var = tuple_ref = None
def __init__(self, dict_obj, expected_size, pos_index_var,
key_target, value_target, tuple_target, is_dict_flag):
Node.__init__(
self, dict_obj.pos,
dict_obj=dict_obj,
expected_size=expected_size,
pos_index_var=pos_index_var,
key_target=key_target,
value_target=value_target,
tuple_target=tuple_target,
is_dict_flag=is_dict_flag,
is_temp=True,
type=PyrexTypes.c_bint_type)
def analyse_expressions(self, env):
from . import ExprNodes
self.dict_obj = self.dict_obj.analyse_types(env)
self.expected_size = self.expected_size.analyse_types(env)
if self.pos_index_var:
self.pos_index_var = self.pos_index_var.analyse_types(env)
if self.key_target:
self.key_target = self.key_target.analyse_target_types(env)
self.key_ref = ExprNodes.TempNode(self.key_target.pos, PyrexTypes.py_object_type)
self.coerced_key_var = self.key_ref.coerce_to(self.key_target.type, env)
if self.value_target:
self.value_target = self.value_target.analyse_target_types(env)
self.value_ref = ExprNodes.TempNode(self.value_target.pos, type=PyrexTypes.py_object_type)
self.coerced_value_var = self.value_ref.coerce_to(self.value_target.type, env)
if self.tuple_target:
self.tuple_target = self.tuple_target.analyse_target_types(env)
self.tuple_ref = ExprNodes.TempNode(self.tuple_target.pos, PyrexTypes.py_object_type)
self.coerced_tuple_var = self.tuple_ref.coerce_to(self.tuple_target.type, env)
self.is_dict_flag = self.is_dict_flag.analyse_types(env)
return self
def generate_function_definitions(self, env, code):
self.dict_obj.generate_function_definitions(env, code)
def generate_execution_code(self, code):
code.globalstate.use_utility_code(UtilityCode.load_cached("dict_iter", "Optimize.c"))
self.dict_obj.generate_evaluation_code(code)
assignments = []
temp_addresses = []
for var, result, target in [(self.key_ref, self.coerced_key_var, self.key_target),
(self.value_ref, self.coerced_value_var, self.value_target),
(self.tuple_ref, self.coerced_tuple_var, self.tuple_target)]:
if target is None:
addr = 'NULL'
else:
assignments.append((var, result, target))
var.allocate(code)
addr = '&%s' % var.result()
temp_addresses.append(addr)
result_temp = code.funcstate.allocate_temp(PyrexTypes.c_int_type, False)
code.putln("%s = __Pyx_dict_iter_next(%s, %s, &%s, %s, %s, %s, %s);" % (
result_temp,
self.dict_obj.py_result(),
self.expected_size.result(),
self.pos_index_var.result(),
temp_addresses[0],
temp_addresses[1],
temp_addresses[2],
self.is_dict_flag.result()
))
code.putln("if (unlikely(%s == 0)) break;" % result_temp)
code.putln(code.error_goto_if("%s == -1" % result_temp, self.pos))
code.funcstate.release_temp(result_temp)
# evaluate all coercions before the assignments
for var, result, target in assignments:
var.generate_gotref(code)
for var, result, target in assignments:
result.generate_evaluation_code(code)
for var, result, target in assignments:
target.generate_assignment_code(result, code)
var.release(code)
| DictIterationNextNode |
python | django__django | django/db/models/fields/related_descriptors.py | {
"start": 17501,
"end": 26148
} | class ____:
"""
Accessor to the related object on the reverse side of a one-to-one
relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
``Place.restaurant`` is a ``ReverseOneToOneDescriptor`` instance.
"""
def __init__(self, related):
# Following the example above, `related` is an instance of OneToOneRel
# which represents the reverse restaurant field (place.restaurant).
self.related = related
@cached_property
def RelatedObjectDoesNotExist(self):
# The exception isn't created at initialization time for the sake of
# consistency with `ForwardManyToOneDescriptor`.
return type(
"RelatedObjectDoesNotExist",
(self.related.related_model.DoesNotExist, AttributeError),
{
"__module__": self.related.model.__module__,
"__qualname__": "%s.%s.RelatedObjectDoesNotExist"
% (
self.related.model.__qualname__,
self.related.name,
),
},
)
def is_cached(self, instance):
return self.related.is_cached(instance)
def get_queryset(self, *, instance):
return self.related.related_model._base_manager.db_manager(
hints={"instance": instance}
).fetch_mode(instance._state.fetch_mode)
def get_prefetch_querysets(self, instances, querysets=None):
if querysets and len(querysets) != 1:
raise ValueError(
"querysets argument of get_prefetch_querysets() should have a length "
"of 1."
)
queryset = (
querysets[0] if querysets else self.get_queryset(instance=instances[0])
)
rel_obj_attr = self.related.field.get_local_related_value
instance_attr = self.related.field.get_foreign_related_value
instances_dict = {instance_attr(inst): inst for inst in instances}
query = {"%s__in" % self.related.field.name: instances}
queryset = queryset.filter(**query)
# There can be only one object prefetched for each instance so clear
# ordering if the query allows it without side effects.
queryset.query.clear_ordering()
# Since we're going to assign directly in the cache,
# we must manage the reverse relation cache manually.
for rel_obj in queryset:
instance = instances_dict[rel_obj_attr(rel_obj)]
self.related.field.set_cached_value(rel_obj, instance)
return (
queryset,
rel_obj_attr,
instance_attr,
True,
self.related.cache_name,
False,
)
def __get__(self, instance, cls=None):
"""
Get the related instance through the reverse relation.
With the example above, when getting ``place.restaurant``:
- ``self`` is the descriptor managing the ``restaurant`` attribute
- ``instance`` is the ``place`` instance
- ``cls`` is the ``Place`` class (unused)
Keep in mind that ``Restaurant`` holds the foreign key to ``Place``.
"""
if instance is None:
return self
# The related instance is loaded from the database and then cached
# by the field on the model instance state. It can also be pre-cached
# by the forward accessor (ForwardManyToOneDescriptor).
try:
rel_obj = self.related.get_cached_value(instance)
except KeyError:
if not instance._is_pk_set():
rel_obj = None
else:
instance._state.fetch_mode.fetch(self, instance)
rel_obj = self.related.get_cached_value(instance)
self.related.set_cached_value(instance, rel_obj)
if rel_obj is None:
raise self.RelatedObjectDoesNotExist(
"%s has no %s."
% (instance.__class__.__name__, self.related.accessor_name)
)
else:
return rel_obj
@property
def field(self):
"""
Add compatibility with the fetcher protocol. While self.related is not
a field but a OneToOneRel, it quacks enough like a field to work.
"""
return self.related
def fetch_one(self, instance):
# Kept for backwards compatibility with overridden
# get_forward_related_filter()
filter_args = self.related.field.get_forward_related_filter(instance)
try:
rel_obj = self.get_queryset(instance=instance).get(**filter_args)
except self.related.related_model.DoesNotExist:
rel_obj = None
else:
self.related.field.set_cached_value(rel_obj, instance)
self.related.set_cached_value(instance, rel_obj)
def fetch_many(self, instances):
is_cached = self.is_cached
missing_instances = [i for i in instances if not is_cached(i)]
prefetch_related_objects(
missing_instances,
self.related.get_accessor_name(),
)
def __set__(self, instance, value):
"""
Set the related instance through the reverse relation.
With the example above, when setting ``place.restaurant = restaurant``:
- ``self`` is the descriptor managing the ``restaurant`` attribute
- ``instance`` is the ``place`` instance
- ``value`` is the ``restaurant`` instance on the right of the equal
sign
Keep in mind that ``Restaurant`` holds the foreign key to ``Place``.
"""
# The similarity of the code below to the code in
# ForwardManyToOneDescriptor is annoying, but there's a bunch
# of small differences that would make a common base class convoluted.
if value is None:
# Update the cached related instance (if any) & clear the cache.
# Following the example above, this would be the cached
# ``restaurant`` instance (if any).
rel_obj = self.related.get_cached_value(instance, default=None)
if rel_obj is not None:
# Remove the ``restaurant`` instance from the ``place``
# instance cache.
self.related.delete_cached_value(instance)
# Set the ``place`` field on the ``restaurant``
# instance to None.
setattr(rel_obj, self.related.field.name, None)
elif not isinstance(value, self.related.related_model):
# An object must be an instance of the related class.
raise ValueError(
'Cannot assign "%r": "%s.%s" must be a "%s" instance.'
% (
value,
instance._meta.object_name,
self.related.accessor_name,
self.related.related_model._meta.object_name,
)
)
else:
if instance._state.db is None:
instance._state.db = router.db_for_write(
instance.__class__, instance=value
)
if value._state.db is None:
value._state.db = router.db_for_write(
value.__class__, instance=instance
)
if not router.allow_relation(value, instance):
raise ValueError(
'Cannot assign "%r": the current database router prevents this '
"relation." % value
)
related_pk = tuple(
getattr(instance, field.attname)
for field in self.related.field.foreign_related_fields
)
# Set the value of the related field to the value of the related
# object's related field.
for index, field in enumerate(self.related.field.local_related_fields):
setattr(value, field.attname, related_pk[index])
# Set the related instance cache used by __get__ to avoid an SQL
# query when accessing the attribute we just set.
self.related.set_cached_value(instance, value)
# Set the forward accessor cache on the related object to the
# current instance to avoid an extra SQL query if it's accessed
# later on.
self.related.field.set_cached_value(value, instance)
def __reduce__(self):
# Same purpose as ForwardManyToOneDescriptor.__reduce__().
return getattr, (self.related.model, self.related.name)
| ReverseOneToOneDescriptor |
python | kamyu104__LeetCode-Solutions | Python/reveal-cards-in-increasing-order.py | {
"start": 50,
"end": 392
} | class ____(object):
def deckRevealedIncreasing(self, deck):
"""
:type deck: List[int]
:rtype: List[int]
"""
d = collections.deque()
deck.sort(reverse=True)
for i in deck:
if d:
d.appendleft(d.pop())
d.appendleft(i)
return list(d)
| Solution |
python | ray-project__ray | python/ray/serve/batching.py | {
"start": 15390,
"end": 19610
} | class ____:
"""Stores a _BatchQueue and updates its settings.
_BatchQueue cannot be pickled, you must construct it lazily
at runtime inside a replica. This class initializes a queue only upon
first access.
"""
def __init__(
self,
max_batch_size: int = 10,
batch_wait_timeout_s: float = 0.0,
max_concurrent_batches: int = 1,
handle_batch_func: Optional[Callable] = None,
):
self._queue: Optional[_BatchQueue] = None
self.max_batch_size = max_batch_size
self.batch_wait_timeout_s = batch_wait_timeout_s
self.max_concurrent_batches = max_concurrent_batches
self.handle_batch_func = handle_batch_func
@property
def queue(self) -> _BatchQueue:
"""Returns _BatchQueue.
Initializes queue when called for the first time.
"""
if self._queue is None:
self._queue = _BatchQueue(
self.max_batch_size,
self.batch_wait_timeout_s,
self.max_concurrent_batches,
self.handle_batch_func,
)
return self._queue
def set_max_batch_size(self, new_max_batch_size: int) -> None:
"""Updates queue's max_batch_size."""
self.max_batch_size = new_max_batch_size
if self._queue is not None:
self._queue.set_max_batch_size(new_max_batch_size)
def set_batch_wait_timeout_s(self, new_batch_wait_timeout_s: float) -> None:
self.batch_wait_timeout_s = new_batch_wait_timeout_s
if self._queue is not None:
self._queue.batch_wait_timeout_s = new_batch_wait_timeout_s
def get_max_batch_size(self) -> int:
return self.max_batch_size
def get_batch_wait_timeout_s(self) -> float:
return self.batch_wait_timeout_s
def _get_curr_iteration_start_times(self) -> _RuntimeSummaryStatistics:
"""Gets summary statistics of current iteration's start times."""
return _RuntimeSummaryStatistics(
list(self.queue.curr_iteration_start_times.values())
)
async def _is_batching_task_alive(self) -> bool:
"""Gets whether default _BatchQueue's background task is alive.
Returns False if the batch handler doesn't use a default _BatchQueue.
"""
if hasattr(self.queue, "_handle_batch_task"):
return not self.queue._handle_batch_task.done()
else:
return False
async def _get_handling_task_stack(self) -> Optional[str]:
"""Gets the stack for the default _BatchQueue's background task.
Returns empty string if the batch handler doesn't use a default _BatchQueue.
"""
if hasattr(self.queue, "_handle_batch_task"):
str_buffer = io.StringIO()
self.queue._handle_batch_task.print_stack(file=str_buffer)
return str_buffer.getvalue()
else:
return None
def _validate_max_batch_size(max_batch_size):
if not isinstance(max_batch_size, int):
if isinstance(max_batch_size, float) and max_batch_size.is_integer():
max_batch_size = int(max_batch_size)
else:
raise TypeError(
f"max_batch_size must be integer >= 1, got {max_batch_size}"
)
if max_batch_size < 1:
raise ValueError(
f"max_batch_size must be an integer >= 1, got {max_batch_size}"
)
def _validate_batch_wait_timeout_s(batch_wait_timeout_s):
if not isinstance(batch_wait_timeout_s, (float, int)):
raise TypeError(
f"batch_wait_timeout_s must be a float >= 0, got {batch_wait_timeout_s}"
)
if batch_wait_timeout_s < 0:
raise ValueError(
f"batch_wait_timeout_s must be a float >= 0, got {batch_wait_timeout_s}"
)
def _validate_max_concurrent_batches(max_concurrent_batches: int) -> None:
if not isinstance(max_concurrent_batches, int) or max_concurrent_batches < 1:
raise TypeError(
f"max_concurrent_batches must be an integer >= 1, got {max_concurrent_batches}"
)
SelfType = TypeVar("SelfType", contravariant=True)
T = TypeVar("T")
R = TypeVar("R")
| _LazyBatchQueueWrapper |
python | django-haystack__django-haystack | haystack/utils/log.py | {
"start": 154,
"end": 468
} | class ____:
def __init__(self, real_logger):
self.real_logger = real_logger
def noop(self, *args, **kwargs):
pass
def __getattr__(self, attr):
if getattr(settings, "HAYSTACK_LOGGING", True):
return getattr(self.real_logger, attr)
return self.noop
| LoggingFacade |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py | {
"start": 200,
"end": 958
} | class ____(Node):
__slots__ = ('loc', 'definitions',)
_fields = ('definitions',)
def __init__(self, definitions, loc=None):
self.loc = loc
self.definitions = definitions
def __eq__(self, other):
return (
self is other or (
isinstance(other, Document) and
# self.loc == other.loc and
self.definitions == other.definitions
)
)
def __repr__(self):
return ('Document('
'definitions={self.definitions!r}'
')').format(self=self)
def __copy__(self):
return type(self)(
self.definitions,
self.loc
)
def __hash__(self):
return id(self)
| Document |
python | realpython__materials | inheritance-and-composition/inheritance/employees.py | {
"start": 236,
"end": 425
} | class ____(Employee, ManagerRole, SalaryPolicy):
def __init__(self, id, name, weekly_salary):
SalaryPolicy.__init__(self, weekly_salary)
super().__init__(id, name)
| Manager |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.