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
doocs__leetcode
solution/0100-0199/0112.Path Sum/Solution.py
{ "start": 192, "end": 586 }
class ____: def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: def dfs(root, s): if root is None: return False s += root.val if root.left is None and root.right is None and s == targetSum: return True return dfs(root.left, s) or dfs(root.right, s) return dfs(root, 0)
Solution
python
weaviate__weaviate-python-client
weaviate/collections/classes/grpc.py
{ "start": 9617, "end": 10716 }
class ____(_WeaviateInput, Generic[V]): dimensionality: Literal["1D", "2D"] vectors: Sequence[V] @staticmethod def is_one_dimensional( self_: "_ListOfVectorsQuery", ) -> TypeGuard["_ListOfVectorsQuery[OneDimensionalVectorType]"]: return self_.dimensionality == "1D" @staticmethod def is_two_dimensional( self_: "_ListOfVectorsQuery", ) -> TypeGuard["_ListOfVectorsQuery[TwoDimensionalVectorType]"]: return self_.dimensionality == "2D" ListOfVectorsQuery = _ListOfVectorsQuery """Define a many-vectors query to be used within a near vector search, i.e. multiple vectors over a single-vector space.""" NearVectorInputType = Union[ OneDimensionalVectorType, TwoDimensionalVectorType, Mapping[ str, Union[ OneDimensionalVectorType, TwoDimensionalVectorType, ListOfVectorsQuery[OneDimensionalVectorType], ListOfVectorsQuery[TwoDimensionalVectorType], ], ], ] """Define the input types that can be used in a near vector search"""
_ListOfVectorsQuery
python
huggingface__transformers
src/transformers/models/sam3_tracker_video/modular_sam3_tracker_video.py
{ "start": 18148, "end": 18212 }
class ____(Sam2VideoAttention): pass
Sam3TrackerVideoAttention
python
Pylons__pyramid
tests/test_path.py
{ "start": 8305, "end": 10442 }
class ____(unittest.TestCase): def _getTargetClass(self): from pyramid.path import PkgResourcesAssetDescriptor return PkgResourcesAssetDescriptor def _makeOne(self, pkg='tests', path='test_asset.py'): return self._getTargetClass()(pkg, path) def test_class_conforms_to_IAssetDescriptor(self): from zope.interface.verify import verifyClass from pyramid.interfaces import IAssetDescriptor verifyClass(IAssetDescriptor, self._getTargetClass()) def test_instance_conforms_to_IAssetDescriptor(self): from zope.interface.verify import verifyObject from pyramid.interfaces import IAssetDescriptor verifyObject(IAssetDescriptor, self._makeOne()) def test_absspec(self): inst = self._makeOne() self.assertEqual(inst.absspec(), 'tests:test_asset.py') def test_abspath(self): inst = self._makeOne() self.assertEqual(inst.abspath(), os.path.join(here, 'test_asset.py')) def test_stream(self): inst = self._makeOne() inst.pkg_resources = DummyPkgResource() inst.pkg_resources.resource_stream = lambda x, y: f'{x}:{y}' s = inst.stream() self.assertEqual(s, '{}:{}'.format('tests', 'test_asset.py')) def test_isdir(self): inst = self._makeOne() inst.pkg_resources = DummyPkgResource() inst.pkg_resources.resource_isdir = lambda x, y: f'{x}:{y}' self.assertEqual( inst.isdir(), '{}:{}'.format('tests', 'test_asset.py') ) def test_listdir(self): inst = self._makeOne() inst.pkg_resources = DummyPkgResource() inst.pkg_resources.resource_listdir = lambda x, y: f'{x}:{y}' self.assertEqual( inst.listdir(), '{}:{}'.format('tests', 'test_asset.py') ) def test_exists(self): inst = self._makeOne() inst.pkg_resources = DummyPkgResource() inst.pkg_resources.resource_exists = lambda x, y: f'{x}:{y}' self.assertEqual( inst.exists(), '{}:{}'.format('tests', 'test_asset.py') )
TestPkgResourcesAssetDescriptor
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/distributions/special_math_test.py
{ "start": 2760, "end": 5008 }
class ____(test.TestCase): def assertAllFinite(self, x): is_finite = np.isfinite(x) all_true = np.ones_like(is_finite, dtype=np.bool_) self.assertAllEqual(all_true, is_finite) @test_util.run_in_graph_and_eager_modes def testNdtri(self): """Verifies that ndtri computation is correct.""" if not special: return p = np.linspace(0., 1.0, 50).astype(np.float64) # Quantile performs piecewise rational approximation so adding some # special input values to make sure we hit all the pieces. p = np.hstack((p, np.exp(-32), 1. - np.exp(-32), np.exp(-2), 1. - np.exp(-2))) expected_x = special.ndtri(p) x = special_math.ndtri(p) self.assertAllClose(expected_x, self.evaluate(x), atol=0.) @test_util.run_deprecated_v1 def testNdtriDynamicShape(self): """Verifies that ndtri computation is correct.""" with self.cached_session() as sess: if not special: return p = array_ops.placeholder(np.float32) p_ = np.linspace(0., 1.0, 50).astype(np.float32) x = special_math.ndtri(p) x_ = sess.run(x, feed_dict={p: p_}) expected_x_ = special.ndtri(p_) self.assertAllClose(expected_x_, x_, atol=0.) def _baseNdtriFiniteGradientTest(self, dtype): """Verifies that ndtri has finite gradients at interesting points.""" # Tests gradients at 0, 1, and piece-wise boundaries. p = constant_op.constant( np.array([ 0., np.exp(-32.), np.exp(-2.), 1. - np.exp(-2.), 1. - np.exp(-32.), 1., ]).astype(dtype)) # Not having the lambda sanitizer means we'd get an `IndexError` whenever # the user supplied function has default args. _, grads = _value_and_gradient( lambda x: special_math.ndtri(x), p) # pylint: disable=unnecessary-lambda self.assertAllFinite(self.evaluate(grads[0])) @test_util.run_in_graph_and_eager_modes def testNdtriFiniteGradientFloat32(self): self._baseNdtriFiniteGradientTest(np.float32) @test_util.run_in_graph_and_eager_modes def testNdtriFiniteGradientFloat64(self): self._baseNdtriFiniteGradientTest(np.float64) @test_util.run_all_in_graph_and_eager_modes
NdtriTest
python
pytest-dev__pytest-django
tests/test_fixtures.py
{ "start": 26907, "end": 32552 }
class ____: @pytest.mark.django_db def test_block_manually(self, django_db_blocker: DjangoDbBlocker) -> None: try: django_db_blocker.block() with pytest.raises(RuntimeError, match="^Database access not allowed,"): Item.objects.exists() finally: django_db_blocker.restore() @pytest.mark.django_db def test_block_with_block(self, django_db_blocker: DjangoDbBlocker) -> None: with django_db_blocker.block(): with pytest.raises(RuntimeError, match="^Database access not allowed,"): Item.objects.exists() def test_unblock_manually(self, django_db_blocker: DjangoDbBlocker) -> None: try: django_db_blocker.unblock() Item.objects.exists() finally: django_db_blocker.restore() def test_unblock_with_block(self, django_db_blocker: DjangoDbBlocker) -> None: with django_db_blocker.unblock(): Item.objects.exists() def test_mail(mailoutbox) -> None: assert mailoutbox is mail.outbox # check that mail.outbox and fixture value is same object assert len(mailoutbox) == 0 mail.send_mail("subject", "body", "from@example.com", ["to@example.com"]) assert len(mailoutbox) == 1 m = mailoutbox[0] assert m.subject == "subject" assert m.body == "body" assert m.from_email == "from@example.com" assert list(m.to) == ["to@example.com"] def test_mail_again(mailoutbox) -> None: test_mail(mailoutbox) def test_mail_message_uses_mocked_DNS_NAME(mailoutbox) -> None: mail.send_mail("subject", "body", "from@example.com", ["to@example.com"]) m = mailoutbox[0] message = m.message() assert message["Message-ID"].endswith("@fake-tests.example.com>") def test_mail_message_uses_django_mail_dnsname_fixture(django_pytester: DjangoPytester) -> None: django_pytester.create_test_module( """ from django.core import mail import pytest @pytest.fixture def django_mail_dnsname(): return 'from.django_mail_dnsname' def test_mailbox_inner(mailoutbox): mail.send_mail('subject', 'body', 'from@example.com', ['to@example.com']) m = mailoutbox[0] message = m.message() assert message['Message-ID'].endswith('@from.django_mail_dnsname>') """ ) result = django_pytester.runpytest_subprocess("--tb=short", "-v") result.stdout.fnmatch_lines(["*test_mailbox_inner*PASSED*"]) assert result.ret == 0 def test_mail_message_dns_patching_can_be_skipped(django_pytester: DjangoPytester) -> None: django_pytester.create_test_module( """ from django.core import mail import pytest @pytest.fixture def django_mail_dnsname(): raise Exception('should not get called') @pytest.fixture def django_mail_patch_dns(): print('\\ndjango_mail_dnsname_mark') def test_mailbox_inner(mailoutbox, monkeypatch): def mocked_make_msgid(*args, **kwargs): mocked_make_msgid.called += [(args, kwargs)] mocked_make_msgid.called = [] monkeypatch.setattr(mail.message, 'make_msgid', mocked_make_msgid) mail.send_mail( 'subject', 'body', 'from@example.com', ['to@example.com'] ) m = mailoutbox[0] assert len(mocked_make_msgid.called) == 1 assert mocked_make_msgid.called[0][1]['domain'] is mail.DNS_NAME """ ) result = django_pytester.runpytest_subprocess("--tb=short", "-vv", "-s") result.stdout.fnmatch_lines(["*test_mailbox_inner*", "django_mail_dnsname_mark", "PASSED*"]) assert result.ret == 0 @pytest.mark.django_project( create_manage_py=True, extra_settings=""" EMAIL_BACKEND = "django.core.mail.backends.dummy.EmailBackend" """, ) def test_mail_auto_fixture_misconfigured(django_pytester: DjangoPytester) -> None: """ django_test_environment fixture can be overridden by user, and that would break mailoutbox fixture. Normally settings.EMAIL_BACKEND is set to "django.core.mail.backends.locmem.EmailBackend" by django, along with mail.outbox = []. If this function doesn't run for whatever reason, the mailoutbox fixture will not work properly. """ django_pytester.create_test_module( """ import pytest @pytest.fixture(autouse=True, scope="session") def django_test_environment(request): yield """, filename="conftest.py", ) django_pytester.create_test_module( """ def test_with_fixture(settings, mailoutbox): assert mailoutbox == [] assert settings.EMAIL_BACKEND == "django.core.mail.backends.dummy.EmailBackend" def test_without_fixture(): from django.core import mail assert not hasattr(mail, "outbox") """ ) result = django_pytester.runpytest_subprocess() result.assert_outcomes(passed=2) @pytest.mark.django_project(create_settings=False) def test_no_settings(django_pytester: DjangoPytester) -> None: django_pytester.create_test_module( """ def test_skipped_settings(settings): assert False def test_skipped_mailoutbox(mailoutbox): assert False def test_mail(): from django.core import mail assert not hasattr(mail, "outbox") """ ) result = django_pytester.runpytest_subprocess() result.assert_outcomes(passed=1, skipped=2)
Test_django_db_blocker
python
has2k1__plotnine
plotnine/_utils/registry.py
{ "start": 1000, "end": 1953 }
class ____(ABCMeta): """ Creates class that automatically registers all subclasses To prevent the base class from showing up in the registry, it should inherit from ABC. This metaclass uses a single dictionary to register all types of subclasses. To access the registered objects, use: obj = Registry['name'] To explicitly register objects Registry['name'] = obj Notes ----- When objects are deleted, they are automatically removed from the Registry. """ # namespace is of the class that subclasses Registry (or a # subclasses a subclass of Registry, ...) being created # e.g. geom, geom_point, ... def __new__(cls, name, bases, namespace): sub_cls = super().__new__(cls, name, bases, namespace) is_base_class = len(bases) and bases[0].__name__ == "ABC" if not is_base_class: Registry[name] = sub_cls return sub_cls
Register
python
falconry__falcon
tests/asgi/_asgi_test_app.py
{ "start": 8260, "end": 8913 }
class ____: async def on_get(self, req, resp): # NOTE(myusko): In the future we shouldn't change the cookie # a test depends on the input. # NOTE(kgriffs): This is the only test that uses a single # cookie (vs. multiple) as input; if this input ever changes, # a separate test will need to be added to explicitly verify # this use case. resp.set_cookie('has_permission', 'true') async def on_post(self, req, resp): if req.cookies['has_permission'] == 'true': resp.status = falcon.HTTP_200 else: resp.status = falcon.HTTP_403
TestJar
python
davidhalter__jedi
test/completion/classes.py
{ "start": 9832, "end": 10046 }
class ____(MyBase): def f3(self): #! 13 ['def f1'] self.f1() . # hey''' #? 13 MyBase.f1 self.f1() . # hey''' # ----------------- # With a very weird __init__ # -----------------
C1
python
optuna__optuna
optuna/cli.py
{ "start": 10552, "end": 12274 }
class ____(_BaseCommand): """Create a new study.""" def add_arguments(self, parser: ArgumentParser) -> None: parser.add_argument( "--study-name", default=None, help="A human-readable name of a study to distinguish it from others.", ) parser.add_argument( "--direction", default=None, type=str, choices=("minimize", "maximize"), help="Set direction of optimization to a new study. Set 'minimize' " "for minimization and 'maximize' for maximization.", ) parser.add_argument( "--skip-if-exists", default=False, action="store_true", help="If specified, the creation of the study is skipped " "without any error when the study name is duplicated.", ) parser.add_argument( "--directions", type=str, default=None, choices=("minimize", "maximize"), help="Set directions of optimization to a new study." " Put whitespace between directions. Each direction should be" ' either "minimize" or "maximize".', nargs="+", ) def take_action(self, parsed_args: Namespace) -> int: storage = _get_storage(parsed_args.storage, parsed_args.storage_class) study_name = optuna.create_study( storage=storage, study_name=parsed_args.study_name, direction=parsed_args.direction, directions=parsed_args.directions, load_if_exists=parsed_args.skip_if_exists, ).study_name print(study_name) return 0
_CreateStudy
python
openai__gym
gym/envs/mujoco/humanoid_v4.py
{ "start": 419, "end": 27951 }
class ____(MujocoEnv, utils.EzPickle): """ ### Description This environment is based on the environment introduced by Tassa, Erez and Todorov in ["Synthesis and stabilization of complex behaviors through online trajectory optimization"](https://ieeexplore.ieee.org/document/6386025). The 3D bipedal robot is designed to simulate a human. It has a torso (abdomen) with a pair of legs and arms. The legs each consist of two links, and so the arms (representing the knees and elbows respectively). The goal of the environment is to walk forward as fast as possible without falling over. ### Action Space The action space is a `Box(-1, 1, (17,), float32)`. An action represents the torques applied at the hinge joints. | Num | Action | Control Min | Control Max | Name (in corresponding XML file) | Joint | Unit | |-----|----------------------|---------------|----------------|---------------------------------------|-------|------| | 0 | Torque applied on the hinge in the y-coordinate of the abdomen | -0.4 | 0.4 | hip_1 (front_left_leg) | hinge | torque (N m) | | 1 | Torque applied on the hinge in the z-coordinate of the abdomen | -0.4 | 0.4 | angle_1 (front_left_leg) | hinge | torque (N m) | | 2 | Torque applied on the hinge in the x-coordinate of the abdomen | -0.4 | 0.4 | hip_2 (front_right_leg) | hinge | torque (N m) | | 3 | Torque applied on the rotor between torso/abdomen and the right hip (x-coordinate) | -0.4 | 0.4 | right_hip_x (right_thigh) | hinge | torque (N m) | | 4 | Torque applied on the rotor between torso/abdomen and the right hip (z-coordinate) | -0.4 | 0.4 | right_hip_z (right_thigh) | hinge | torque (N m) | | 5 | Torque applied on the rotor between torso/abdomen and the right hip (y-coordinate) | -0.4 | 0.4 | right_hip_y (right_thigh) | hinge | torque (N m) | | 6 | Torque applied on the rotor between the right hip/thigh and the right shin | -0.4 | 0.4 | right_knee | hinge | torque (N m) | | 7 | Torque applied on the rotor between torso/abdomen and the left hip (x-coordinate) | -0.4 | 0.4 | left_hip_x (left_thigh) | hinge | torque (N m) | | 8 | Torque applied on the rotor between torso/abdomen and the left hip (z-coordinate) | -0.4 | 0.4 | left_hip_z (left_thigh) | hinge | torque (N m) | | 9 | Torque applied on the rotor between torso/abdomen and the left hip (y-coordinate) | -0.4 | 0.4 | left_hip_y (left_thigh) | hinge | torque (N m) | | 10 | Torque applied on the rotor between the left hip/thigh and the left shin | -0.4 | 0.4 | left_knee | hinge | torque (N m) | | 11 | Torque applied on the rotor between the torso and right upper arm (coordinate -1) | -0.4 | 0.4 | right_shoulder1 | hinge | torque (N m) | | 12 | Torque applied on the rotor between the torso and right upper arm (coordinate -2) | -0.4 | 0.4 | right_shoulder2 | hinge | torque (N m) | | 13 | Torque applied on the rotor between the right upper arm and right lower arm | -0.4 | 0.4 | right_elbow | hinge | torque (N m) | | 14 | Torque applied on the rotor between the torso and left upper arm (coordinate -1) | -0.4 | 0.4 | left_shoulder1 | hinge | torque (N m) | | 15 | Torque applied on the rotor between the torso and left upper arm (coordinate -2) | -0.4 | 0.4 | left_shoulder2 | hinge | torque (N m) | | 16 | Torque applied on the rotor between the left upper arm and left lower arm | -0.4 | 0.4 | left_elbow | hinge | torque (N m) | ### Observation Space Observations consist of positional values of different body parts of the Humanoid, followed by the velocities of those individual parts (their derivatives) with all the positions ordered before all the velocities. By default, observations do not include the x- and y-coordinates of the torso. These may be included by passing `exclude_current_positions_from_observation=False` during construction. In that case, the observation space will have 378 dimensions where the first two dimensions represent the x- and y-coordinates of the torso. Regardless of whether `exclude_current_positions_from_observation` was set to true or false, the x- and y-coordinates will be returned in `info` with keys `"x_position"` and `"y_position"`, respectively. However, by default, the observation is a `ndarray` with shape `(376,)` where the elements correspond to the following: | Num | Observation | Min | Max | Name (in corresponding XML file) | Joint | Unit | | --- | --------------------------------------------------------------------------------------------------------------- | ---- | --- | -------------------------------- | ----- | -------------------------- | | 0 | z-coordinate of the torso (centre) | -Inf | Inf | root | free | position (m) | | 1 | x-orientation of the torso (centre) | -Inf | Inf | root | free | angle (rad) | | 2 | y-orientation of the torso (centre) | -Inf | Inf | root | free | angle (rad) | | 3 | z-orientation of the torso (centre) | -Inf | Inf | root | free | angle (rad) | | 4 | w-orientation of the torso (centre) | -Inf | Inf | root | free | angle (rad) | | 5 | z-angle of the abdomen (in lower_waist) | -Inf | Inf | abdomen_z | hinge | angle (rad) | | 6 | y-angle of the abdomen (in lower_waist) | -Inf | Inf | abdomen_y | hinge | angle (rad) | | 7 | x-angle of the abdomen (in pelvis) | -Inf | Inf | abdomen_x | hinge | angle (rad) | | 8 | x-coordinate of angle between pelvis and right hip (in right_thigh) | -Inf | Inf | right_hip_x | hinge | angle (rad) | | 9 | z-coordinate of angle between pelvis and right hip (in right_thigh) | -Inf | Inf | right_hip_z | hinge | angle (rad) | | 19 | y-coordinate of angle between pelvis and right hip (in right_thigh) | -Inf | Inf | right_hip_y | hinge | angle (rad) | | 11 | angle between right hip and the right shin (in right_knee) | -Inf | Inf | right_knee | hinge | angle (rad) | | 12 | x-coordinate of angle between pelvis and left hip (in left_thigh) | -Inf | Inf | left_hip_x | hinge | angle (rad) | | 13 | z-coordinate of angle between pelvis and left hip (in left_thigh) | -Inf | Inf | left_hip_z | hinge | angle (rad) | | 14 | y-coordinate of angle between pelvis and left hip (in left_thigh) | -Inf | Inf | left_hip_y | hinge | angle (rad) | | 15 | angle between left hip and the left shin (in left_knee) | -Inf | Inf | left_knee | hinge | angle (rad) | | 16 | coordinate-1 (multi-axis) angle between torso and right arm (in right_upper_arm) | -Inf | Inf | right_shoulder1 | hinge | angle (rad) | | 17 | coordinate-2 (multi-axis) angle between torso and right arm (in right_upper_arm) | -Inf | Inf | right_shoulder2 | hinge | angle (rad) | | 18 | angle between right upper arm and right_lower_arm | -Inf | Inf | right_elbow | hinge | angle (rad) | | 19 | coordinate-1 (multi-axis) angle between torso and left arm (in left_upper_arm) | -Inf | Inf | left_shoulder1 | hinge | angle (rad) | | 20 | coordinate-2 (multi-axis) angle between torso and left arm (in left_upper_arm) | -Inf | Inf | left_shoulder2 | hinge | angle (rad) | | 21 | angle between left upper arm and left_lower_arm | -Inf | Inf | left_elbow | hinge | angle (rad) | | 22 | x-coordinate velocity of the torso (centre) | -Inf | Inf | root | free | velocity (m/s) | | 23 | y-coordinate velocity of the torso (centre) | -Inf | Inf | root | free | velocity (m/s) | | 24 | z-coordinate velocity of the torso (centre) | -Inf | Inf | root | free | velocity (m/s) | | 25 | x-coordinate angular velocity of the torso (centre) | -Inf | Inf | root | free | anglular velocity (rad/s) | | 26 | y-coordinate angular velocity of the torso (centre) | -Inf | Inf | root | free | anglular velocity (rad/s) | | 27 | z-coordinate angular velocity of the torso (centre) | -Inf | Inf | root | free | anglular velocity (rad/s) | | 28 | z-coordinate of angular velocity of the abdomen (in lower_waist) | -Inf | Inf | abdomen_z | hinge | anglular velocity (rad/s) | | 29 | y-coordinate of angular velocity of the abdomen (in lower_waist) | -Inf | Inf | abdomen_y | hinge | anglular velocity (rad/s) | | 30 | x-coordinate of angular velocity of the abdomen (in pelvis) | -Inf | Inf | abdomen_x | hinge | aanglular velocity (rad/s) | | 31 | x-coordinate of the angular velocity of the angle between pelvis and right hip (in right_thigh) | -Inf | Inf | right_hip_x | hinge | anglular velocity (rad/s) | | 32 | z-coordinate of the angular velocity of the angle between pelvis and right hip (in right_thigh) | -Inf | Inf | right_hip_z | hinge | anglular velocity (rad/s) | | 33 | y-coordinate of the angular velocity of the angle between pelvis and right hip (in right_thigh) | -Inf | Inf | right_hip_y | hinge | anglular velocity (rad/s) | | 34 | angular velocity of the angle between right hip and the right shin (in right_knee) | -Inf | Inf | right_knee | hinge | anglular velocity (rad/s) | | 35 | x-coordinate of the angular velocity of the angle between pelvis and left hip (in left_thigh) | -Inf | Inf | left_hip_x | hinge | anglular velocity (rad/s) | | 36 | z-coordinate of the angular velocity of the angle between pelvis and left hip (in left_thigh) | -Inf | Inf | left_hip_z | hinge | anglular velocity (rad/s) | | 37 | y-coordinate of the angular velocity of the angle between pelvis and left hip (in left_thigh) | -Inf | Inf | left_hip_y | hinge | anglular velocity (rad/s) | | 38 | angular velocity of the angle between left hip and the left shin (in left_knee) | -Inf | Inf | left_knee | hinge | anglular velocity (rad/s) | | 39 | coordinate-1 (multi-axis) of the angular velocity of the angle between torso and right arm (in right_upper_arm) | -Inf | Inf | right_shoulder1 | hinge | anglular velocity (rad/s) | | 40 | coordinate-2 (multi-axis) of the angular velocity of the angle between torso and right arm (in right_upper_arm) | -Inf | Inf | right_shoulder2 | hinge | anglular velocity (rad/s) | | 41 | angular velocity of the angle between right upper arm and right_lower_arm | -Inf | Inf | right_elbow | hinge | anglular velocity (rad/s) | | 42 | coordinate-1 (multi-axis) of the angular velocity of the angle between torso and left arm (in left_upper_arm) | -Inf | Inf | left_shoulder1 | hinge | anglular velocity (rad/s) | | 43 | coordinate-2 (multi-axis) of the angular velocity of the angle between torso and left arm (in left_upper_arm) | -Inf | Inf | left_shoulder2 | hinge | anglular velocity (rad/s) | | 44 | angular velocitty of the angle between left upper arm and left_lower_arm | -Inf | Inf | left_elbow | hinge | anglular velocity (rad/s) | Additionally, after all the positional and velocity based values in the table, the observation contains (in order): - *cinert:* Mass and inertia of a single rigid body relative to the center of mass (this is an intermediate result of transition). It has shape 14*10 (*nbody * 10*) and hence adds to another 140 elements in the state space. - *cvel:* Center of mass based velocity. It has shape 14 * 6 (*nbody * 6*) and hence adds another 84 elements in the state space - *qfrc_actuator:* Constraint force generated as the actuator force. This has shape `(23,)` *(nv * 1)* and hence adds another 23 elements to the state space. - *cfrc_ext:* This is the center of mass based external force on the body. It has shape 14 * 6 (*nbody * 6*) and hence adds to another 84 elements in the state space. where *nbody* stands for the number of bodies in the robot and *nv* stands for the number of degrees of freedom (*= dim(qvel)*) The (x,y,z) coordinates are translational DOFs while the orientations are rotational DOFs expressed as quaternions. One can read more about free joints on the [Mujoco Documentation](https://mujoco.readthedocs.io/en/latest/XMLreference.html). **Note:** Humanoid-v4 environment no longer has the following contact forces issue. If using previous Humanoid versions from v4, there have been reported issues that using a Mujoco-Py version > 2.0 results in the contact forces always being 0. As such we recommend to use a Mujoco-Py version < 2.0 when using the Humanoid environment if you would like to report results with contact forces (if contact forces are not used in your experiments, you can use version > 2.0). ### Rewards The reward consists of three parts: - *healthy_reward*: Every timestep that the humanoid is alive (see section Episode Termination for definition), it gets a reward of fixed value `healthy_reward` - *forward_reward*: A reward of walking forward which is measured as *`forward_reward_weight` * (average center of mass before action - average center of mass after action)/dt*. *dt* is the time between actions and is dependent on the frame_skip parameter (default is 5), where the frametime is 0.003 - making the default *dt = 5 * 0.003 = 0.015*. This reward would be positive if the humanoid walks forward (in positive x-direction). The calculation for the center of mass is defined in the `.py` file for the Humanoid. - *ctrl_cost*: A negative reward for penalising the humanoid if it has too large of a control force. If there are *nu* actuators/controls, then the control has shape `nu x 1`. It is measured as *`ctrl_cost_weight` * sum(control<sup>2</sup>)*. - *contact_cost*: A negative reward for penalising the humanoid if the external contact force is too large. It is calculated by clipping *`contact_cost_weight` * sum(external contact force<sup>2</sup>)* to the interval specified by `contact_cost_range`. The total reward returned is ***reward*** *=* *healthy_reward + forward_reward - ctrl_cost - contact_cost* and `info` will also contain the individual reward terms ### Starting State All observations start in state (0.0, 0.0, 1.4, 1.0, 0.0 ... 0.0) with a uniform noise in the range of [-`reset_noise_scale`, `reset_noise_scale`] added to the positional and velocity values (values in the table) for stochasticity. Note that the initial z coordinate is intentionally selected to be high, thereby indicating a standing up humanoid. The initial orientation is designed to make it face forward as well. ### Episode End The humanoid is said to be unhealthy if the z-position of the torso is no longer contained in the closed interval specified by the argument `healthy_z_range`. If `terminate_when_unhealthy=True` is passed during construction (which is the default), the episode ends when any of the following happens: 1. Truncation: The episode duration reaches a 1000 timesteps 3. Termination: The humanoid is unhealthy If `terminate_when_unhealthy=False` is passed, the episode is ended only when 1000 timesteps are exceeded. ### Arguments No additional arguments are currently supported in v2 and lower. ``` env = gym.make('Humanoid-v4') ``` v3 and v4 take gym.make kwargs such as xml_file, ctrl_cost_weight, reset_noise_scale etc. ``` env = gym.make('Humanoid-v4', ctrl_cost_weight=0.1, ....) ``` | Parameter | Type | Default | Description | | -------------------------------------------- | --------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `xml_file` | **str** | `"humanoid.xml"` | Path to a MuJoCo model | | `forward_reward_weight` | **float** | `1.25` | Weight for _forward_reward_ term (see section on reward) | | `ctrl_cost_weight` | **float** | `0.1` | Weight for _ctrl_cost_ term (see section on reward) | | `contact_cost_weight` | **float** | `5e-7` | Weight for _contact_cost_ term (see section on reward) | | `healthy_reward` | **float** | `5.0` | Constant reward given if the humanoid is "healthy" after timestep | | `terminate_when_unhealthy` | **bool** | `True` | If true, issue a done signal if the z-coordinate of the torso is no longer in the `healthy_z_range` | | `healthy_z_range` | **tuple** | `(1.0, 2.0)` | The humanoid is considered healthy if the z-coordinate of the torso is in this range | | `reset_noise_scale` | **float** | `1e-2` | Scale of random perturbations of initial position and velocity (see section on Starting State) | | `exclude_current_positions_from_observation` | **bool** | `True` | Whether or not to omit the x- and y-coordinates from observations. Excluding the position can serve as an inductive bias to induce position-agnostic behavior in policies | ### Version History * v4: all mujoco environments now use the mujoco bindings in mujoco>=2.1.3 * v3: support for gym.make kwargs such as xml_file, ctrl_cost_weight, reset_noise_scale etc. rgb rendering comes from tracking camera (so agent does not run away from screen) * v2: All continuous control environments now use mujoco_py >= 1.50 * v1: max_time_steps raised to 1000 for robot based tasks. Added reward_threshold to environments. * v0: Initial versions release (1.0.0) """ metadata = { "render_modes": [ "human", "rgb_array", "depth_array", ], "render_fps": 67, } def __init__( self, forward_reward_weight=1.25, ctrl_cost_weight=0.1, healthy_reward=5.0, terminate_when_unhealthy=True, healthy_z_range=(1.0, 2.0), reset_noise_scale=1e-2, exclude_current_positions_from_observation=True, **kwargs ): utils.EzPickle.__init__( self, forward_reward_weight, ctrl_cost_weight, healthy_reward, terminate_when_unhealthy, healthy_z_range, reset_noise_scale, exclude_current_positions_from_observation, **kwargs ) self._forward_reward_weight = forward_reward_weight self._ctrl_cost_weight = ctrl_cost_weight self._healthy_reward = healthy_reward self._terminate_when_unhealthy = terminate_when_unhealthy self._healthy_z_range = healthy_z_range self._reset_noise_scale = reset_noise_scale self._exclude_current_positions_from_observation = ( exclude_current_positions_from_observation ) if exclude_current_positions_from_observation: observation_space = Box( low=-np.inf, high=np.inf, shape=(376,), dtype=np.float64 ) else: observation_space = Box( low=-np.inf, high=np.inf, shape=(378,), dtype=np.float64 ) MujocoEnv.__init__( self, "humanoid.xml", 5, observation_space=observation_space, **kwargs ) @property def healthy_reward(self): return ( float(self.is_healthy or self._terminate_when_unhealthy) * self._healthy_reward ) def control_cost(self, action): control_cost = self._ctrl_cost_weight * np.sum(np.square(self.data.ctrl)) return control_cost @property def is_healthy(self): min_z, max_z = self._healthy_z_range is_healthy = min_z < self.data.qpos[2] < max_z return is_healthy @property def terminated(self): terminated = (not self.is_healthy) if self._terminate_when_unhealthy else False return terminated def _get_obs(self): position = self.data.qpos.flat.copy() velocity = self.data.qvel.flat.copy() com_inertia = self.data.cinert.flat.copy() com_velocity = self.data.cvel.flat.copy() actuator_forces = self.data.qfrc_actuator.flat.copy() external_contact_forces = self.data.cfrc_ext.flat.copy() if self._exclude_current_positions_from_observation: position = position[2:] return np.concatenate( ( position, velocity, com_inertia, com_velocity, actuator_forces, external_contact_forces, ) ) def step(self, action): xy_position_before = mass_center(self.model, self.data) self.do_simulation(action, self.frame_skip) xy_position_after = mass_center(self.model, self.data) xy_velocity = (xy_position_after - xy_position_before) / self.dt x_velocity, y_velocity = xy_velocity ctrl_cost = self.control_cost(action) forward_reward = self._forward_reward_weight * x_velocity healthy_reward = self.healthy_reward rewards = forward_reward + healthy_reward observation = self._get_obs() reward = rewards - ctrl_cost terminated = self.terminated info = { "reward_linvel": forward_reward, "reward_quadctrl": -ctrl_cost, "reward_alive": healthy_reward, "x_position": xy_position_after[0], "y_position": xy_position_after[1], "distance_from_origin": np.linalg.norm(xy_position_after, ord=2), "x_velocity": x_velocity, "y_velocity": y_velocity, "forward_reward": forward_reward, } if self.render_mode == "human": self.render() return observation, reward, terminated, False, info def reset_model(self): noise_low = -self._reset_noise_scale noise_high = self._reset_noise_scale qpos = self.init_qpos + self.np_random.uniform( low=noise_low, high=noise_high, size=self.model.nq ) qvel = self.init_qvel + self.np_random.uniform( low=noise_low, high=noise_high, size=self.model.nv ) self.set_state(qpos, qvel) observation = self._get_obs() return observation def viewer_setup(self): assert self.viewer is not None for key, value in DEFAULT_CAMERA_CONFIG.items(): if isinstance(value, np.ndarray): getattr(self.viewer.cam, key)[:] = value else: setattr(self.viewer.cam, key, value)
HumanoidEnv
python
matplotlib__matplotlib
lib/matplotlib/backends/_backend_gtk.py
{ "start": 3707, "end": 3777 }
class ____(FigureCanvasBase): _timer_cls = TimerGTK
_FigureCanvasGTK
python
getsentry__sentry
src/sentry/api/serializers/models/discoversavedquery.py
{ "start": 637, "end": 1018 }
class ____(TypedDict, total=False): environment: list[str] query: str fields: list[str] widths: list[str] conditions: list[str] aggregations: list[str] range: str start: str end: str orderby: str limit: str yAxis: list[str] display: str topEvents: int interval: str exploreQuery: dict
DiscoverSavedQueryResponseOptional
python
gevent__gevent
src/gevent/events.py
{ "start": 4732, "end": 5509 }
class ____(Interface): """ The contract for the periodic monitoring thread that is started by the hub. """ def add_monitoring_function(function, period): """ Schedule the *function* to be called approximately every *period* fractional seconds. The *function* receives one argument, the hub being monitored. It is called in the monitoring thread, *not* the hub thread. It **must not** attempt to use the gevent asynchronous API. If the *function* is already a monitoring function, then its *period* will be updated for future runs. If the *period* is ``None``, then the function will be removed. A *period* less than or equal to zero is not allowed. """
IPeriodicMonitorThread
python
sympy__sympy
sympy/combinatorics/free_groups.py
{ "start": 9552, "end": 39641 }
class ____(CantSympify, DefaultPrinting, tuple): """Used to create elements of FreeGroup. It cannot be used directly to create a free group element. It is called by the `dtype` method of the `FreeGroup` class. """ __slots__ = () is_assoc_word = True def new(self, init): return self.__class__(init) _hash = None def __hash__(self): _hash = self._hash if _hash is None: self._hash = _hash = hash((self.group, frozenset(tuple(self)))) return _hash def copy(self): return self.new(self) @property def is_identity(self): return not self.array_form @property def array_form(self): """ SymPy provides two different internal kinds of representation of associative words. The first one is called the `array_form` which is a tuple containing `tuples` as its elements, where the size of each tuple is two. At the first position the tuple contains the `symbol-generator`, while at the second position of tuple contains the exponent of that generator at the position. Since elements (i.e. words) do not commute, the indexing of tuple makes that property to stay. The structure in ``array_form`` of ``FreeGroupElement`` is of form: ``( ( symbol_of_gen, exponent ), ( , ), ... ( , ) )`` Examples ======== >>> from sympy.combinatorics import free_group >>> f, x, y, z = free_group("x y z") >>> (x*z).array_form ((x, 1), (z, 1)) >>> (x**2*z*y*x**2).array_form ((x, 2), (z, 1), (y, 1), (x, 2)) See Also ======== letter_repr """ return tuple(self) @property def letter_form(self): """ The letter representation of a ``FreeGroupElement`` is a tuple of generator symbols, with each entry corresponding to a group generator. Inverses of the generators are represented by negative generator symbols. Examples ======== >>> from sympy.combinatorics import free_group >>> f, a, b, c, d = free_group("a b c d") >>> (a**3).letter_form (a, a, a) >>> (a**2*d**-2*a*b**-4).letter_form (a, a, -d, -d, a, -b, -b, -b, -b) >>> (a**-2*b**3*d).letter_form (-a, -a, b, b, b, d) See Also ======== array_form """ return tuple(flatten([(i,)*j if j > 0 else (-i,)*(-j) for i, j in self.array_form])) def __getitem__(self, i): group = self.group r = self.letter_form[i] if r.is_Symbol: return group.dtype(((r, 1),)) else: return group.dtype(((-r, -1),)) def index(self, gen): if len(gen) != 1: raise ValueError() return (self.letter_form).index(gen.letter_form[0]) @property def letter_form_elm(self): """ """ group = self.group r = self.letter_form return [group.dtype(((elm,1),)) if elm.is_Symbol \ else group.dtype(((-elm,-1),)) for elm in r] @property def ext_rep(self): """This is called the External Representation of ``FreeGroupElement`` """ return tuple(flatten(self.array_form)) def __contains__(self, gen): return gen.array_form[0][0] in tuple([r[0] for r in self.array_form]) def __str__(self): if self.is_identity: return "<identity>" str_form = "" array_form = self.array_form for i in range(len(array_form)): if i == len(array_form) - 1: if array_form[i][1] == 1: str_form += str(array_form[i][0]) else: str_form += str(array_form[i][0]) + \ "**" + str(array_form[i][1]) else: if array_form[i][1] == 1: str_form += str(array_form[i][0]) + "*" else: str_form += str(array_form[i][0]) + \ "**" + str(array_form[i][1]) + "*" return str_form __repr__ = __str__ def __pow__(self, n): n = as_int(n) result = self.group.identity if n == 0: return result if n < 0: n = -n x = self.inverse() else: x = self while True: if n % 2: result *= x n >>= 1 if not n: break x *= x return result def __mul__(self, other): """Returns the product of elements belonging to the same ``FreeGroup``. Examples ======== >>> from sympy.combinatorics import free_group >>> f, x, y, z = free_group("x y z") >>> x*y**2*y**-4 x*y**-2 >>> z*y**-2 z*y**-2 >>> x**2*y*y**-1*x**-2 <identity> """ group = self.group if not isinstance(other, group.dtype): raise TypeError("only FreeGroup elements of same FreeGroup can " "be multiplied") if self.is_identity: return other if other.is_identity: return self r = list(self.array_form + other.array_form) zero_mul_simp(r, len(self.array_form) - 1) return group.dtype(tuple(r)) def __truediv__(self, other): group = self.group if not isinstance(other, group.dtype): raise TypeError("only FreeGroup elements of same FreeGroup can " "be multiplied") return self*(other.inverse()) def __rtruediv__(self, other): group = self.group if not isinstance(other, group.dtype): raise TypeError("only FreeGroup elements of same FreeGroup can " "be multiplied") return other*(self.inverse()) def __add__(self, other): return NotImplemented def inverse(self): """ Returns the inverse of a ``FreeGroupElement`` element Examples ======== >>> from sympy.combinatorics import free_group >>> f, x, y, z = free_group("x y z") >>> x.inverse() x**-1 >>> (x*y).inverse() y**-1*x**-1 """ group = self.group r = tuple([(i, -j) for i, j in self.array_form[::-1]]) return group.dtype(r) def order(self): """Find the order of a ``FreeGroupElement``. Examples ======== >>> from sympy.combinatorics import free_group >>> f, x, y = free_group("x y") >>> (x**2*y*y**-1*x**-2).order() 1 """ if self.is_identity: return S.One else: return S.Infinity def commutator(self, other): """ Return the commutator of `self` and `x`: ``~x*~self*x*self`` """ group = self.group if not isinstance(other, group.dtype): raise ValueError("commutator of only FreeGroupElement of the same " "FreeGroup exists") else: return self.inverse()*other.inverse()*self*other def eliminate_words(self, words, _all=False, inverse=True): ''' Replace each subword from the dictionary `words` by words[subword]. If words is a list, replace the words by the identity. ''' again = True new = self if isinstance(words, dict): while again: again = False for sub in words: prev = new new = new.eliminate_word(sub, words[sub], _all=_all, inverse=inverse) if new != prev: again = True else: while again: again = False for sub in words: prev = new new = new.eliminate_word(sub, _all=_all, inverse=inverse) if new != prev: again = True return new def eliminate_word(self, gen, by=None, _all=False, inverse=True): """ For an associative word `self`, a subword `gen`, and an associative word `by` (identity by default), return the associative word obtained by replacing each occurrence of `gen` in `self` by `by`. If `_all = True`, the occurrences of `gen` that may appear after the first substitution will also be replaced and so on until no occurrences are found. This might not always terminate (e.g. `(x).eliminate_word(x, x**2, _all=True)`). Examples ======== >>> from sympy.combinatorics import free_group >>> f, x, y = free_group("x y") >>> w = x**5*y*x**2*y**-4*x >>> w.eliminate_word( x, x**2 ) x**10*y*x**4*y**-4*x**2 >>> w.eliminate_word( x, y**-1 ) y**-11 >>> w.eliminate_word(x**5) y*x**2*y**-4*x >>> w.eliminate_word(x*y, y) x**4*y*x**2*y**-4*x See Also ======== substituted_word """ if by is None: by = self.group.identity if self.is_independent(gen) or gen == by: return self if gen == self: return by if gen**-1 == by: _all = False word = self l = len(gen) try: i = word.subword_index(gen) k = 1 except ValueError: if not inverse: return word try: i = word.subword_index(gen**-1) k = -1 except ValueError: return word word = word.subword(0, i)*by**k*word.subword(i+l, len(word)).eliminate_word(gen, by) if _all: return word.eliminate_word(gen, by, _all=True, inverse=inverse) else: return word def __len__(self): """ For an associative word `self`, returns the number of letters in it. Examples ======== >>> from sympy.combinatorics import free_group >>> f, a, b = free_group("a b") >>> w = a**5*b*a**2*b**-4*a >>> len(w) 13 >>> len(a**17) 17 >>> len(w**0) 0 """ return sum(abs(j) for (i, j) in self) def __eq__(self, other): """ Two associative words are equal if they are words over the same alphabet and if they are sequences of the same letters. This is equivalent to saying that the external representations of the words are equal. There is no "universal" empty word, every alphabet has its own empty word. Examples ======== >>> from sympy.combinatorics import free_group >>> f, swapnil0, swapnil1 = free_group("swapnil0 swapnil1") >>> f <free group on the generators (swapnil0, swapnil1)> >>> g, swap0, swap1 = free_group("swap0 swap1") >>> g <free group on the generators (swap0, swap1)> >>> swapnil0 == swapnil1 False >>> swapnil0*swapnil1 == swapnil1/swapnil1*swapnil0*swapnil1 True >>> swapnil0*swapnil1 == swapnil1*swapnil0 False >>> swapnil1**0 == swap0**0 False """ group = self.group if not isinstance(other, group.dtype): return False return tuple.__eq__(self, other) def __lt__(self, other): """ The ordering of associative words is defined by length and lexicography (this ordering is called short-lex ordering), that is, shorter words are smaller than longer words, and words of the same length are compared w.r.t. the lexicographical ordering induced by the ordering of generators. Generators are sorted according to the order in which they were created. If the generators are invertible then each generator `g` is larger than its inverse `g^{-1}`, and `g^{-1}` is larger than every generator that is smaller than `g`. Examples ======== >>> from sympy.combinatorics import free_group >>> f, a, b = free_group("a b") >>> b < a False >>> a < a.inverse() False """ group = self.group if not isinstance(other, group.dtype): raise TypeError("only FreeGroup elements of same FreeGroup can " "be compared") l = len(self) m = len(other) # implement lenlex order if l < m: return True elif l > m: return False for i in range(l): a = self[i].array_form[0] b = other[i].array_form[0] p = group.symbols.index(a[0]) q = group.symbols.index(b[0]) if p < q: return True elif p > q: return False elif a[1] < b[1]: return True elif a[1] > b[1]: return False return False def __le__(self, other): return (self == other or self < other) def __gt__(self, other): """ Examples ======== >>> from sympy.combinatorics import free_group >>> f, x, y, z = free_group("x y z") >>> y**2 > x**2 True >>> y*z > z*y False >>> x > x.inverse() True """ group = self.group if not isinstance(other, group.dtype): raise TypeError("only FreeGroup elements of same FreeGroup can " "be compared") return not self <= other def __ge__(self, other): return not self < other def exponent_sum(self, gen): """ For an associative word `self` and a generator or inverse of generator `gen`, ``exponent_sum`` returns the number of times `gen` appears in `self` minus the number of times its inverse appears in `self`. If neither `gen` nor its inverse occur in `self` then 0 is returned. Examples ======== >>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> w = x**2*y**3 >>> w.exponent_sum(x) 2 >>> w.exponent_sum(x**-1) -2 >>> w = x**2*y**4*x**-3 >>> w.exponent_sum(x) -1 See Also ======== generator_count """ if len(gen) != 1: raise ValueError("gen must be a generator or inverse of a generator") s = gen.array_form[0] return s[1]*sum(i[1] for i in self.array_form if i[0] == s[0]) def generator_count(self, gen): """ For an associative word `self` and a generator `gen`, ``generator_count`` returns the multiplicity of generator `gen` in `self`. Examples ======== >>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> w = x**2*y**3 >>> w.generator_count(x) 2 >>> w = x**2*y**4*x**-3 >>> w.generator_count(x) 5 See Also ======== exponent_sum """ if len(gen) != 1 or gen.array_form[0][1] < 0: raise ValueError("gen must be a generator") s = gen.array_form[0] return s[1]*sum(abs(i[1]) for i in self.array_form if i[0] == s[0]) def subword(self, from_i, to_j, strict=True): """ For an associative word `self` and two positive integers `from_i` and `to_j`, `subword` returns the subword of `self` that begins at position `from_i` and ends at `to_j - 1`, indexing is done with origin 0. Examples ======== >>> from sympy.combinatorics import free_group >>> f, a, b = free_group("a b") >>> w = a**5*b*a**2*b**-4*a >>> w.subword(2, 6) a**3*b """ group = self.group if not strict: from_i = max(from_i, 0) to_j = min(len(self), to_j) if from_i < 0 or to_j > len(self): raise ValueError("`from_i`, `to_j` must be positive and no greater than " "the length of associative word") if to_j <= from_i: return group.identity else: letter_form = self.letter_form[from_i: to_j] array_form = letter_form_to_array_form(letter_form, group) return group.dtype(array_form) def subword_index(self, word, start = 0): ''' Find the index of `word` in `self`. Examples ======== >>> from sympy.combinatorics import free_group >>> f, a, b = free_group("a b") >>> w = a**2*b*a*b**3 >>> w.subword_index(a*b*a*b) 1 ''' l = len(word) self_lf = self.letter_form word_lf = word.letter_form index = None for i in range(start,len(self_lf)-l+1): if self_lf[i:i+l] == word_lf: index = i break if index is not None: return index else: raise ValueError("The given word is not a subword of self") def is_dependent(self, word): """ Examples ======== >>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> (x**4*y**-3).is_dependent(x**4*y**-2) True >>> (x**2*y**-1).is_dependent(x*y) False >>> (x*y**2*x*y**2).is_dependent(x*y**2) True >>> (x**12).is_dependent(x**-4) True See Also ======== is_independent """ try: return self.subword_index(word) is not None except ValueError: pass try: return self.subword_index(word**-1) is not None except ValueError: return False def is_independent(self, word): """ See Also ======== is_dependent """ return not self.is_dependent(word) def contains_generators(self): """ Examples ======== >>> from sympy.combinatorics import free_group >>> F, x, y, z = free_group("x, y, z") >>> (x**2*y**-1).contains_generators() {x, y} >>> (x**3*z).contains_generators() {x, z} """ group = self.group gens = {group.dtype(((syllable[0], 1),)) for syllable in self.array_form} return gens def cyclic_subword(self, from_i, to_j): group = self.group l = len(self) letter_form = self.letter_form period1 = int(from_i/l) if from_i >= l: from_i -= l*period1 to_j -= l*period1 diff = to_j - from_i word = letter_form[from_i: to_j] period2 = int(to_j/l) - 1 word += letter_form*period2 + letter_form[:diff-l+from_i-l*period2] word = letter_form_to_array_form(word, group) return group.dtype(word) def cyclic_conjugates(self): """Returns a words which are cyclic to the word `self`. Examples ======== >>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> w = x*y*x*y*x >>> w.cyclic_conjugates() {x*y*x**2*y, x**2*y*x*y, y*x*y*x**2, y*x**2*y*x, x*y*x*y*x} >>> s = x*y*x**2*y*x >>> s.cyclic_conjugates() {x**2*y*x**2*y, y*x**2*y*x**2, x*y*x**2*y*x} References ========== .. [1] https://planetmath.org/cyclicpermutation """ return {self.cyclic_subword(i, i+len(self)) for i in range(len(self))} def is_cyclic_conjugate(self, w): """ Checks whether words ``self``, ``w`` are cyclic conjugates. Examples ======== >>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> w1 = x**2*y**5 >>> w2 = x*y**5*x >>> w1.is_cyclic_conjugate(w2) True >>> w3 = x**-1*y**5*x**-1 >>> w3.is_cyclic_conjugate(w2) False """ l1 = len(self) l2 = len(w) if l1 != l2: return False w1 = self.identity_cyclic_reduction() w2 = w.identity_cyclic_reduction() letter1 = w1.letter_form letter2 = w2.letter_form str1 = ' '.join(map(str, letter1)) str2 = ' '.join(map(str, letter2)) if len(str1) != len(str2): return False return str1 in str2 + ' ' + str2 def number_syllables(self): """Returns the number of syllables of the associative word `self`. Examples ======== >>> from sympy.combinatorics import free_group >>> f, swapnil0, swapnil1 = free_group("swapnil0 swapnil1") >>> (swapnil1**3*swapnil0*swapnil1**-1).number_syllables() 3 """ return len(self.array_form) def exponent_syllable(self, i): """ Returns the exponent of the `i`-th syllable of the associative word `self`. Examples ======== >>> from sympy.combinatorics import free_group >>> f, a, b = free_group("a b") >>> w = a**5*b*a**2*b**-4*a >>> w.exponent_syllable( 2 ) 2 """ return self.array_form[i][1] def generator_syllable(self, i): """ Returns the symbol of the generator that is involved in the i-th syllable of the associative word `self`. Examples ======== >>> from sympy.combinatorics import free_group >>> f, a, b = free_group("a b") >>> w = a**5*b*a**2*b**-4*a >>> w.generator_syllable( 3 ) b """ return self.array_form[i][0] def sub_syllables(self, from_i, to_j): """ `sub_syllables` returns the subword of the associative word `self` that consists of syllables from positions `from_to` to `to_j`, where `from_to` and `to_j` must be positive integers and indexing is done with origin 0. Examples ======== >>> from sympy.combinatorics import free_group >>> f, a, b = free_group("a, b") >>> w = a**5*b*a**2*b**-4*a >>> w.sub_syllables(1, 2) b >>> w.sub_syllables(3, 3) <identity> """ if not isinstance(from_i, int) or not isinstance(to_j, int): raise ValueError("both arguments should be integers") group = self.group if to_j <= from_i: return group.identity else: r = tuple(self.array_form[from_i: to_j]) return group.dtype(r) def substituted_word(self, from_i, to_j, by): """ Returns the associative word obtained by replacing the subword of `self` that begins at position `from_i` and ends at position `to_j - 1` by the associative word `by`. `from_i` and `to_j` must be positive integers, indexing is done with origin 0. In other words, `w.substituted_word(w, from_i, to_j, by)` is the product of the three words: `w.subword(0, from_i)`, `by`, and `w.subword(to_j len(w))`. See Also ======== eliminate_word """ lw = len(self) if from_i >= to_j or from_i > lw or to_j > lw: raise ValueError("values should be within bounds") # otherwise there are four possibilities # first if from=1 and to=lw then if from_i == 0 and to_j == lw: return by elif from_i == 0: # second if from_i=1 (and to_j < lw) then return by*self.subword(to_j, lw) elif to_j == lw: # third if to_j=1 (and from_i > 1) then return self.subword(0, from_i)*by else: # finally return self.subword(0, from_i)*by*self.subword(to_j, lw) def is_cyclically_reduced(self): r"""Returns whether the word is cyclically reduced or not. A word is cyclically reduced if by forming the cycle of the word, the word is not reduced, i.e a word w = `a_1 ... a_n` is called cyclically reduced if `a_1 \ne a_n^{-1}`. Examples ======== >>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> (x**2*y**-1*x**-1).is_cyclically_reduced() False >>> (y*x**2*y**2).is_cyclically_reduced() True """ if not self: return True return self[0] != self[-1]**-1 def identity_cyclic_reduction(self): """Return a unique cyclically reduced version of the word. Examples ======== >>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> (x**2*y**2*x**-1).identity_cyclic_reduction() x*y**2 >>> (x**-3*y**-1*x**5).identity_cyclic_reduction() x**2*y**-1 References ========== .. [1] https://planetmath.org/cyclicallyreduced """ word = self.copy() group = self.group while not word.is_cyclically_reduced(): exp1 = word.exponent_syllable(0) exp2 = word.exponent_syllable(-1) r = exp1 + exp2 if r == 0: rep = word.array_form[1: word.number_syllables() - 1] else: rep = ((word.generator_syllable(0), exp1 + exp2),) + \ word.array_form[1: word.number_syllables() - 1] word = group.dtype(rep) return word def cyclic_reduction(self, removed=False): """Return a cyclically reduced version of the word. Unlike `identity_cyclic_reduction`, this will not cyclically permute the reduced word - just remove the "unreduced" bits on either side of it. Compare the examples with those of `identity_cyclic_reduction`. When `removed` is `True`, return a tuple `(word, r)` where self `r` is such that before the reduction the word was either `r*word*r**-1`. Examples ======== >>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> (x**2*y**2*x**-1).cyclic_reduction() x*y**2 >>> (x**-3*y**-1*x**5).cyclic_reduction() y**-1*x**2 >>> (x**-3*y**-1*x**5).cyclic_reduction(removed=True) (y**-1*x**2, x**-3) """ word = self.copy() g = self.group.identity while not word.is_cyclically_reduced(): exp1 = abs(word.exponent_syllable(0)) exp2 = abs(word.exponent_syllable(-1)) exp = min(exp1, exp2) start = word[0]**abs(exp) end = word[-1]**abs(exp) word = start**-1*word*end**-1 g = g*start if removed: return word, g return word def power_of(self, other): ''' Check if `self == other**n` for some integer n. Examples ======== >>> from sympy.combinatorics import free_group >>> F, x, y = free_group("x, y") >>> ((x*y)**2).power_of(x*y) True >>> (x**-3*y**-2*x**3).power_of(x**-3*y*x**3) True ''' if self.is_identity: return True l = len(other) if l == 1: # self has to be a power of one generator gens = self.contains_generators() s = other in gens or other**-1 in gens return len(gens) == 1 and s # if self is not cyclically reduced and it is a power of other, # other isn't cyclically reduced and the parts removed during # their reduction must be equal reduced, r1 = self.cyclic_reduction(removed=True) if not r1.is_identity: other, r2 = other.cyclic_reduction(removed=True) if r1 == r2: return reduced.power_of(other) return False if len(self) < l or len(self) % l: return False prefix = self.subword(0, l) if prefix == other or prefix**-1 == other: rest = self.subword(l, len(self)) return rest.power_of(other) return False def letter_form_to_array_form(array_form, group): """ This method converts a list given with possible repetitions of elements in it. It returns a new list such that repetitions of consecutive elements is removed and replace with a tuple element of size two such that the first index contains `value` and the second index contains the number of consecutive repetitions of `value`. """ a = list(array_form[:]) new_array = [] n = 1 symbols = group.symbols for i in range(len(a)): if i == len(a) - 1: if a[i] == a[i - 1]: if (-a[i]) in symbols: new_array.append((-a[i], -n)) else: new_array.append((a[i], n)) else: if (-a[i]) in symbols: new_array.append((-a[i], -1)) else: new_array.append((a[i], 1)) return new_array elif a[i] == a[i + 1]: n += 1 else: if (-a[i]) in symbols: new_array.append((-a[i], -n)) else: new_array.append((a[i], n)) n = 1 def zero_mul_simp(l, index): """Used to combine two reduced words.""" while index >=0 and index < len(l) - 1 and l[index][0] == l[index + 1][0]: exp = l[index][1] + l[index + 1][1] base = l[index][0] l[index] = (base, exp) del l[index + 1] if l[index][1] == 0: del l[index] index -= 1
FreeGroupElement
python
anthropics__anthropic-sdk-python
src/anthropic/types/thinking_config_enabled_param.py
{ "start": 226, "end": 724 }
class ____(TypedDict, total=False): budget_tokens: Required[int] """Determines how many tokens Claude can use for its internal reasoning process. Larger budgets can enable more thorough analysis for complex problems, improving response quality. Must be ≥1024 and less than `max_tokens`. See [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details. """ type: Required[Literal["enabled"]]
ThinkingConfigEnabledParam
python
gevent__gevent
src/greentest/3.14/test_socketserver.py
{ "start": 15877, "end": 17812 }
class ____(unittest.TestCase): def test_all(self): # objects defined in the module should be in __all__ expected = [] for name in dir(socketserver): if not name.startswith('_'): mod_object = getattr(socketserver, name) if getattr(mod_object, '__module__', None) == 'socketserver': expected.append(name) self.assertCountEqual(socketserver.__all__, expected) def test_shutdown_request_called_if_verify_request_false(self): # Issue #26309: BaseServer should call shutdown_request even if # verify_request is False class MyServer(socketserver.TCPServer): def verify_request(self, request, client_address): return False shutdown_called = 0 def shutdown_request(self, request): self.shutdown_called += 1 socketserver.TCPServer.shutdown_request(self, request) server = MyServer((HOST, 0), socketserver.StreamRequestHandler) s = socket.socket(server.address_family, socket.SOCK_STREAM) s.connect(server.server_address) s.close() server.handle_request() self.assertEqual(server.shutdown_called, 1) server.server_close() def test_threads_reaped(self): """ In #37193, users reported a memory leak due to the saving of every request thread. Ensure that not all threads are kept forever. """ class MyServer(socketserver.ThreadingMixIn, socketserver.TCPServer): pass server = MyServer((HOST, 0), socketserver.StreamRequestHandler) for n in range(10): with socket.create_connection(server.server_address): server.handle_request() self.assertLess(len(server._threads), 10) server.server_close() if __name__ == "__main__": unittest.main()
MiscTestCase
python
kamyu104__LeetCode-Solutions
Python/out-of-boundary-paths.py
{ "start": 41, "end": 906 }
class ____(object): def findPaths(self, m, n, N, x, y): """ :type m: int :type n: int :type N: int :type x: int :type y: int :rtype: int """ M = 1000000000 + 7 dp = [[[0 for _ in xrange(n)] for _ in xrange(m)] for _ in xrange(2)] for moves in xrange(N): for i in xrange(m): for j in xrange(n): dp[(moves + 1) % 2][i][j] = (((1 if (i == 0) else dp[moves % 2][i - 1][j]) + \ (1 if (i == m - 1) else dp[moves % 2][i + 1][j])) % M + \ ((1 if (j == 0) else dp[moves % 2][i][j - 1]) + \ (1 if (j == n - 1) else dp[moves % 2][i][j + 1])) % M) % M return dp[N % 2][x][y]
Solution
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_multiple_wrapping.py
{ "start": 877, "end": 1102 }
class ____(Module): def __init__(self, device): super().__init__() self.layers = Sequential(FSDP(Linear(5, 5), device_id=device_type.type)) def forward(self, x): return self.layers(x)
InnerModel
python
great-expectations__great_expectations
great_expectations/expectations/core/expect_column_proportion_of_unique_values_to_be_between.py
{ "start": 2723, "end": 17972 }
class ____(ColumnAggregateExpectation): __doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION} For example, in a column containing [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], there are 4 unique values and 10 total \ values for a proportion of 0.4. ExpectColumnProportionOfUniqueValuesToBeBetween is a \ Column Aggregate Expectation. Column Aggregate Expectations are one of the most common types of Expectation. They are evaluated for a single column, and produce an aggregate Metric, such as a mean, standard deviation, number of unique values, column type, etc. If that Metric meets the conditions you set, the Expectation considers that data valid. Args: column (str): \ {COLUMN_DESCRIPTION} min_value (float or None): \ {MIN_VALUE_DESCRIPTION} max_value (float or None): \ {MAX_VALUE_DESCRIPTION} strict_min (boolean): \ {STRICT_MIN_DESCRIPTION} default=False strict_max (boolean): \ {STRICT_MAX_DESCRIPTION} default=False Other Parameters: result_format (str or None): \ Which output mode to use: BOOLEAN_ONLY, BASIC, COMPLETE, or SUMMARY. \ For more detail, see [result_format](https://docs.greatexpectations.io/docs/reference/expectations/result_format). catch_exceptions (boolean or None): \ If True, then catch exceptions and include them as part of the result object. \ For more detail, see [catch_exceptions](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#catch_exceptions). meta (dict or None): \ A JSON-serializable dictionary (nesting allowed) that will be included in the output without \ modification. For more detail, see [meta](https://docs.greatexpectations.io/docs/reference/expectations/standard_arguments/#meta). severity (str or None): \ {FAILURE_SEVERITY_DESCRIPTION} \ For more detail, see [failure severity](https://docs.greatexpectations.io/docs/cloud/expectations/expectations_overview/#failure-severity). Returns: An [ExpectationSuiteValidationResult](https://docs.greatexpectations.io/docs/terms/validation_result) Exact fields vary depending on the values passed to result_format, catch_exceptions, and meta. Notes: * min_value and max_value are both inclusive unless strict_min or strict_max are set to True. * If min_value is None, then max_value is treated as an upper bound * If max_value is None, then min_value is treated as a lower bound * observed_value field in the result object is customized for this expectation to be a float \ representing the proportion of unique values in the column See Also: [ExpectColumnUniqueValueCountToBeBetween](https://greatexpectations.io/expectations/expect_column_unique_value_count_to_be_between) Supported Data Sources: [{SUPPORTED_DATA_SOURCES[0]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[1]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[2]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[3]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[4]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[5]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[6]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[7]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[8]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[9]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[10]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[11]}](https://docs.greatexpectations.io/docs/application_integration_support/) [{SUPPORTED_DATA_SOURCES[12]}](https://docs.greatexpectations.io/docs/application_integration_support/) Data Quality Issues: {DATA_QUALITY_ISSUES[0]} Example Data: test test2 0 "aaa" 1 1 "abb" 1 2 "acc" 1 3 "aaa" 3 Code Examples: Passing Case: Input: ExpectColumnProportionOfUniqueValuesToBeBetween( column="test", min_value=0, max_value=0.8 ) Output: {{ "exception_info": {{ "raised_exception": false, "exception_traceback": null, "exception_message": null }}, "result": {{ "observed_value": .75 }}, "meta": {{}}, "success": true }} Failing Case: Input: ExpectColumnProportionOfUniqueValuesToBeBetween( column="test2", min_value=0.3, max_value=0.5, strict_min=False, strict_max=True ) Output: {{ "exception_info": {{ "raised_exception": false, "exception_traceback": null, "exception_message": null }}, "result": {{ "observed_value": .5 }}, "meta": {{}}, "success": false }} """ # noqa: E501 # FIXME CoP min_value: Optional[Union[float, SuiteParameterDict]] = pydantic.Field( default=None, description=MIN_VALUE_DESCRIPTION ) max_value: Optional[Union[float, SuiteParameterDict]] = pydantic.Field( default=None, description=MAX_VALUE_DESCRIPTION ) strict_min: Union[bool, SuiteParameterDict] = pydantic.Field( default=False, description=STRICT_MIN_DESCRIPTION ) strict_max: Union[bool, SuiteParameterDict] = pydantic.Field( default=False, description=STRICT_MAX_DESCRIPTION ) # This dictionary contains metadata for display in the public gallery library_metadata = { "maturity": "production", "tags": ["core expectation", "column aggregate expectation"], "contributors": ["@great_expectations"], "requirements": [], "has_full_test_suite": True, "manually_reviewed_code": True, } _library_metadata = library_metadata # Setting necessary computation metric dependencies and defining kwargs, as well as assigning kwargs default values\ # noqa: E501 # FIXME CoP metric_dependencies = ("column.unique_proportion",) success_keys = ( "min_value", "strict_min", "max_value", "strict_max", ) args_keys = ( "column", "min_value", "max_value", "strict_min", "strict_max", ) """ A Column Aggregate MetricProvider Decorator for the Unique Proportion""" class Config: title = "Expect column proportion of unique values to be between" @staticmethod def schema_extra( schema: Dict[str, Any], model: Type[ExpectColumnProportionOfUniqueValuesToBeBetween] ) -> None: ColumnAggregateExpectation.Config.schema_extra(schema, model) schema["properties"]["metadata"]["properties"].update( { "data_quality_issues": { "title": "Data Quality Issues", "type": "array", "const": DATA_QUALITY_ISSUES, }, "library_metadata": { "title": "Library Metadata", "type": "object", "const": model._library_metadata, }, "short_description": { "title": "Short Description", "type": "string", "const": EXPECTATION_SHORT_DESCRIPTION, }, "supported_data_sources": { "title": "Supported Data Sources", "type": "array", "const": SUPPORTED_DATA_SOURCES, }, } ) @classmethod def _prescriptive_template( # noqa: C901 # too complex cls, renderer_configuration: RendererConfiguration, ) -> RendererConfiguration: add_param_args: AddParamArgs = ( ("column", RendererValueType.STRING), ("min_value", [RendererValueType.NUMBER, RendererValueType.DATETIME]), ("max_value", [RendererValueType.NUMBER, RendererValueType.DATETIME]), ("strict_min", RendererValueType.BOOLEAN), ("strict_max", RendererValueType.BOOLEAN), ) for name, param_type in add_param_args: renderer_configuration.add_param(name=name, param_type=param_type) params = renderer_configuration.params if not params.min_value and not params.max_value: template_str = "may have any proportion of unique values." else: at_least_str = "greater than or equal to" if params.strict_min: at_least_str = cls._get_strict_min_string( renderer_configuration=renderer_configuration ) at_most_str = "less than or equal to" if params.strict_max: at_most_str = cls._get_strict_max_string( renderer_configuration=renderer_configuration ) if not params.min_value: template_str = f"proportion of unique values must be {at_most_str} $max_value." elif not params.max_value: template_str = f"proportion of unique values must be {at_least_str} $min_value." else: # noqa: PLR5501 # FIXME CoP if params.min_value.value != params.max_value.value: template_str = f"proportion of unique values must be {at_least_str} $min_value and {at_most_str} $max_value." # noqa: E501 # FIXME CoP else: template_str = "proportion of unique values must be exactly $min_value." if renderer_configuration.include_column_name: template_str = f"$column {template_str}" renderer_configuration.template_str = template_str return renderer_configuration @classmethod @renderer(renderer_type=LegacyRendererType.PRESCRIPTIVE) @render_suite_parameter_string def _prescriptive_renderer( cls, configuration: Optional[ExpectationConfiguration] = None, result: Optional[ExpectationValidationResult] = None, runtime_configuration: Optional[dict] = None, **kwargs, ): runtime_configuration = runtime_configuration or {} include_column_name = runtime_configuration.get("include_column_name") is not False styling = runtime_configuration.get("styling") params = substitute_none_for_missing( configuration.kwargs, [ "column", "min_value", "max_value", "row_condition", "condition_parser", "strict_min", "strict_max", ], ) if params["min_value"] is None and params["max_value"] is None: template_str = "may have any proportion of unique values." else: at_least_str, at_most_str = handle_strict_min_max(params) if params["min_value"] is None: template_str = f"proportion of unique values must be {at_most_str} $max_value." elif params["max_value"] is None: template_str = f"proportion of unique values must be {at_least_str} $min_value." else: # noqa: PLR5501 # FIXME CoP if params["min_value"] != params["max_value"]: template_str = f"proportion of unique values must be {at_least_str} $min_value and {at_most_str} $max_value." # noqa: E501 # FIXME CoP else: template_str = "proportion of unique values must be exactly $min_value." if include_column_name: template_str = f"$column {template_str}" if params["row_condition"] is not None: conditional_template_str = parse_row_condition_string(params["row_condition"]) template_str, styling = _style_row_condition( conditional_template_str, template_str, params, styling, ) return [ RenderedStringTemplateContent( **{ "content_block_type": "string_template", "string_template": { "template": template_str, "params": params, "styling": styling, }, } ) ] @classmethod @renderer( renderer_type=LegacyDescriptiveRendererType.COLUMN_PROPERTIES_TABLE_DISTINCT_PERCENT_ROW ) def _descriptive_column_properties_table_distinct_percent_row_renderer( cls, configuration: Optional[ExpectationConfiguration] = None, result: Optional[ExpectationValidationResult] = None, runtime_configuration: Optional[dict] = None, **kwargs, ): assert result, "Must pass in result." observed_value = result.result["observed_value"] template_string_object = RenderedStringTemplateContent( **{ "content_block_type": "string_template", "string_template": { "template": "Distinct (%)", "tooltip": { "content": "expect_column_proportion_of_unique_values_to_be_between" }, }, } ) if not observed_value: return [template_string_object, "--"] else: return [template_string_object, f"{100 * observed_value:.1f}%"] def _validate( self, metrics: Dict, runtime_configuration: Optional[dict] = None, execution_engine: Optional[ExecutionEngine] = None, ): return self._validate_metric_value_between( metric_name="column.unique_proportion", metrics=metrics, runtime_configuration=runtime_configuration, execution_engine=execution_engine, )
ExpectColumnProportionOfUniqueValuesToBeBetween
python
django__django
django/contrib/gis/gdal/raster/band.py
{ "start": 7836, "end": 8343 }
class ____(list): def __init__(self, source): self.source = source super().__init__() def __iter__(self): for idx in range(1, len(self) + 1): yield GDALBand(self.source, idx) def __len__(self): return capi.get_ds_raster_count(self.source._ptr) def __getitem__(self, index): try: return GDALBand(self.source, index + 1) except GDALException: raise GDALException("Unable to get band index %d" % index)
BandList
python
kamyu104__LeetCode-Solutions
Python/longest-common-subpath.py
{ "start": 37, "end": 1542 }
class ____(object): def longestCommonSubpath(self, n, paths): """ :type n: int :type paths: List[List[int]] :rtype: int """ def RabinKarp(arr, x): # double hashing hashes = tuple([reduce(lambda h,x: (h*p+x)%MOD, (arr[i] for i in xrange(x)), 0) for p in P]) powers = [pow(p, x, MOD) for p in P] lookup = {hashes} for i in xrange(x, len(arr)): hashes = tuple([(hashes[j]*P[j] - arr[i-x]*powers[j] + arr[i])%MOD for j in xrange(len(P))]) # in smaller datasets, tuple from list is much faster than tuple from generator, see https://stackoverflow.com/questions/16940293/why-is-there-no-tuple-comprehension-in-python lookup.add(hashes) return lookup def check(paths, x): intersect = RabinKarp(paths[0], x) for i in xrange(1, len(paths)): intersect = set.intersection(intersect, RabinKarp(paths[i], x)) if not intersect: return False return True MOD, P = 10**9+7, (113, 109) # MOD could be the min prime of 7-digit number (10**6+3), P could be (2, 3) left, right = 1, min(len(p) for p in paths) while left <= right: mid = left + (right-left)//2 if not check(paths, mid): right = mid-1 else: left = mid+1 return right # Time: O(m * nlogn) # Space: O(n)
Solution
python
google__flatbuffers
tests/monster_test_generated.py
{ "start": 14302, "end": 15353 }
class ____(object): __slots__ = ['_tab'] @classmethod def SizeOf(cls): return 20 # StructOfStructs def Init(self, buf, pos): self._tab = flatbuffers.table.Table(buf, pos) # StructOfStructs def A(self, obj): obj.Init(self._tab.Bytes, self._tab.Pos + 0) return obj # StructOfStructs def B(self, obj): obj.Init(self._tab.Bytes, self._tab.Pos + 8) return obj # StructOfStructs def C(self, obj): obj.Init(self._tab.Bytes, self._tab.Pos + 12) return obj def CreateStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance): builder.Prep(4, 20) builder.Prep(4, 8) builder.PrependUint32(c_distance) builder.PrependUint32(c_id) builder.Prep(2, 4) builder.Pad(1) builder.PrependInt8(b_b) builder.PrependInt16(b_a) builder.Prep(4, 8) builder.PrependUint32(a_distance) builder.PrependUint32(a_id) return builder.Offset() try: from typing import Optional except: pass
StructOfStructs
python
nedbat__coveragepy
tests/test_python.py
{ "start": 2174, "end": 2914 }
class ____(CoverageTest): """Tests using runpy.""" @pytest.mark.parametrize("convert_to", ["str", "Path"]) def test_runpy_path(self, convert_to: str) -> None: # Ensure runpy.run_path(path) works when path is pathlib.Path or str. # # runpy.run_path(pathlib.Path(...)) causes __file__ to be a Path, # which may make source_for_file() stumble (#1819) with: # # AttributeError: 'PosixPath' object has no attribute 'endswith' self.check_coverage(f"""\ import runpy from pathlib import Path pyfile = Path('script.py') pyfile.write_text('', encoding='utf-8') runpy.run_path({convert_to}(pyfile)) """)
RunpyTest
python
dask__distributed
distributed/tests/test_client.py
{ "start": 142136, "end": 175729 }
class ____: def __getstate__(self): return 1 def __dask_tokenize__(self): return uuid.uuid4().hex def __setstate__(self, state): raise MyException("hello") def __call__(self): return 1 @gen_cluster(client=True) async def test_robust_undeserializable(c, s, a, b): future = c.submit(identity, BrokenSetState()) await wait(future) assert future.status == "error" with raises_with_cause(RuntimeError, "deserialization", MyException, "hello"): await future futures = c.map(inc, range(10)) results = await c.gather(futures) assert results == list(map(inc, range(10))) assert a.data and b.data @gen_cluster(client=True) async def test_robust_undeserializable_function(c, s, a, b): future = c.submit(BrokenSetState(), 1) await wait(future) assert future.status == "error" with raises_with_cause(RuntimeError, "deserialization", MyException, "hello"): await future futures = c.map(inc, range(10)) results = await c.gather(futures) assert results == list(map(inc, range(10))) assert a.data and b.data @gen_cluster(client=True) async def test_fire_and_forget(c, s, a, b): future = c.submit(slowinc, 1, delay=0.1) import distributed def f(x): distributed.foo = 123 try: fire_and_forget(c.submit(f, future)) while not hasattr(distributed, "foo"): await asyncio.sleep(0.01) assert distributed.foo == 123 finally: del distributed.foo while len(s.tasks) > 1: await asyncio.sleep(0.01) assert set(s.tasks) == {future.key} assert s.tasks[future.key].who_wants @gen_cluster(client=True) async def test_fire_and_forget_err(c, s, a, b): fire_and_forget(c.submit(div, 1, 0)) await asyncio.sleep(0.1) # erred task should clear out quickly start = time() while s.tasks: await asyncio.sleep(0.01) assert time() < start + 1 def test_quiet_client_close(loop): with captured_logger("distributed") as logger: with Client( loop=loop, processes=False, dashboard_address=":0", threads_per_worker=4, ) as c: futures = c.map(slowinc, range(1000), delay=0.01) # Stop part-way s = c.cluster.scheduler while sum(ts.state == "memory" for ts in list(s.tasks.values())) < 20: sleep(0.01) sleep(0.1) # let things settle out = logger.getvalue() lines = out.strip().split("\n") unexpected_lines = [ line for line in lines if line and "heartbeat from unregistered worker" not in line and "unaware of this worker" not in line and "garbage" not in line and "ended with CancelledError" not in line and set(line) != {"-"} ] assert not unexpected_lines, lines @pytest.mark.slow def test_quiet_client_close_when_cluster_is_closed_before_client(loop): with captured_logger("tornado.application") as logger: cluster = LocalCluster(loop=loop, n_workers=1, dashboard_address=":0") client = Client(cluster, loop=loop) cluster.close() client.close() out = logger.getvalue() assert "CancelledError" not in out @gen_cluster() async def test_close(s, a, b): async with Client(s.address, asynchronous=True) as c: future = c.submit(inc, 1) await wait(future) assert c.id in s.clients await c.close() while c.id in s.clients or s.tasks: await asyncio.sleep(0.01) def test_threadsafe(c): def f(_): d = deque(maxlen=50) for _ in range(100): future = c.submit(inc, random.randint(0, 100)) d.append(future) sleep(0.001) c.gather(list(d)) total = c.submit(sum, list(d)) return total.result() from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(20) as e: results = list(e.map(f, range(20))) assert results and all(results) del results @pytest.mark.slow def test_threadsafe_get(c): pytest.importorskip("numpy") da = pytest.importorskip("dask.array") x = da.arange(100, chunks=(10,)) def f(_): total = 0 for _ in range(20): total += (x + random.randint(0, 20)).sum().compute() sleep(0.001) return total from concurrent.futures import ThreadPoolExecutor with ThreadPoolExecutor(30) as e: results = list(e.map(f, range(30))) assert results and all(results) @pytest.mark.slow def test_threadsafe_compute(c): pytest.importorskip("numpy") da = pytest.importorskip("dask.array") x = da.arange(100, chunks=(10,)) def f(_): total = 0 for _ in range(20): future = c.compute((x + random.randint(0, 20)).sum()) total += future.result() sleep(0.001) return total from concurrent.futures import ThreadPoolExecutor e = ThreadPoolExecutor(30) results = list(e.map(f, range(30))) assert results and all(results) @gen_cluster(client=True) async def test_identity(c, s, a, b): assert c.id.lower().startswith("client") assert a.id.lower().startswith("worker") assert b.id.lower().startswith("worker") assert s.id.lower().startswith("scheduler") @gen_cluster(client=True, nthreads=[("127.0.0.1", 4)] * 2) async def test_get_client(c, s, a, b): assert get_client() is c assert c.asynchronous def f(x): import distributed client = get_client() assert not client.asynchronous assert client is distributed.tmp_client future = client.submit(inc, x) return future.result() import distributed distributed.tmp_client = c try: futures = c.map(f, range(5)) results = await c.gather(futures) assert results == list(map(inc, range(5))) finally: del distributed.tmp_client def test_get_client_no_cluster(): # Clean up any global workers added by other tests. This test requires that # there are no global workers. Worker._instances.clear() msg = "No global client found and no address provided" with pytest.raises(ValueError, match=rf"^{msg}$"): get_client() @gen_cluster(client=True) async def test_serialize_collections(c, s, a, b): pytest.importorskip("numpy") da = pytest.importorskip("dask.array") x = c.persist(da.arange(10, chunks=(5,))) def f(x): assert isinstance(x, da.Array) return x.sum().compute() future = c.submit(f, x) result = await future assert result == sum(range(10)) @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)] * 1) async def test_secede_simple(c, s, a): def f(): client = get_client() secede() return client.submit(inc, 1).result() result = await c.submit(f) assert result == 2 @gen_cluster(client=True) async def test_secede_balances(c, s, a, b): """Ensure that tasks scheduled from a seceded thread can be scheduled elsewhere""" def f(x): client = get_client() secede() futures = client.map(inc, range(10), pure=False) total = client.submit(sum, futures).result() return total futures = c.map(f, range(10), workers=[a.address]) results = await c.gather(futures) # We dispatch 10 tasks and every task generates 11 more tasks # 10 * 11 + 10 assert a.state.executed_count + b.state.executed_count == 120 assert a.state.executed_count >= 10 assert b.state.executed_count > 0 assert results == [sum(map(inc, range(10)))] * 10 @pytest.mark.parametrize("raise_exception", [True, False]) @gen_cluster(client=True, nthreads=[("", 1)]) async def test_long_running_not_in_occupancy(c, s, a, raise_exception): # https://github.com/dask/distributed/issues/5332 # See also test_long_running_removal_clean l = Lock() entered = Event() await l.acquire() def long_running(lock, entered): entered.set() secede() lock.acquire() if raise_exception: raise RuntimeError("Exception in task") f = c.submit(long_running, l, entered) await entered.wait() ts = s.tasks[f.key] ws = s.workers[a.address] assert ws.occupancy == parse_timedelta( dask.config.get("distributed.scheduler.unknown-task-duration") ) while ws.occupancy: await asyncio.sleep(0.01) await a.heartbeat() assert s.workers[a.address].occupancy == 0 assert s.total_occupancy == 0 assert ws.occupancy == 0 await l.release() with ( pytest.raises(RuntimeError, match="Exception in task") if raise_exception else nullcontext() ): await f assert s.total_occupancy == 0 assert ws.occupancy == 0 assert not ws.long_running @pytest.mark.parametrize("ordinary_task", [True, False]) @gen_cluster(client=True, nthreads=[("", 1)]) async def test_long_running_removal_clean(c, s, a, ordinary_task): # https://github.com/dask/distributed/issues/5975 which could reduce # occupancy to negative values upon finishing long running tasks # See also test_long_running_not_in_occupancy l = Lock() entered = Event() l2 = Lock() entered2 = Event() await l.acquire() await l2.acquire() def long_running_secede(lock, entered): entered.set() secede() lock.acquire() def long_running(lock, entered): entered.set() lock.acquire() f = c.submit(long_running_secede, l, entered) await entered.wait() if ordinary_task: f2 = c.submit(long_running, l2, entered2) await entered2.wait() await l.release() await f ws = s.workers[a.address] if ordinary_task: # Should be exactly 0.5 but if for whatever reason this test runs slow, # some approximation may kick in increasing this number assert s.total_occupancy >= 0.5 assert ws.occupancy >= 0.5 await l2.release() await f2 # In the end, everything should be reset assert s.total_occupancy == 0 assert ws.occupancy == 0 assert not ws.long_running @gen_cluster(client=True) async def test_sub_submit_priority(c, s, a, b): def func(): client = get_client() f = client.submit(slowinc, 1, delay=0.5, key="slowinc") client.gather(f) future = c.submit(func, key="f") while len(s.tasks) != 2: await asyncio.sleep(0.001) # lower values schedule first assert s.tasks["f"].priority > s.tasks["slowinc"].priority, ( s.tasks["f"].priority, s.tasks["slowinc"].priority, ) def test_get_client_sync(c, s, a, b): for w in [a, b]: assert ( c.submit( lambda: get_worker().scheduler.address, workers=[w["address"]] ).result() == s["address"] ) assert ( c.submit( lambda: get_client().scheduler.address, workers=[w["address"]] ).result() == s["address"] ) @gen_cluster(client=True) async def test_serialize_collections_of_futures(c, s, a, b): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") from dask.dataframe.utils import assert_eq df = pd.DataFrame({"x": [1, 2, 3]}) ddf = c.persist(dd.from_pandas(df, npartitions=2)) future = await c.scatter(ddf) ddf2 = await future df2 = await c.compute(ddf2) assert_eq(df, df2) def test_serialize_collections_of_futures_sync(c): pd = pytest.importorskip("pandas") dd = pytest.importorskip("dask.dataframe") from dask.dataframe.utils import assert_eq df = pd.DataFrame({"x": [1, 2, 3]}) ddf = dd.from_pandas(df, npartitions=2).persist() future = c.scatter(ddf) result = future.result() assert_eq(result.compute(), df) assert future.type == dd.DataFrame assert c.submit(lambda x, y: assert_eq(x.compute(), y), future, df).result() def _dynamic_workload(x, delay=0.01): if delay == "random": sleep(random.random() / 2) else: sleep(delay) if x > 4: return 4 secede() client = get_client() futures = client.map( _dynamic_workload, [x + i + 1 for i in range(2)], pure=False, delay=delay ) total = client.submit(sum, futures) return total.result() def test_dynamic_workloads_sync(c): future = c.submit(_dynamic_workload, 0, delay=0.02) assert future.result(timeout=20) == 52 @pytest.mark.slow def test_dynamic_workloads_sync_random(c): future = c.submit(_dynamic_workload, 0, delay="random") assert future.result(timeout=20) == 52 @gen_cluster(client=True) async def test_unicode_ascii_keys(c, s, a, b): uni_type = str key = "inc-123" future = c.submit(inc, 1, key=key) result = await future assert type(future.key) is uni_type assert set(s.tasks) == {key} assert key in a.data or key in b.data assert result == 2 @gen_cluster(client=True) async def test_unicode_keys(c, s, a, b): uni_type = str key = "inc-123\u03bc" future = c.submit(inc, 1, key=key) result = await future assert type(future.key) is uni_type assert set(s.tasks) == {key} assert key in a.data or key in b.data assert result == 2 future2 = c.submit(inc, future) result2 = await future2 assert result2 == 3 future3 = await c.scatter({"data-123": 123}) result3 = await future3["data-123"] assert result3 == 123 def test_use_synchronous_client_in_async_context(loop, c): async def f(): x = await c.scatter(123) y = c.submit(inc, x) z = await c.gather(y) return z z = sync(loop, f) assert z == 124 def test_quiet_quit_when_cluster_leaves(loop_in_thread): loop = loop_in_thread with LocalCluster(loop=loop, dashboard_address=":0", silence_logs=False) as cluster: with captured_logger("distributed.comm") as sio: with Client(cluster, loop=loop) as client: futures = client.map(lambda x: x + 1, range(10)) sleep(0.05) cluster.close() sleep(0.05) text = sio.getvalue() assert not text @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_future(c, s, a, b): x = c.submit(slowdec, 1, delay=0.5) future = c.submit(slowinc, 1, delay=0.5) await asyncio.sleep(0.1) results = await asyncio.gather( c.call_stack(future), c.call_stack(keys=[future.key]) ) assert all(list(first(result.values())) == [future.key] for result in results) assert results[0] == results[1] result = results[0] ts = a.state.tasks.get(future.key) if ts is not None and ts.state == "executing": w = a else: w = b assert list(result) == [w.address] assert list(result[w.address]) == [future.key] assert "slowinc" in str(result) assert "slowdec" not in str(result) @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_all(c, s, a, b): future = c.submit(slowinc, 1, delay=0.8) while not a.state.executing_count and not b.state.executing_count: await asyncio.sleep(0.01) result = await c.call_stack() w = a if a.state.executing_count else b assert list(result) == [w.address] assert list(result[w.address]) == [future.key] assert "slowinc" in str(result) @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_collections(c, s, a, b): pytest.importorskip("numpy") da = pytest.importorskip("dask.array") x = c.persist(da.random.random(100, chunks=(10,)).map_blocks(slowinc, delay=0.5)) while not a.state.executing_count and not b.state.executing_count: await asyncio.sleep(0.001) result = await c.call_stack(x) assert result @gen_cluster([("127.0.0.1", 4)] * 2, client=True) async def test_call_stack_collections_all(c, s, a, b): pytest.importorskip("numpy") da = pytest.importorskip("dask.array") x = c.persist(da.random.random(100, chunks=(10,)).map_blocks(slowinc, delay=0.5)) while not a.state.executing_count and not b.state.executing_count: await asyncio.sleep(0.001) result = await c.call_stack() assert result @pytest.mark.skipif(sys.version_info.minor == 11, reason="Profiler disabled") @pytest.mark.flaky(condition=WINDOWS, reruns=10, reruns_delay=5) @gen_cluster( client=True, config={ "distributed.worker.profile.enabled": True, "distributed.worker.profile.cycle": "100ms", }, ) async def test_profile(c, s, a, b): futures = c.map(slowinc, range(10), delay=0.05, workers=a.address) await wait(futures) x = await c.profile(start=time() + 10, stop=time() + 20) assert not x["count"] x = await c.profile(start=0, stop=time()) assert ( x["count"] == sum(p["count"] for _, p in a.profile_history) + a.profile_recent["count"] ) y = await c.profile(start=time() - 0.300, stop=time()) assert 0 < y["count"] < x["count"] assert not any(p["count"] for _, p in b.profile_history) result = await c.profile(workers=b.address) assert not result["count"] @gen_cluster( client=True, config={ "distributed.worker.profile.enabled": False, "distributed.worker.profile.cycle": "100ms", }, ) async def test_profile_disabled(c, s, a, b): futures = c.map(slowinc, range(10), delay=0.05, workers=a.address) await wait(futures) x = await c.profile(start=time() + 10, stop=time() + 20) assert x["count"] == 0 x = await c.profile(start=0, stop=time()) assert x["count"] == 0 y = await c.profile(start=time() - 0.300, stop=time()) assert 0 == y["count"] == x["count"] @gen_cluster( client=True, config={ "distributed.worker.profile.cycle": "100ms", }, ) async def test_profile_keys(c, s, a, b): x = c.map(slowinc, range(10), delay=0.05, workers=a.address) y = c.map(slowdec, range(10), delay=0.05, workers=a.address) await wait(x + y) xp = await c.profile("slowinc") yp = await c.profile("slowdec") p = await c.profile() assert p["count"] == xp["count"] + yp["count"] with captured_logger("distributed") as logger: prof = await c.profile("does-not-exist") assert prof == profile.create() out = logger.getvalue() assert not out @gen_cluster() async def test_client_with_name(s, a, b): with captured_logger("distributed.scheduler") as sio: async with Client(s.address, asynchronous=True, name="foo") as client: assert "foo" in client.id text = sio.getvalue() assert "foo" in text def test_client_async_before_loop_starts(cleanup): with pytest.raises( RuntimeError, match=r"Constructing LoopRunner\(asynchronous=True\) without a running loop is not supported", ): client = Client(asynchronous=True, loop=None) @pytest.mark.slow @gen_cluster(client=True, Worker=Nanny, timeout=60, nthreads=[("127.0.0.1", 3)] * 2) async def test_nested_compute(c, s, a, b): def fib(x): assert get_worker().get_current_task() if x < 2: return x a = delayed(fib)(x - 1) b = delayed(fib)(x - 2) c = a + b return c.compute() future = c.submit(fib, 8) result = await future assert result == 21 assert len(s.transition_log) > 50 @gen_cluster(client=True) async def test_task_metadata(c, s, a, b): with pytest.raises(KeyError): await c.get_metadata("x") with pytest.raises(KeyError): await c.get_metadata(["x"]) result = await c.get_metadata("x", None) assert result is None result = await c.get_metadata(["x"], None) assert result is None with pytest.raises(KeyError): await c.get_metadata(["x", "y"]) result = await c.get_metadata(["x", "y"], None) assert result is None await c.set_metadata("x", 1) result = await c.get_metadata("x") assert result == 1 with pytest.raises(TypeError): await c.get_metadata(["x", "y"]) with pytest.raises(TypeError): await c.get_metadata(["x", "y"], None) future = c.submit(inc, 1) key = future.key await wait(future) await c.set_metadata(key, 123) result = await c.get_metadata(key) assert result == 123 del future while key in s.tasks: await asyncio.sleep(0.01) with pytest.raises(KeyError): await c.get_metadata(key) result = await c.get_metadata(key, None) assert result is None await c.set_metadata(["x", "a"], 1) result = await c.get_metadata("x") assert result == {"a": 1} await c.set_metadata(["x", "b"], 2) result = await c.get_metadata("x") assert result == {"a": 1, "b": 2} result = await c.get_metadata(["x", "a"]) assert result == 1 await c.set_metadata(["x", "a", "c", "d"], 1) result = await c.get_metadata("x") assert result == {"a": {"c": {"d": 1}}, "b": 2} @gen_cluster(client=True, Worker=Nanny) async def test_logs(c, s, a, b): await wait(c.map(inc, range(5))) logs = await c.get_scheduler_logs(n=5) assert logs for _, msg in logs: assert "distributed.scheduler" in msg w_logs = await c.get_worker_logs(n=5) assert set(w_logs.keys()) == {a.worker_address, b.worker_address} for log in w_logs.values(): for _, msg in log: assert "distributed.worker" in msg n_logs = await c.get_worker_logs(nanny=True) assert set(n_logs.keys()) == {a.worker_address, b.worker_address} for log in n_logs.values(): for _, msg in log: assert "distributed.nanny" in msg n_logs = await c.get_worker_logs(nanny=True, workers=[a.worker_address]) assert set(n_logs.keys()) == {a.worker_address} for log in n_logs.values(): for _, msg in log: assert "distributed.nanny" in msg @gen_cluster(client=True, nthreads=[("", 1)], Worker=Nanny) async def test_logs_from_worker_submodules(c, s, a): def on_worker(dask_worker): from distributed.worker import logger as l1 from distributed.worker_memory import worker_logger as l2 from distributed.worker_state_machine import logger as l3 l1.info("AAA") l2.info("BBB") l3.info("CCC") await c.run(on_worker) logs = await c.get_worker_logs() logs = [row[1].partition(" - ")[2] for row in logs[a.worker_address]] assert logs[:3] == [ "distributed.worker.state_machine - INFO - CCC", "distributed.worker.memory - INFO - BBB", "distributed.worker - INFO - AAA", ] def on_nanny(dask_worker): from distributed.nanny import logger as l4 from distributed.worker_memory import nanny_logger as l5 l4.info("DDD") l5.info("EEE") await c.run(on_nanny, nanny=True) logs = await c.get_worker_logs(nanny=True) logs = [row[1].partition(" - ")[2] for row in logs[a.worker_address]] assert logs[:2] == [ "distributed.nanny.memory - INFO - EEE", "distributed.nanny - INFO - DDD", ] @gen_cluster(client=True) async def test_avoid_delayed_finalize(c, s, a, b): x = delayed(inc)(1) future = c.compute(x) result = await future assert result == 2 assert list(s.tasks) == [future.key] == [x.key] @gen_cluster() async def test_config_scheduler_address(s, a, b): with dask.config.set({"scheduler-address": s.address}): with captured_logger("distributed.client") as sio: async with Client(asynchronous=True) as c: assert c.scheduler.address == s.address assert sio.getvalue() == f"Config value `scheduler-address` found: {s.address}\n" @gen_cluster(client=True, nthreads=[]) async def test_warn_when_submitting_large_values(c, s): with pytest.warns(UserWarning, match="Sending large graph of size"): future = c.submit(lambda x: x + 1, b"0" * 10_000_000) with dask.config.set({"distributed.admin.large-graph-warning-threshold": "1GB"}): future = c.submit(lambda x: x + 1, b"0" * 10_000_000) @gen_cluster(client=True, nthreads=[]) async def test_warn_when_submitting_large_values_memoryview(c, s): """When sending numpy or parquet data, len(memoryview(obj)) returns the number of elements, not the number of bytes. Make sure we're reading memoryview.nbytes. """ # The threshold is 10MB a = array.array("d", b"0" * 9_500_000) c.submit(lambda: a) a = array.array("d", b"0" * 10_000_000) with pytest.warns(UserWarning, match="Sending large graph of size"): c.submit(lambda: a) @gen_cluster(client=True, nthreads=[]) async def test_closed_client_send_message(c, s): # Ensure a meaningful, but concise error is raised when # a closed client attempts to send a message to the scheduler await c.close() with pytest.raises(ClosedClientError, match="update-graph") as exc_info: c.submit(lambda x: x + 1) msg = str(exc_info.value) assert "Can't send update-graph" in msg assert len(msg) < 100 @gen_cluster(client=True) async def test_unhashable_function(c, s, a, b): func = _UnhashableCallable() result = await c.submit(func, 1) assert result == 2 @gen_cluster() async def test_client_name(s, a, b): with dask.config.set({"client-name": "hello-world"}): async with Client(s.address, asynchronous=True) as c: assert any("hello-world" in name for name in list(s.clients)) def test_client_doesnt_close_given_loop(loop_in_thread, s, a, b): with Client(s["address"], loop=loop_in_thread) as c: assert c.submit(inc, 1).result() == 2 with Client(s["address"], loop=loop_in_thread) as c: assert c.submit(inc, 2).result() == 3 @pytest.mark.slow @gen_cluster(client=True, nthreads=[]) async def test_quiet_scheduler_loss(c, s): c._periodic_callbacks["scheduler-info"].interval = 10 with captured_logger("distributed.client") as logger: await s.close() text = logger.getvalue() assert "BrokenPipeError" not in text def test_dashboard_link(loop, monkeypatch): monkeypatch.setenv("USER", "myusername") with cluster(scheduler_kwargs={"dashboard_address": ":12355"}) as (s, [a, b]): with Client(s["address"], loop=loop) as c: with dask.config.set( {"distributed.dashboard.link": "{scheme}://foo-{USER}:{port}/status"} ): link = "http://foo-myusername:12355/status" assert link == c.dashboard_link text = c._repr_html_() assert link in text @gen_test() async def test_dashboard_link_inproc(): async with Client(processes=False, asynchronous=True, dashboard_address=":0") as c: with dask.config.set({"distributed.dashboard.link": "{host}"}): assert "/" not in c.dashboard_link @gen_test() async def test_client_timeout_2(): port = open_port() with dask.config.set({"distributed.comm.timeouts.connect": "10ms"}): start = time() c = Client(f"127.0.0.1:{port}", asynchronous=True) with pytest.raises((TimeoutError, IOError)): async with c: pass stop = time() assert c.status == "closed" assert stop - start < 1 @pytest.mark.parametrize("direct", [True, False]) @gen_cluster(client=True, client_kwargs={"serializers": ["dask", "msgpack"]}) async def test_turn_off_pickle(c, s, a, b, direct): np = pytest.importorskip("numpy") assert (await c.submit(inc, 1)) == 2 await c.submit(np.ones, 5) await c.scatter(1) # Can't send complex data with pytest.raises(TypeError): await c.scatter(inc) # can send complex tasks (this uses pickle regardless) future = c.submit(lambda x: x, inc) await wait(future) # but can't receive complex results with pytest.raises(TypeError): await c.gather(future, direct=direct) # Run works result = await c.run(lambda: 1) assert list(result.values()) == [1, 1] result = await c.run_on_scheduler(lambda: 1) assert result == 1 # But not with complex return values with pytest.raises(TypeError): await c.run(lambda: inc) with pytest.raises(TypeError): await c.run_on_scheduler(lambda: inc) @gen_cluster() async def test_de_serialization(s, a, b): np = pytest.importorskip("numpy") async with Client( s.address, asynchronous=True, serializers=["msgpack", "pickle"], deserializers=["msgpack"], ) as c: # Can send complex data future = await c.scatter(np.ones(5)) # But can not retrieve it with pytest.raises(TypeError): result = await future @gen_cluster() async def test_de_serialization_none(s, a, b): np = pytest.importorskip("numpy") async with Client(s.address, asynchronous=True, deserializers=["msgpack"]) as c: # Can send complex data future = await c.scatter(np.ones(5)) # But can not retrieve it with pytest.raises(TypeError): result = await future @gen_cluster() async def test_client_repr_closed(s, a, b): async with Client(s.address, asynchronous=True) as c: pass assert "No scheduler connected." in c._repr_html_() @pytest.mark.skip def test_client_repr_closed_sync(loop): with Client(loop=loop, processes=False, dashboard_address=":0") as c: pass assert "No scheduler connected." in c._repr_html_() @pytest.mark.xfail(reason="https://github.com/dask/dask/pull/6807") @gen_cluster(client=True, nthreads=[("127.0.0.1", 1)]) async def test_nested_prioritization(c, s, w): x = delayed(inc)(1, dask_key_name=("a", 2)) y = delayed(inc)(2, dask_key_name=("a", 10)) o = dask.order.order(merge(x.__dask_graph__(), y.__dask_graph__())) fx, fy = c.compute([x, y]) await wait([fx, fy]) assert (o[x.key] < o[y.key]) == ( s.tasks[fx.key].priority < s.tasks[fy.key].priority ) @gen_cluster(client=True) async def test_scatter_error_cancel(c, s, a, b): # https://github.com/dask/distributed/issues/2038 def bad_fn(x): raise Exception("lol") x = await c.scatter(1) y = c.submit(bad_fn, x) del x await wait(y) assert y.status == "error" await asyncio.sleep(0.1) assert y.status == "error" # not cancelled @pytest.mark.parametrize("workers_arg", [False, True]) @pytest.mark.parametrize("direct", [False, True]) @pytest.mark.parametrize("broadcast", [False, True, 10]) @gen_cluster( client=True, nthreads=[("", 1)] * 10, config=merge(NO_AMM, {"distributed.worker.memory.pause": False}), ) async def test_scatter_and_replicate_avoid_paused_workers( c, s, *workers, workers_arg, direct, broadcast ): paused_workers = [w for i, w in enumerate(workers) if i not in (3, 7)] for w in paused_workers: w.status = Status.paused while any(s.workers[w.address].status != Status.paused for w in paused_workers): await asyncio.sleep(0.01) f = await c.scatter( {"x": 1}, workers=[w.address for w in workers[1:-1]] if workers_arg else None, broadcast=broadcast, direct=direct, ) if not broadcast: await c.replicate(f, n=10) expect = [i in (3, 7) for i in range(10)] actual = [("x" in w.data) for w in workers] assert actual == expect @pytest.mark.xfail(reason="GH#5409 Dask-Default-Threads are frequently detected") def test_no_threads_lingering(): if threading.active_count() < 40: return active = dict(threading._active) print(f"==== Found {len(active)} active threads: ====") for t in active.values(): print(t) assert False @gen_cluster() async def test_direct_async(s, a, b): # Keyword option async with Client(s.address, asynchronous=True, direct_to_workers=True) as c: assert c.direct_to_workers async with Client(s.address, asynchronous=True, direct_to_workers=False) as c: assert not c.direct_to_workers # Config option with dask.config.set({"distributed.client.direct-to-workers": True}): async with Client(s.address, asynchronous=True) as c: assert c.direct_to_workers with dask.config.set({"distributed.client.direct-to-workers": False}): async with Client(s.address, asynchronous=True) as c: assert not c.direct_to_workers def test_direct_sync(c): assert not c.direct_to_workers def f(): return get_client().direct_to_workers assert c.submit(f).result() @gen_cluster() async def test_mixing_clients_same_scheduler(s, a, b): async with ( Client(s.address, asynchronous=True) as c1, Client(s.address, asynchronous=True) as c2, ): future = c1.submit(inc, 1) assert await c2.submit(inc, future) == 3 assert not s.tasks @gen_cluster() async def test_mixing_clients_different_scheduler(s, a, b): async with ( Scheduler(port=open_port(), dashboard_address=":0") as s2, Worker(s2.address) as w1, Client(s.address, asynchronous=True) as c1, Client(s2.address, asynchronous=True) as c2, ): future = c1.submit(inc, 1) with pytest.raises(CancelledError): await c2.submit(inc, future) @dataclass(frozen=True)
BrokenSetState
python
getsentry__sentry
src/sentry/rules/processing/buffer_processing.py
{ "start": 542, "end": 593 }
class ____: project_id: int @dataclass
FilterKeys
python
ray-project__ray
doc/source/ray-core/doc_code/tasks_fault_tolerance.py
{ "start": 934, "end": 2797 }
class ____(Exception): pass @ray.remote(max_retries=1, retry_exceptions=True) def potentially_fail(failure_probability): if failure_probability < 0 or failure_probability > 1: raise ValueError( "failure_probability must be between 0 and 1, but got: " f"{failure_probability}" ) time.sleep(0.2) if np.random.random() < failure_probability: raise RandomError("Failed!") return 0 for _ in range(3): try: # If this task crashes, Ray will retry it up to one additional # time. If either of the attempts succeeds, the call to ray.get # below will return normally. Otherwise, it will raise an # exception. ray.get(potentially_fail.remote(0.5)) print('SUCCESS') except RandomError: print('FAILURE') # Provide the exceptions that we want to retry as an allowlist. retry_on_exception = potentially_fail.options(retry_exceptions=[RandomError]) try: # This will fail since we're passing in -1 for the failure_probability, # which will raise a ValueError in the task and does not match the RandomError # exception that we provided. ray.get(retry_on_exception.remote(-1)) except ValueError: print("FAILED AS EXPECTED") else: raise RuntimeError("An exception should be raised so this shouldn't be reached.") # These will retry on the RandomError exception. for _ in range(3): try: # If this task crashes, Ray will retry it up to one additional # time. If either of the attempts succeeds, the call to ray.get # below will return normally. Otherwise, it will raise an # exception. ray.get(retry_on_exception.remote(0.5)) print('SUCCESS') except RandomError: print('FAILURE AFTER RETRIES') # __tasks_fault_tolerance_retries_exception_end__ # fmt: on
RandomError
python
numba__numba
numba/core/ccallback.py
{ "start": 1002, "end": 4312 }
class ____(object): """ A compiled C callback, as created by the @cfunc decorator. """ _targetdescr = registry.cpu_target def __init__(self, pyfunc, sig, locals, options, pipeline_class=compiler.Compiler): args, return_type = sig if return_type is None: raise TypeError("C callback needs an explicit return type") self.__name__ = pyfunc.__name__ self.__qualname__ = getattr(pyfunc, '__qualname__', self.__name__) self.__wrapped__ = pyfunc self._pyfunc = pyfunc self._sig = signature(return_type, *args) self._compiler = _CFuncCompiler(pyfunc, self._targetdescr, options, locals, pipeline_class=pipeline_class) self._wrapper_name = None self._wrapper_address = None self._cache = NullCache() self._cache_hits = 0 def enable_caching(self): self._cache = FunctionCache(self._pyfunc) @global_compiler_lock def compile(self): # Try to load from cache cres = self._cache.load_overload(self._sig, self._targetdescr.target_context) if cres is None: cres = self._compile_uncached() self._cache.save_overload(self._sig, cres) else: self._cache_hits += 1 self._library = cres.library self._wrapper_name = cres.fndesc.llvm_cfunc_wrapper_name self._wrapper_address = self._library.get_pointer_to_function( self._wrapper_name) def _compile_uncached(self): sig = self._sig # Compile native function as well as cfunc wrapper return self._compiler.compile(sig.args, sig.return_type) @property def native_name(self): """ The process-wide symbol the C callback is exposed as. """ # Note from our point of view, the C callback is the wrapper around # the native function. return self._wrapper_name @property def address(self): """ The address of the C callback. """ return self._wrapper_address @cached_property def cffi(self): """ A cffi function pointer representing the C callback. """ import cffi ffi = cffi.FFI() # cffi compares types by name, so using precise types would risk # spurious mismatches (such as "int32_t" vs. "int"). return ffi.cast("void *", self.address) @cached_property def ctypes(self): """ A ctypes function object representing the C callback. """ ctypes_args = [to_ctypes(ty) for ty in self._sig.args] ctypes_restype = to_ctypes(self._sig.return_type) functype = ctypes.CFUNCTYPE(ctypes_restype, *ctypes_args) return functype(self.address) def inspect_llvm(self): """ Return the LLVM IR of the C callback definition. """ return self._library.get_llvm_str() @property def cache_hits(self): return self._cache_hits def __repr__(self): return "<Numba C callback %r>" % (self.__qualname__,) def __call__(self, *args, **kwargs): return self._pyfunc(*args, **kwargs)
CFunc
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/annotated1.py
{ "start": 192, "end": 396 }
class ____: @staticmethod def ctype(a: str): pass class Packed: pass UnsignedShort = Annotated[int, struct2.ctype("H")] SignedChar = Annotated[int, struct2.ctype("b")]
struct2
python
walkccc__LeetCode
solutions/437. Path Sum III/437.py
{ "start": 0, "end": 447 }
class ____: def pathSum(self, root: TreeNode | None, summ: int) -> int: if not root: return 0 def dfs(root: TreeNode, summ: int) -> int: if not root: return 0 return (int(summ == root.val) + dfs(root.left, summ - root.val) + dfs(root.right, summ - root.val)) return (dfs(root, summ) + self.pathSum(root.left, summ) + self.pathSum(root.right, summ))
Solution
python
pytorch__pytorch
torch/distributed/fsdp/_flat_param.py
{ "start": 4899, "end": 5612 }
class ____(NamedTuple): """Shard-related information for an original parameter.""" in_shard: bool # Use to index into the sharded flat parameter, e.g. # `flat_param[offset_in_shard : offset_in_shard + numel_in_shard]` offset_in_shard: Optional[int] numel_in_shard: Optional[int] # Use to get part of the parameter in the local shard from a flattened # version of the unsharded parameter, e.g. either # `param.flatten()[intra_param_start_idx : intra_param_end_idx + 1]` or # `param.as_strided((param.numel(),), (1,))[intra_param_start_idx : intra_param_end_idx + 1]` intra_param_start_idx: Optional[int] intra_param_end_idx: Optional[int] # inclusive
_ShardParamInfo
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_tags.py
{ "start": 17645, "end": 19650 }
class ____(APITestCase, ReplaysSnubaTestCase): def test_dataset_replays(self) -> None: self.login_as(user=self.user) replay1_id = uuid.uuid4().hex replay2_id = uuid.uuid4().hex replay3_id = uuid.uuid4().hex self.r1_seq0_timestamp = before_now(seconds=22) self.r1_seq1_timestamp = before_now(seconds=15) self.r2_seq0_timestamp = before_now(seconds=10) self.r3_seq0_timestamp = before_now(seconds=10) self.store_replays( mock_replay( self.r1_seq0_timestamp, self.project.id, replay1_id, tags={"fruit": "orange"}, segment_id=0, ), ) self.store_replays( mock_replay( self.r1_seq1_timestamp, self.project.id, replay1_id, tags={"fruit": "orange"}, segment_id=1, ), ) self.store_replays( mock_replay( self.r2_seq0_timestamp, self.project.id, replay2_id, tags={"fruit": "orange"}, ) ) self.store_replays( mock_replay( self.r3_seq0_timestamp, self.project.id, replay3_id, tags={"fruit": "apple", "drink": "water"}, ) ) url = reverse( "sentry-api-0-organization-tags", kwargs={"organization_id_or_slug": self.organization.slug}, ) response = self.client.get(url, {"statsPeriod": "14d", "dataset": "replays"}, format="json") assert response.status_code == 200, response.content data = response.data data.sort(key=lambda val: val["name"]) assert data == [ {"key": "drink", "name": "Drink", "totalValues": 1}, {"key": "fruit", "name": "Fruit", "totalValues": 4}, ]
ReplayOrganizationTagsTest
python
bokeh__bokeh
src/bokeh/resources.py
{ "start": 7896, "end": 19016 }
class ____: """ The Resources class encapsulates information relating to loading or embedding Bokeh Javascript and CSS. Args: mode (str) : how should Bokeh JS and CSS be included in output See below for descriptions of available modes version (str, optional) : what version of Bokeh JS and CSS to load Only valid with the ``'cdn'`` mode root_dir (str, optional) : root directory for loading Bokeh JS and CSS assets Only valid with ``'relative'`` and ``'relative-dev'`` modes minified (bool, optional) : whether JavaScript and CSS should be minified or not (default: True) root_url (str, optional) : URL and port of Bokeh Server to load resources from Only valid with ``'server'`` and ``'server-dev'`` modes The following **mode** values are available for configuring a Resource object: * ``'inline'`` configure to provide entire Bokeh JS and CSS inline * ``'cdn'`` configure to load Bokeh JS and CSS from ``https://cdn.bokeh.org`` * ``'server'`` configure to load from a Bokeh Server * ``'server-dev'`` same as ``server`` but supports non-minified assets * ``'relative'`` configure to load relative to the given directory * ``'relative-dev'`` same as ``relative`` but supports non-minified assets * ``'absolute'`` configure to load from the installed Bokeh library static directory * ``'absolute-dev'`` same as ``absolute`` but supports non-minified assets Once configured, a Resource object exposes the following public attributes: Attributes: js_raw : any raw JS that needs to be placed inside ``<script>`` tags css_raw : any raw CSS that needs to be places inside ``<style>`` tags js_files : URLs of any JS files that need to be loaded by ``<script>`` tags css_files : URLs of any CSS files that need to be loaded by ``<link>`` tags messages : any informational messages concerning this configuration These attributes are often useful as template parameters when embedding Bokeh plots. """ _default_root_dir = Path(os.curdir) _default_root_url = DEFAULT_SERVER_HTTP_URL mode: BaseMode messages: list[RuntimeMessage] _log_level: LogLevel components: list[Component] _component_defs: ClassVar[ComponentDefs] = { "js": ["bokeh", "bokeh-gl", "bokeh-widgets", "bokeh-tables", "bokeh-mathjax", "bokeh-api"], "css": [], } _default_components: ClassVar[list[Component]] = ["bokeh", "bokeh-gl", "bokeh-widgets", "bokeh-tables", "bokeh-mathjax"] def __init__( self, mode: ResourcesMode | None = None, *, version: str | None = None, root_dir: PathLike | None = None, dev: bool | None = None, minified: bool | None = None, log_level: LogLevel | None = None, root_url: str | None = None, path_versioner: PathVersioner | None = None, components: list[Component] | None = None, base_dir: PathLike | None = None, ): self.components = components if components is not None else list(self._default_components) mode = settings.resources(mode) mode_dev = mode.endswith("-dev") self.dev = dev if dev is not None else settings.dev or mode_dev self.mode = cast(BaseMode, mode[:-4] if mode_dev else mode) if self.mode not in get_args(BaseMode): raise ValueError( "wrong value for 'mode' parameter, expected " f"'inline', 'cdn', 'server(-dev)', 'relative(-dev)' or 'absolute(-dev)', got {mode}", ) if root_dir and not self.mode.startswith("relative"): raise ValueError("setting 'root_dir' makes sense only when 'mode' is set to 'relative'") if version and not self.mode.startswith("cdn"): raise ValueError("setting 'version' makes sense only when 'mode' is set to 'cdn'") if root_url and not self.mode.startswith("server"): raise ValueError("setting 'root_url' makes sense only when 'mode' is set to 'server'") self.root_dir = settings.rootdir(root_dir) del root_dir self.version = settings.cdn_version(version) del version if minified is None and self.dev: minified = False self.minified = settings.minified(minified) del minified self.log_level = settings.log_level(log_level) del log_level self.path_versioner = path_versioner del path_versioner if root_url and not root_url.endswith("/"): # root_url should end with a /, adding one root_url = root_url + "/" self._root_url = root_url self.messages = [] match self.mode: case "cdn": cdn = self._cdn_urls() self.messages.extend(cdn.messages) case "server": server = self._server_urls() self.messages.extend(server.messages) self.base_dir = Path(base_dir) if base_dir is not None else settings.bokehjs_path() def clone(self, *, components: list[Component] | None = None) -> Resources: """ Make a clone of a resources instance allowing to override its components. """ return Resources( mode=self.mode, version=self.version, root_dir=self.root_dir, dev=self.dev, minified=self.minified, log_level=self.log_level, root_url=self._root_url, path_versioner=self.path_versioner, components=components if components is not None else list(self.components), base_dir=self.base_dir, ) def __repr__(self) -> str: args = [f"mode={self.mode!r}"] if self.dev: args.append("dev=True") if self.components != self._default_components: args.append(f"components={self.components!r}") return f"Resources({', '.join(args)})" __str__ = __repr__ @classmethod def build(cls, resources: ResourcesLike | None = None) -> Resources: if isinstance(resources, Resources): return resources else: return Resources(mode=settings.resources(resources)) # Properties -------------------------------------------------------------- @property def log_level(self) -> LogLevel: return self._log_level @log_level.setter def log_level(self, level: LogLevel) -> None: valid_levels = get_args(LogLevel) if not (level is None or level in valid_levels): raise ValueError(f"Unknown log level '{level}', valid levels are: {valid_levels}") self._log_level = level @property def root_url(self) -> str: if self._root_url is not None: return self._root_url else: return self._default_root_url # Public methods ---------------------------------------------------------- def components_for(self, kind: Kind) -> list[Component]: return [comp for comp in self.components if comp in self._component_defs[kind]] def _file_paths(self, kind: Kind) -> list[Path]: minified = ".min" if self.minified else "" files = [f"{component}{minified}.{kind}" for component in self.components_for(kind)] paths = [self.base_dir / kind / file for file in files] return paths def _collect_external_resources(self, resource_attr: ResourceAttr) -> list[str]: """ Collect external resources set on resource_attr attribute of all models.""" external_resources: list[str] = [] for _, cls in sorted(Model.model_class_reverse_map.items(), key=lambda arg: arg[0]): external: list[str] | str | None = getattr(cls, resource_attr, None) match external: case str(): if external not in external_resources: external_resources.append(external) case list(): for e in external: if e not in external_resources: external_resources.append(e) return external_resources def _cdn_urls(self) -> Urls: return _get_cdn_urls(self.version, self.minified) def _server_urls(self) -> Urls: return _get_server_urls(self.root_url, self.minified, self.path_versioner) def _resolve(self, kind: Kind) -> tuple[list[str], list[str], Hashes]: paths = self._file_paths(kind) files, raw = [], [] hashes = {} match self.mode: case "inline": raw = [self._inline(path) for path in paths] case "relative": root_dir = self.root_dir or self._default_root_dir files = [str(relpath(path, root_dir)) for path in paths] case "absolute": files = list(map(str, paths)) case "cdn": cdn = self._cdn_urls() files = list(cdn.urls(self.components_for(kind), kind)) if cdn.hashes: hashes = cdn.hashes(self.components_for(kind), kind) case "server": server = self._server_urls() files = list(server.urls(self.components_for(kind), kind)) return (files, raw, hashes) @staticmethod def _inline(path: Path) -> str: filename = path.name begin = f"/* BEGIN {filename} */" with open(path, "rb") as f: middle = f.read().decode("utf-8") end = f"/* END {filename} */" return f"{begin}\n{middle}\n{end}" @property def js_files(self) -> list[str]: files, _, _ = self._resolve("js") external_resources = self._collect_external_resources("__javascript__") return external_resources + files @property def js_raw(self) -> list[str]: _, raw, _ = self._resolve("js") if self.log_level is not None: raw.append(f'Bokeh.set_log_level("{self.log_level}");') if self.dev: raw.append("Bokeh.settings.dev = true") return raw @property def hashes(self) -> Hashes: _, _, hashes = self._resolve("js") return hashes def render_js(self) -> str: return JS_RESOURCES.render(js_raw=self.js_raw, js_files=self.js_files, hashes=self.hashes) @property def css_files(self) -> list[str]: files, _, _ = self._resolve("css") external_resources = self._collect_external_resources("__css__") return external_resources + files @property def css_raw(self) -> list[str]: _, raw, _ = self._resolve("css") return raw @property def css_raw_str(self) -> list[str]: return [json.dumps(css) for css in self.css_raw] def render_css(self) -> str: return CSS_RESOURCES.render(css_raw=self.css_raw, css_files=self.css_files) def render(self) -> str: css, js = self.render_css(), self.render_js() return f"{css}\n{js}"
Resources
python
rq__rq
tests/test_cli.py
{ "start": 1418, "end": 31948 }
class ____(CLITestCase): @pytest.fixture(autouse=True) def set_tmpdir(self, tmpdir): self.tmpdir = tmpdir def assert_normal_execution(self, result): if result.exit_code == 0: return True else: print('Non normal execution') print(f'Exit Code: {result.exit_code}') print(f'Output: {result.output}') print(f'Exception: {result.exception}') self.assertEqual(result.exit_code, 0) """Test rq_cli script""" def setUp(self): super().setUp() job = Job.create(func=div_by_zero, args=(1, 2, 3), connection=self.connection) job.origin = 'fake' job.save() def test_config_file(self): settings = read_config_file('tests.config_files.dummy') self.assertIn('REDIS_HOST', settings) self.assertEqual(settings['REDIS_HOST'], 'testhost.example.com') def test_config_file_logging(self): runner = CliRunner() result = runner.invoke(main, ['worker', '-u', self.redis_url, '-b', '-c', 'tests.config_files.dummy_logging']) self.assert_normal_execution(result) def test_config_file_option(self): """""" cli_config = CliConfig(config='tests.config_files.dummy') self.assertEqual( cli_config.connection.connection_pool.connection_kwargs['host'], 'testhost.example.com', ) runner = CliRunner() result = runner.invoke(main, ['info', '--config', str(cli_config.config)]) self.assertEqual(result.exit_code, 1) def test_config_file_default_options(self): """""" cli_config = CliConfig(config='tests.config_files.dummy') self.assertEqual( cli_config.connection.connection_pool.connection_kwargs['host'], 'testhost.example.com', ) self.assertEqual(cli_config.connection.connection_pool.connection_kwargs['port'], 6379) self.assertEqual(cli_config.connection.connection_pool.connection_kwargs['db'], 0) self.assertEqual(cli_config.connection.connection_pool.connection_kwargs['password'], None) def test_config_file_default_options_override(self): """""" cli_config = CliConfig(config='tests.config_files.dummy_override') self.assertEqual( cli_config.connection.connection_pool.connection_kwargs['host'], 'testhost.example.com', ) self.assertEqual(cli_config.connection.connection_pool.connection_kwargs['port'], 6378) self.assertEqual(cli_config.connection.connection_pool.connection_kwargs['db'], 2) self.assertEqual(cli_config.connection.connection_pool.connection_kwargs['password'], '123') def test_config_env_vars(self): os.environ['REDIS_HOST'] = 'testhost.example.com' cli_config = CliConfig() self.assertEqual( cli_config.connection.connection_pool.connection_kwargs['host'], 'testhost.example.com', ) def test_death_penalty_class(self): cli_config = CliConfig() self.assertEqual(UnixSignalDeathPenalty, cli_config.death_penalty_class) cli_config = CliConfig(death_penalty_class='rq.job.Job') self.assertEqual(Job, cli_config.death_penalty_class) with self.assertRaises(ValueError): CliConfig(death_penalty_class='rq.abcd') def test_empty_nothing(self): """rq empty -u <url>""" runner = CliRunner() result = runner.invoke(main, ['empty', '-u', self.redis_url]) self.assert_normal_execution(result) self.assertEqual(result.output.strip(), 'Nothing to do') def test_requeue(self): """rq requeue -u <url> --all""" connection = Redis.from_url(self.redis_url) queue = Queue('requeue', connection=connection) registry = queue.failed_job_registry runner = CliRunner() job = queue.enqueue(div_by_zero) job2 = queue.enqueue(div_by_zero) job3 = queue.enqueue(div_by_zero) worker = Worker([queue], connection=connection) worker.work(burst=True) self.assertIn(job, registry) self.assertIn(job2, registry) self.assertIn(job3, registry) result = runner.invoke(main, ['requeue', '-u', self.redis_url, '--queue', 'requeue', job.id]) self.assert_normal_execution(result) # Only the first specified job is requeued self.assertNotIn(job, registry) self.assertIn(job2, registry) self.assertIn(job3, registry) result = runner.invoke(main, ['requeue', '-u', self.redis_url, '--queue', 'requeue', '--all']) self.assert_normal_execution(result) # With --all flag, all failed jobs are requeued self.assertNotIn(job2, registry) self.assertNotIn(job3, registry) def test_requeue_with_serializer(self): """rq requeue -u <url> -S <serializer> --all""" connection = Redis.from_url(self.redis_url) queue = Queue('requeue', connection=connection, serializer=JSONSerializer) registry = queue.failed_job_registry runner = CliRunner() job = queue.enqueue(div_by_zero) job2 = queue.enqueue(div_by_zero) job3 = queue.enqueue(div_by_zero) worker = Worker([queue], serializer=JSONSerializer, connection=connection) worker.work(burst=True) self.assertIn(job, registry) self.assertIn(job2, registry) self.assertIn(job3, registry) result = runner.invoke( main, ['requeue', '-u', self.redis_url, '--queue', 'requeue', '-S', 'rq.serializers.JSONSerializer', job.id] ) self.assert_normal_execution(result) # Only the first specified job is requeued self.assertNotIn(job, registry) self.assertIn(job2, registry) self.assertIn(job3, registry) result = runner.invoke( main, ['requeue', '-u', self.redis_url, '--queue', 'requeue', '-S', 'rq.serializers.JSONSerializer', '--all'], ) self.assert_normal_execution(result) # With --all flag, all failed jobs are requeued self.assertNotIn(job2, registry) self.assertNotIn(job3, registry) def test_info(self): """rq info -u <url>""" runner = CliRunner() result = runner.invoke(main, ['info', '-u', self.redis_url]) self.assert_normal_execution(result) self.assertIn('0 queues, 0 jobs total', result.output) queue = Queue(connection=self.connection) queue.enqueue(say_hello) result = runner.invoke(main, ['info', '-u', self.redis_url]) self.assert_normal_execution(result) self.assertIn('1 queues, 1 jobs total', result.output) def test_info_only_queues(self): """rq info -u <url> --only-queues (-Q)""" runner = CliRunner() result = runner.invoke(main, ['info', '-u', self.redis_url, '--only-queues']) self.assert_normal_execution(result) self.assertIn('0 queues, 0 jobs total', result.output) queue = Queue(connection=self.connection) queue.enqueue(say_hello) result = runner.invoke(main, ['info', '-u', self.redis_url]) self.assert_normal_execution(result) self.assertIn('1 queues, 1 jobs total', result.output) def test_info_only_workers(self): """rq info -u <url> --only-workers (-W)""" runner = CliRunner() result = runner.invoke(main, ['info', '-u', self.redis_url, '--only-workers']) self.assert_normal_execution(result) self.assertIn('0 workers, 0 queue', result.output) result = runner.invoke(main, ['info', '--by-queue', '-u', self.redis_url, '--only-workers']) self.assert_normal_execution(result) self.assertIn('0 workers, 0 queue', result.output) worker = Worker(['default'], connection=self.connection) worker.register_birth() result = runner.invoke(main, ['info', '-u', self.redis_url, '--only-workers']) self.assert_normal_execution(result) self.assertIn('1 workers, 0 queues', result.output) worker.register_death() queue = Queue(connection=self.connection) queue.enqueue(say_hello) result = runner.invoke(main, ['info', '-u', self.redis_url, '--only-workers']) self.assert_normal_execution(result) self.assertIn('0 workers, 1 queues', result.output) foo_queue = Queue(name='foo', connection=self.connection) foo_queue.enqueue(say_hello) bar_queue = Queue(name='bar', connection=self.connection) bar_queue.enqueue(say_hello) worker_1 = Worker([foo_queue, bar_queue], connection=self.connection) worker_1.register_birth() worker_2 = Worker([foo_queue, bar_queue], connection=self.connection) worker_2.register_birth() worker_2.set_state(WorkerStatus.BUSY) result = runner.invoke(main, ['info', 'foo', 'bar', '-u', self.redis_url, '--only-workers']) self.assert_normal_execution(result) self.assertIn('2 workers, 2 queues', result.output) result = runner.invoke(main, ['info', 'foo', 'bar', '--by-queue', '-u', self.redis_url, '--only-workers']) self.assert_normal_execution(result) # Ensure both queues' workers are shown self.assertIn('foo:', result.output) self.assertIn('bar:', result.output) self.assertIn('2 workers, 2 queues', result.output) def test_worker(self): """rq worker -u <url> -b""" runner = CliRunner() result = runner.invoke(main, ['worker', '-u', self.redis_url, '-b']) self.assert_normal_execution(result) def test_worker_pid(self): """rq worker -u <url> /tmp/..""" pid = self.tmpdir.join('rq.pid') runner = CliRunner() result = runner.invoke(main, ['worker', '-u', self.redis_url, '-b', '--pid', str(pid)]) self.assertGreater(len(pid.read()), 0) self.assert_normal_execution(result) def test_worker_with_scheduler(self): """rq worker -u <url> --with-scheduler""" queue = Queue(connection=self.connection) queue.enqueue_at(datetime(2019, 1, 1, tzinfo=timezone.utc), say_hello) registry = ScheduledJobRegistry(queue=queue) runner = CliRunner() result = runner.invoke(main, ['worker', '-u', self.redis_url, '-b']) self.assert_normal_execution(result) self.assertEqual(len(registry), 1) # 1 job still scheduled result = runner.invoke(main, ['worker', '-u', self.redis_url, '-b', '--with-scheduler']) self.assert_normal_execution(result) self.assertEqual(len(registry), 0) # Job has been enqueued def test_worker_logging_options(self): """--quiet and --verbose logging options are supported""" runner = CliRunner() args = ['worker', '-u', self.redis_url, '-b'] result = runner.invoke(main, args + ['--verbose']) self.assert_normal_execution(result) result = runner.invoke(main, args + ['--quiet']) self.assert_normal_execution(result) # --quiet and --verbose are mutually exclusive result = runner.invoke(main, args + ['--quiet', '--verbose']) self.assertNotEqual(result.exit_code, 0) def test_worker_dequeue_strategy(self): """--quiet and --verbose logging options are supported""" runner = CliRunner() args = ['worker', '-u', self.redis_url, '-b', '--dequeue-strategy', 'random'] result = runner.invoke(main, args) self.assert_normal_execution(result) args = ['worker', '-u', self.redis_url, '-b', '--dequeue-strategy', 'round_robin'] result = runner.invoke(main, args) self.assert_normal_execution(result) args = ['worker', '-u', self.redis_url, '-b', '--dequeue-strategy', 'wrong'] result = runner.invoke(main, args) self.assertEqual(result.exit_code, 1) def test_exception_handlers(self): """rq worker -u <url> -b --exception-handler <handler>""" connection = Redis.from_url(self.redis_url) q = Queue('default', connection=connection) runner = CliRunner() # If exception handler is not given, no custom exception handler is run job = q.enqueue(div_by_zero) runner.invoke(main, ['worker', '-u', self.redis_url, '-b']) registry = FailedJobRegistry(queue=q) self.assertIn(job, registry) # If disable-default-exception-handler is given, job is not moved to FailedJobRegistry job = q.enqueue(div_by_zero) runner.invoke(main, ['worker', '-u', self.redis_url, '-b', '--disable-default-exception-handler']) registry = FailedJobRegistry(queue=q) self.assertNotIn(job, registry) # Both default and custom exception handler is run job = q.enqueue(div_by_zero) runner.invoke(main, ['worker', '-u', self.redis_url, '-b', '--exception-handler', 'tests.fixtures.add_meta']) registry = FailedJobRegistry(queue=q) self.assertIn(job, registry) job.refresh() self.assertEqual(job.meta, {'foo': 1}) # Only custom exception handler is run job = q.enqueue(div_by_zero) runner.invoke( main, [ 'worker', '-u', self.redis_url, '-b', '--exception-handler', 'tests.fixtures.add_meta', '--disable-default-exception-handler', ], ) registry = FailedJobRegistry(queue=q) self.assertNotIn(job, registry) job.refresh() self.assertEqual(job.meta, {'foo': 1}) def test_suspend_and_resume(self): """rq suspend -u <url> rq worker -u <url> -b rq resume -u <url> """ runner = CliRunner() result = runner.invoke(main, ['suspend', '-u', self.redis_url]) self.assert_normal_execution(result) result = runner.invoke(main, ['worker', '-u', self.redis_url, '-b']) self.assertEqual(result.exit_code, 1) self.assertEqual(result.output.strip(), 'RQ is currently suspended, to resume job execution run "rq resume"') result = runner.invoke(main, ['resume', '-u', self.redis_url]) self.assert_normal_execution(result) def test_suspend_with_ttl(self): """rq suspend -u <url> --duration=2""" runner = CliRunner() result = runner.invoke(main, ['suspend', '-u', self.redis_url, '--duration', '1']) self.assert_normal_execution(result) def test_suspend_with_invalid_ttl(self): """rq suspend -u <url> --duration=0""" runner = CliRunner() result = runner.invoke(main, ['suspend', '-u', self.redis_url, '--duration', '0']) self.assertEqual(result.exit_code, 1) self.assertIn('Duration must be an integer greater than 1', result.output) def test_serializer(self): """rq worker -u <url> --serializer <serializer>""" connection = Redis.from_url(self.redis_url) q = Queue('default', connection=connection, serializer=JSONSerializer) runner = CliRunner() job = q.enqueue(say_hello) runner.invoke(main, ['worker', '-u', self.redis_url, '--serializer rq.serializer.JSONSerializer']) self.assertIn(job.id, q.job_ids) def test_cli_enqueue(self): """rq enqueue -u <url> tests.fixtures.say_hello""" queue = Queue(connection=self.connection) self.assertTrue(queue.is_empty()) runner = CliRunner() result = runner.invoke(main, ['enqueue', '-u', self.redis_url, 'tests.fixtures.say_hello']) self.assert_normal_execution(result) prefix = "Enqueued tests.fixtures.say_hello() with job-id '" suffix = "'.\n" self.assertTrue(result.output.startswith(prefix)) self.assertTrue(result.output.endswith(suffix)) job_id = result.output[len(prefix) : -len(suffix)] queue_key = 'rq:queue:default' self.assertEqual(self.connection.llen(queue_key), 1) self.assertEqual(self.connection.lrange(queue_key, 0, -1)[0].decode('ascii'), job_id) worker = Worker(queue, connection=self.connection) worker.work(True) self.assertEqual(Job(job_id, connection=self.connection).result, 'Hi there, Stranger!') def test_cli_enqueue_with_serializer(self): """rq enqueue -u <url> -S rq.serializers.JSONSerializer tests.fixtures.say_hello""" queue = Queue(connection=self.connection, serializer=JSONSerializer) self.assertTrue(queue.is_empty()) runner = CliRunner() result = runner.invoke( main, ['enqueue', '-u', self.redis_url, '-S', 'rq.serializers.JSONSerializer', 'tests.fixtures.say_hello'] ) self.assert_normal_execution(result) prefix = "Enqueued tests.fixtures.say_hello() with job-id '" suffix = "'.\n" self.assertTrue(result.output.startswith(prefix)) self.assertTrue(result.output.endswith(suffix)) job_id = result.output[len(prefix) : -len(suffix)] queue_key = 'rq:queue:default' self.assertEqual(self.connection.llen(queue_key), 1) self.assertEqual(self.connection.lrange(queue_key, 0, -1)[0].decode('ascii'), job_id) worker = Worker(queue, serializer=JSONSerializer, connection=self.connection) worker.work(True) self.assertEqual( Job(job_id, serializer=JSONSerializer, connection=self.connection).result, 'Hi there, Stranger!' ) def test_cli_enqueue_args(self): """rq enqueue -u <url> tests.fixtures.echo hello ':[1, {"key": "value"}]' json:=["abc"] nojson=def""" queue = Queue(connection=self.connection) self.assertTrue(queue.is_empty()) runner = CliRunner() result = runner.invoke( main, [ 'enqueue', '-u', self.redis_url, 'tests.fixtures.echo', 'hello', ':[1, {"key": "value"}]', ':@tests/test.json', '%1, 2', 'json:=[3.0, true]', 'nojson=abc', 'file=@tests/test.json', ], ) self.assert_normal_execution(result) job_id = self.connection.lrange('rq:queue:default', 0, -1)[0].decode('ascii') worker = Worker(queue, connection=self.connection) worker.work(True) args, kwargs = Job(job_id, connection=self.connection).result self.assertEqual(args, ('hello', [1, {'key': 'value'}], {'test': True}, (1, 2))) self.assertEqual(kwargs, {'json': [3.0, True], 'nojson': 'abc', 'file': '{"test": true}\n'}) def test_cli_enqueue_schedule_in(self): """rq enqueue -u <url> tests.fixtures.say_hello --schedule-in 1s""" queue = Queue(connection=self.connection) registry = ScheduledJobRegistry(queue=queue) worker = Worker(queue, connection=self.connection) scheduler = RQScheduler(queue, self.connection) self.assertEqual(len(queue), 0) self.assertEqual(len(registry), 0) runner = CliRunner() result = runner.invoke( main, ['enqueue', '-u', self.redis_url, 'tests.fixtures.say_hello', '--schedule-in', '10s'] ) self.assert_normal_execution(result) scheduler.acquire_locks() scheduler.enqueue_scheduled_jobs() self.assertEqual(len(queue), 0) self.assertEqual(len(registry), 1) self.assertFalse(worker.work(True)) sleep(11) scheduler.enqueue_scheduled_jobs() self.assertEqual(len(queue), 1) self.assertEqual(len(registry), 0) self.assertTrue(worker.work(True)) def test_cli_enqueue_schedule_at(self): """ rq enqueue -u <url> tests.fixtures.say_hello --schedule-at 2021-01-01T00:00:00 rq enqueue -u <url> tests.fixtures.say_hello --schedule-at 2100-01-01T00:00:00 """ queue = Queue(connection=self.connection) registry = ScheduledJobRegistry(queue=queue) worker = Worker(queue, connection=self.connection) scheduler = RQScheduler(queue, self.connection) self.assertEqual(len(queue), 0) self.assertEqual(len(registry), 0) runner = CliRunner() result = runner.invoke( main, ['enqueue', '-u', self.redis_url, 'tests.fixtures.say_hello', '--schedule-at', '2021-01-01T00:00:00'] ) self.assert_normal_execution(result) scheduler.acquire_locks() self.assertEqual(len(queue), 0) self.assertEqual(len(registry), 1) scheduler.enqueue_scheduled_jobs() self.assertEqual(len(queue), 1) self.assertEqual(len(registry), 0) self.assertTrue(worker.work(True)) self.assertEqual(len(queue), 0) self.assertEqual(len(registry), 0) result = runner.invoke( main, ['enqueue', '-u', self.redis_url, 'tests.fixtures.say_hello', '--schedule-at', '2100-01-01T00:00:00'] ) self.assert_normal_execution(result) self.assertEqual(len(queue), 0) self.assertEqual(len(registry), 1) scheduler.enqueue_scheduled_jobs() self.assertEqual(len(queue), 0) self.assertEqual(len(registry), 1) self.assertFalse(worker.work(True)) def test_cli_enqueue_retry(self): """rq enqueue -u <url> tests.fixtures.say_hello --retry-max 3 --retry-interval 10 --retry-interval 20 --retry-interval 40""" queue = Queue(connection=self.connection) self.assertTrue(queue.is_empty()) runner = CliRunner() result = runner.invoke( main, [ 'enqueue', '-u', self.redis_url, 'tests.fixtures.say_hello', '--retry-max', '3', '--retry-interval', '10', '--retry-interval', '20', '--retry-interval', '40', ], ) self.assert_normal_execution(result) job = Job.fetch( self.connection.lrange('rq:queue:default', 0, -1)[0].decode('ascii'), connection=self.connection ) self.assertEqual(job.retries_left, 3) self.assertEqual(job.retry_intervals, [10, 20, 40]) def test_cli_enqueue_errors(self): """ rq enqueue -u <url> tests.fixtures.echo :invalid_json rq enqueue -u <url> tests.fixtures.echo %invalid_eval_statement rq enqueue -u <url> tests.fixtures.echo key=value key=value rq enqueue -u <url> tests.fixtures.echo --schedule-in 1s --schedule-at 2000-01-01T00:00:00 rq enqueue -u <url> tests.fixtures.echo @not_existing_file """ runner = CliRunner() result = runner.invoke(main, ['enqueue', '-u', self.redis_url, 'tests.fixtures.echo', ':invalid_json']) self.assertNotEqual(result.exit_code, 0) self.assertIn('Unable to parse 1. non keyword argument as JSON.', result.output) result = runner.invoke( main, ['enqueue', '-u', self.redis_url, 'tests.fixtures.echo', '%invalid_eval_statement'] ) self.assertNotEqual(result.exit_code, 0) self.assertIn('Unable to eval 1. non keyword argument as Python object.', result.output) result = runner.invoke(main, ['enqueue', '-u', self.redis_url, 'tests.fixtures.echo', 'key=value', 'key=value']) self.assertNotEqual(result.exit_code, 0) self.assertIn("You can't specify multiple values for the same keyword.", result.output) result = runner.invoke( main, [ 'enqueue', '-u', self.redis_url, 'tests.fixtures.echo', '--schedule-in', '1s', '--schedule-at', '2000-01-01T00:00:00', ], ) self.assertNotEqual(result.exit_code, 0) self.assertIn("You can't specify both --schedule-in and --schedule-at", result.output) result = runner.invoke(main, ['enqueue', '-u', self.redis_url, 'tests.fixtures.echo', '@not_existing_file']) self.assertNotEqual(result.exit_code, 0) self.assertIn('Not found', result.output) def test_parse_schedule(self): """executes the rq.cli.helpers.parse_schedule function""" self.assertEqual(parse_schedule(None, '2000-01-23T23:45:01'), datetime(2000, 1, 23, 23, 45, 1)) start = datetime.now(timezone.utc) + timedelta(minutes=5) middle = parse_schedule('5m', None) end = datetime.now(timezone.utc) + timedelta(minutes=5) assert middle is not None and start is not None self.assertGreater(middle, start) self.assertLess(middle, end) def test_parse_function_arg(self): """executes the rq.cli.helpers.parse_function_arg function""" self.assertEqual(parse_function_arg('abc', 0), (None, 'abc')) self.assertEqual(parse_function_arg(':{"json": true}', 1), (None, {'json': True})) self.assertEqual(parse_function_arg('%1, 2', 2), (None, (1, 2))) self.assertEqual(parse_function_arg('key=value', 3), ('key', 'value')) self.assertEqual(parse_function_arg('jsonkey:=["json", "value"]', 4), ('jsonkey', ['json', 'value'])) self.assertEqual(parse_function_arg('evalkey%=1.2', 5), ('evalkey', 1.2)) self.assertEqual(parse_function_arg(':@tests/test.json', 6), (None, {'test': True})) self.assertEqual(parse_function_arg('@tests/test.json', 7), (None, '{"test": true}\n')) def test_cli_enqueue_doc_test(self): """tests the examples of the documentation""" runner = CliRunner() id = str(uuid4()) result = runner.invoke(main, ['enqueue', '-u', self.redis_url, '--job-id', id, 'tests.fixtures.echo', 'abc']) self.assert_normal_execution(result) job = Job.fetch(id, connection=self.connection) self.assertEqual((job.args, job.kwargs), (['abc'], {})) id = str(uuid4()) result = runner.invoke( main, ['enqueue', '-u', self.redis_url, '--job-id', id, 'tests.fixtures.echo', 'abc=def'] ) self.assert_normal_execution(result) job = Job.fetch(id, connection=self.connection) self.assertEqual((job.args, job.kwargs), ([], {'abc': 'def'})) id = str(uuid4()) result = runner.invoke( main, ['enqueue', '-u', self.redis_url, '--job-id', id, 'tests.fixtures.echo', ':{"json": "abc"}'] ) self.assert_normal_execution(result) job = Job.fetch(id, connection=self.connection) self.assertEqual((job.args, job.kwargs), ([{'json': 'abc'}], {})) id = str(uuid4()) result = runner.invoke( main, ['enqueue', '-u', self.redis_url, '--job-id', id, 'tests.fixtures.echo', 'key:={"json": "abc"}'] ) self.assert_normal_execution(result) job = Job.fetch(id, connection=self.connection) self.assertEqual((job.args, job.kwargs), ([], {'key': {'json': 'abc'}})) id = str(uuid4()) result = runner.invoke(main, ['enqueue', '-u', self.redis_url, '--job-id', id, 'tests.fixtures.echo', '%1, 2']) self.assert_normal_execution(result) job = Job.fetch(id, connection=self.connection) self.assertEqual((job.args, job.kwargs), ([(1, 2)], {})) id = str(uuid4()) result = runner.invoke(main, ['enqueue', '-u', self.redis_url, '--job-id', id, 'tests.fixtures.echo', '%None']) self.assert_normal_execution(result) job = Job.fetch(id, connection=self.connection) self.assertEqual((job.args, job.kwargs), ([None], {})) id = str(uuid4()) result = runner.invoke(main, ['enqueue', '-u', self.redis_url, '--job-id', id, 'tests.fixtures.echo', '%True']) self.assert_normal_execution(result) job = Job.fetch(id, connection=self.connection) self.assertEqual((job.args, job.kwargs), ([True], {})) id = str(uuid4()) result = runner.invoke( main, ['enqueue', '-u', self.redis_url, '--job-id', id, 'tests.fixtures.echo', 'key%=(1, 2)'] ) self.assert_normal_execution(result) job = Job.fetch(id, connection=self.connection) self.assertEqual((job.args, job.kwargs), ([], {'key': (1, 2)})) id = str(uuid4()) result = runner.invoke( main, ['enqueue', '-u', self.redis_url, '--job-id', id, 'tests.fixtures.echo', 'key%={"foo": True}'] ) self.assert_normal_execution(result) job = Job.fetch(id, connection=self.connection) self.assertEqual((job.args, job.kwargs), ([], {'key': {'foo': True}})) id = str(uuid4()) result = runner.invoke( main, ['enqueue', '-u', self.redis_url, '--job-id', id, 'tests.fixtures.echo', '@tests/test.json'] ) self.assert_normal_execution(result) job = Job.fetch(id, connection=self.connection) self.assertEqual((job.args, job.kwargs), ([open('tests/test.json').read()], {})) id = str(uuid4()) result = runner.invoke( main, ['enqueue', '-u', self.redis_url, '--job-id', id, 'tests.fixtures.echo', 'key=@tests/test.json'] ) self.assert_normal_execution(result) job = Job.fetch(id, connection=self.connection) self.assertEqual((job.args, job.kwargs), ([], {'key': open('tests/test.json').read()})) id = str(uuid4()) result = runner.invoke( main, ['enqueue', '-u', self.redis_url, '--job-id', id, 'tests.fixtures.echo', ':@tests/test.json'] ) self.assert_normal_execution(result) job = Job.fetch(id, connection=self.connection) self.assertEqual((job.args, job.kwargs), ([json.loads(open('tests/test.json').read())], {})) id = str(uuid4()) result = runner.invoke( main, ['enqueue', '-u', self.redis_url, '--job-id', id, 'tests.fixtures.echo', 'key:=@tests/test.json'] ) self.assert_normal_execution(result) job = Job.fetch(id, connection=self.connection) self.assertEqual((job.args, job.kwargs), ([], {'key': json.loads(open('tests/test.json').read())}))
TestRQCli
python
kubernetes-client__python
kubernetes/client/models/v1alpha1_cluster_trust_bundle_list.py
{ "start": 383, "end": 7259 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'api_version': 'str', 'items': 'list[V1alpha1ClusterTrustBundle]', 'kind': 'str', 'metadata': 'V1ListMeta' } attribute_map = { 'api_version': 'apiVersion', 'items': 'items', 'kind': 'kind', 'metadata': 'metadata' } def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501 """V1alpha1ClusterTrustBundleList - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._api_version = None self._items = None self._kind = None self._metadata = None self.discriminator = None if api_version is not None: self.api_version = api_version self.items = items if kind is not None: self.kind = kind if metadata is not None: self.metadata = metadata @property def api_version(self): """Gets the api_version of this V1alpha1ClusterTrustBundleList. # noqa: E501 APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :return: The api_version of this V1alpha1ClusterTrustBundleList. # noqa: E501 :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """Sets the api_version of this V1alpha1ClusterTrustBundleList. APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :param api_version: The api_version of this V1alpha1ClusterTrustBundleList. # noqa: E501 :type: str """ self._api_version = api_version @property def items(self): """Gets the items of this V1alpha1ClusterTrustBundleList. # noqa: E501 items is a collection of ClusterTrustBundle objects # noqa: E501 :return: The items of this V1alpha1ClusterTrustBundleList. # noqa: E501 :rtype: list[V1alpha1ClusterTrustBundle] """ return self._items @items.setter def items(self, items): """Sets the items of this V1alpha1ClusterTrustBundleList. items is a collection of ClusterTrustBundle objects # noqa: E501 :param items: The items of this V1alpha1ClusterTrustBundleList. # noqa: E501 :type: list[V1alpha1ClusterTrustBundle] """ if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501 raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501 self._items = items @property def kind(self): """Gets the kind of this V1alpha1ClusterTrustBundleList. # noqa: E501 Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :return: The kind of this V1alpha1ClusterTrustBundleList. # noqa: E501 :rtype: str """ return self._kind @kind.setter def kind(self, kind): """Sets the kind of this V1alpha1ClusterTrustBundleList. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :param kind: The kind of this V1alpha1ClusterTrustBundleList. # noqa: E501 :type: str """ self._kind = kind @property def metadata(self): """Gets the metadata of this V1alpha1ClusterTrustBundleList. # noqa: E501 :return: The metadata of this V1alpha1ClusterTrustBundleList. # noqa: E501 :rtype: V1ListMeta """ return self._metadata @metadata.setter def metadata(self, metadata): """Sets the metadata of this V1alpha1ClusterTrustBundleList. :param metadata: The metadata of this V1alpha1ClusterTrustBundleList. # noqa: E501 :type: V1ListMeta """ self._metadata = metadata 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, V1alpha1ClusterTrustBundleList): 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, V1alpha1ClusterTrustBundleList): return True return self.to_dict() != other.to_dict()
V1alpha1ClusterTrustBundleList
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol3.py
{ "start": 2619, "end": 2656 }
class ____(Protocol): x: str
Proto7
python
tox-dev__tox
src/tox/tox_env/errors.py
{ "start": 69, "end": 152 }
class ____(Exception): # noqa: N818 """Recreate the tox environment."""
Recreate
python
charliermarsh__ruff
crates/ruff_python_formatter/resources/test/fixtures/ruff/fmt_on_off/fmt_off_unclosed_trailing_comment.py
{ "start": 126, "end": 162 }
class ____: x: int # Optional[int]
A
python
pypa__warehouse
tests/unit/admin/test_bans.py
{ "start": 193, "end": 1257 }
class ____: def test_no_ip_not_banned(self, db_request): assert not db_request.banned.by_ip("4.3.2.1") def test_with_ip_not_banned(self, db_request): assert not db_request.banned.by_ip(db_request.ip_address.ip_address) def test_with_ip_banned(self, db_request): user_service = pretend.stub( _hit_ratelimits=pretend.call_recorder(lambda userid=None: None), _check_ratelimits=pretend.call_recorder( lambda userid=None, tags=None: None ), ) db_request.find_service = lambda service_name, context=None: user_service ip_addy = IpAddressFactory( is_banned=True, ban_reason=BanReason.AUTHENTICATION_ATTEMPTS, ban_date=sql.func.now(), ) assert db_request.banned.by_ip(ip_addy.ip_address) assert user_service._hit_ratelimits.calls == [pretend.call(userid=None)] assert user_service._check_ratelimits.calls == [ pretend.call(userid=None, tags=["banned:by_ip"]) ]
TestAdminFlag
python
getsentry__sentry
src/sentry/api/endpoints/relay/public_keys.py
{ "start": 421, "end": 1558 }
class ____(Endpoint): publish_status = { "POST": ApiPublishStatus.PRIVATE, } authentication_classes = (RelayAuthentication,) permission_classes = (RelayPermission,) enforce_rate_limit = False owner = ApiOwner.OWNERS_INGEST def post(self, request: Request) -> Response: calling_relay = request.relay relay_ids = request.relay_request_data.get("relay_ids") or () legacy_public_keys = dict.fromkeys(relay_ids) public_keys = dict.fromkeys(relay_ids) if relay_ids: relays = Relay.objects.filter(relay_id__in=relay_ids) for relay in relays: pk = relay.public_key relay_id = relay.relay_id legacy_public_keys[relay_id] = pk public_keys[relay_id] = { "publicKey": pk, # only expose internal information to internal relays "internal": relay.is_internal and calling_relay.is_internal, } return Response({"public_keys": legacy_public_keys, "relays": public_keys}, status=200)
RelayPublicKeysEndpoint
python
wandb__wandb
wandb/vendor/pygments/lexers/erlang.py
{ "start": 578, "end": 5972 }
class ____(RegexLexer): """ For the Erlang functional programming language. Blame Jeremy Thurgood (http://jerith.za.net/). .. versionadded:: 0.9 """ name = 'Erlang' aliases = ['erlang'] filenames = ['*.erl', '*.hrl', '*.es', '*.escript'] mimetypes = ['text/x-erlang'] keywords = ( 'after', 'begin', 'case', 'catch', 'cond', 'end', 'fun', 'if', 'let', 'of', 'query', 'receive', 'try', 'when', ) builtins = ( # See erlang(3) man page 'abs', 'append_element', 'apply', 'atom_to_list', 'binary_to_list', 'bitstring_to_list', 'binary_to_term', 'bit_size', 'bump_reductions', 'byte_size', 'cancel_timer', 'check_process_code', 'delete_module', 'demonitor', 'disconnect_node', 'display', 'element', 'erase', 'exit', 'float', 'float_to_list', 'fun_info', 'fun_to_list', 'function_exported', 'garbage_collect', 'get', 'get_keys', 'group_leader', 'hash', 'hd', 'integer_to_list', 'iolist_to_binary', 'iolist_size', 'is_atom', 'is_binary', 'is_bitstring', 'is_boolean', 'is_builtin', 'is_float', 'is_function', 'is_integer', 'is_list', 'is_number', 'is_pid', 'is_port', 'is_process_alive', 'is_record', 'is_reference', 'is_tuple', 'length', 'link', 'list_to_atom', 'list_to_binary', 'list_to_bitstring', 'list_to_existing_atom', 'list_to_float', 'list_to_integer', 'list_to_pid', 'list_to_tuple', 'load_module', 'localtime_to_universaltime', 'make_tuple', 'md5', 'md5_final', 'md5_update', 'memory', 'module_loaded', 'monitor', 'monitor_node', 'node', 'nodes', 'open_port', 'phash', 'phash2', 'pid_to_list', 'port_close', 'port_command', 'port_connect', 'port_control', 'port_call', 'port_info', 'port_to_list', 'process_display', 'process_flag', 'process_info', 'purge_module', 'put', 'read_timer', 'ref_to_list', 'register', 'resume_process', 'round', 'send', 'send_after', 'send_nosuspend', 'set_cookie', 'setelement', 'size', 'spawn', 'spawn_link', 'spawn_monitor', 'spawn_opt', 'split_binary', 'start_timer', 'statistics', 'suspend_process', 'system_flag', 'system_info', 'system_monitor', 'system_profile', 'term_to_binary', 'tl', 'trace', 'trace_delivered', 'trace_info', 'trace_pattern', 'trunc', 'tuple_size', 'tuple_to_list', 'universaltime_to_localtime', 'unlink', 'unregister', 'whereis' ) operators = r'(\+\+?|--?|\*|/|<|>|/=|=:=|=/=|=<|>=|==?|<-|!|\?)' word_operators = ( 'and', 'andalso', 'band', 'bnot', 'bor', 'bsl', 'bsr', 'bxor', 'div', 'not', 'or', 'orelse', 'rem', 'xor' ) atom_re = r"(?:[a-z]\w*|'[^\n']*[^\\]')" variable_re = r'(?:[A-Z_]\w*)' esc_char_re = r'[bdefnrstv\'"\\]' esc_octal_re = r'[0-7][0-7]?[0-7]?' esc_hex_re = r'(?:x[0-9a-fA-F]{2}|x\{[0-9a-fA-F]+\})' esc_ctrl_re = r'\^[a-zA-Z]' escape_re = r'(?:\\(?:'+esc_char_re+r'|'+esc_octal_re+r'|'+esc_hex_re+r'|'+esc_ctrl_re+r'))' macro_re = r'(?:'+variable_re+r'|'+atom_re+r')' base_re = r'(?:[2-9]|[12][0-9]|3[0-6])' tokens = { 'root': [ (r'\s+', Text), (r'%.*\n', Comment), (words(keywords, suffix=r'\b'), Keyword), (words(builtins, suffix=r'\b'), Name.Builtin), (words(word_operators, suffix=r'\b'), Operator.Word), (r'^-', Punctuation, 'directive'), (operators, Operator), (r'"', String, 'string'), (r'<<', Name.Label), (r'>>', Name.Label), ('(' + atom_re + ')(:)', bygroups(Name.Namespace, Punctuation)), ('(?:^|(?<=:))(' + atom_re + r')(\s*)(\()', bygroups(Name.Function, Text, Punctuation)), (r'[+-]?' + base_re + r'#[0-9a-zA-Z]+', Number.Integer), (r'[+-]?\d+', Number.Integer), (r'[+-]?\d+.\d+', Number.Float), (r'[]\[:_@\".{}()|;,]', Punctuation), (variable_re, Name.Variable), (atom_re, Name), (r'\?'+macro_re, Name.Constant), (r'\$(?:'+escape_re+r'|\\[ %]|[^\\])', String.Char), (r'#'+atom_re+r'(:?\.'+atom_re+r')?', Name.Label), # Erlang script shebang (r'\A#!.+\n', Comment.Hashbang), # EEP 43: Maps # http://www.erlang.org/eeps/eep-0043.html (r'#\{', Punctuation, 'map_key'), ], 'string': [ (escape_re, String.Escape), (r'"', String, '#pop'), (r'~[0-9.*]*[~#+BPWXb-ginpswx]', String.Interpol), (r'[^"\\~]+', String), (r'~', String), ], 'directive': [ (r'(define)(\s*)(\()('+macro_re+r')', bygroups(Name.Entity, Text, Punctuation, Name.Constant), '#pop'), (r'(record)(\s*)(\()('+macro_re+r')', bygroups(Name.Entity, Text, Punctuation, Name.Label), '#pop'), (atom_re, Name.Entity, '#pop'), ], 'map_key': [ include('root'), (r'=>', Punctuation, 'map_val'), (r':=', Punctuation, 'map_val'), (r'\}', Punctuation, '#pop'), ], 'map_val': [ include('root'), (r',', Punctuation, '#pop'), (r'(?=\})', Punctuation, '#pop'), ], }
ErlangLexer
python
ApeWorX__ape
src/ape/pytest/utils.py
{ "start": 24, "end": 285 }
class ____(int, Enum): SESSION = 0 PACKAGE = 1 MODULE = 2 CLASS = 3 FUNCTION = 4 def __str__(self) -> str: return self.name.lower() @property def isolation_fixturename(self) -> str: return f"_{self}_isolation"
Scope
python
jina-ai__jina
jina/clients/grpc.py
{ "start": 189, "end": 781 }
class ____(GRPCBaseClient, PostMixin, HealthCheckMixin, ProfileMixin): """A client connecting to a Gateway using gRPC protocol. Instantiate this class through the :meth:`jina.Client` convenience method. EXAMPLE USAGE .. code-block:: python from jina import Client from docarray import Document # select host address to connect to c = Client( protocol='grpc', asyncio=False, host='grpc://my.awesome.flow:1234' ) # returns GRPCClient instance c.post(on='/index', inputs=Document(text='hello!')) """
GRPCClient
python
pennersr__django-allauth
allauth/socialaccount/providers/dingtalk/client.py
{ "start": 140, "end": 1345 }
class ____(OAuth2Client): def get_access_token(self, code, pkce_code_verifier=None): data = { "clientId": self.consumer_key, "clientSecret": self.consumer_secret, "code": code, "grantType": "authorization_code", } params = None if pkce_code_verifier: data["code_verifier"] = pkce_code_verifier self._strip_empty_keys(data) url = self.access_token_url if self.access_token_method == "GET": # nosec params = data data = None resp = ( get_adapter() .get_requests_session() .request(self.access_token_method, url, params=params, json=data) ) resp.raise_for_status() access_token = resp.json() if not access_token or "accessToken" not in access_token: raise OAuth2Error("Error retrieving access token: %s" % resp.content) access_token["access_token"] = access_token.pop("accessToken") access_token["refresh_token"] = access_token.pop("refreshToken") access_token["expires_in"] = access_token.pop("expireIn") return access_token
DingTalkOAuth2Client
python
getsentry__sentry
src/sentry/integrations/discord/integration.py
{ "start": 4958, "end": 11261 }
class ____(IntegrationProvider): key = IntegrationProviderSlug.DISCORD.value name = "Discord" metadata = metadata integration_cls = DiscordIntegration features = frozenset([IntegrationFeatures.CHAT_UNFURL, IntegrationFeatures.ALERT_RULE]) # https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes oauth_scopes = frozenset(["applications.commands", "bot", "identify", "guilds.members.read"]) access_token = "" bot_permissions = ( DiscordPermissions.VIEW_CHANNEL.value | DiscordPermissions.SEND_MESSAGES.value | DiscordPermissions.EMBED_LINKS.value | DiscordPermissions.CREATE_PUBLIC_THREADS.value | DiscordPermissions.CREATE_PRIVATE_THREADS.value | DiscordPermissions.SEND_MESSAGES_IN_THREADS.value ) setup_dialog_config = {"width": 600, "height": 900} def __init__(self) -> None: self.application_id = options.get("discord.application-id") self.public_key = options.get("discord.public-key") self.bot_token = options.get("discord.bot-token") self.client_secret = options.get("discord.client-secret") self.client = DiscordClient() self.setup_url = absolute_uri("extensions/discord/setup/") self.configure_url = absolute_uri("extensions/discord/configure/") super().__init__() def get_pipeline_views(self) -> Sequence[PipelineView[IntegrationPipeline]]: return [DiscordInstallPipeline(self.get_params_for_oauth())] def build_integration(self, state: Mapping[str, Any]) -> IntegrationData: guild_id = str(state.get("guild_id")) if not guild_id.isdigit(): raise IntegrationError( "Invalid guild ID. The Discord guild ID must be entirely numeric." ) try: guild_name = self.client.get_guild_name(guild_id=guild_id) except (ApiError, AttributeError): guild_name = guild_id discord_config = state.get(IntegrationProviderSlug.DISCORD.value, {}) if isinstance(discord_config, dict): use_configure = discord_config.get("use_configure") == "1" else: use_configure = False url = self.configure_url if use_configure else self.setup_url auth_code = str(state.get("code")) if auth_code: discord_user_id = self._get_discord_user_id(auth_code, url) if not self.client.check_user_bot_installation_permission( access_token=self.access_token, guild_id=guild_id ): raise IntegrationError("User does not have permissions to install bot.") else: raise IntegrationError("Missing code from state.") return { "name": guild_name, "external_id": guild_id, "user_identity": { "type": IntegrationProviderSlug.DISCORD.value, "external_id": discord_user_id, "scopes": [], "data": {}, }, } def _has_application_commands(self) -> bool: try: return self.client.has_application_commands() except ApiError as e: logger.error( "discord.fail.setup.get_application_commands", extra={ "status": e.code, "error": str(e), "application_id": self.application_id, }, ) raise ApiError(str(e)) def post_install( self, integration: Integration, organization: RpcOrganization, *, extra: dict[str, Any], ) -> None: if self._credentials_exist() and not self._has_application_commands(): try: for command in COMMANDS: self.client.set_application_command(command) except ApiError as e: logger.error( "discord.fail.setup.set_application_command", extra={ "status": e.code, "error": str(e), "application_id": self.application_id, }, ) raise ApiError(str(e)) def _get_discord_user_id(self, auth_code: str, url: str) -> str: """ Helper function for completing the oauth2 flow and grabbing the installing user's Discord user id so we can link their identities. We don't keep the granted token beyond this function because we don't need it. If something goes wrong with this we will throw an error because we need an initial identity to configure the identity provider for this integration. """ try: self.access_token = self.client.get_access_token(auth_code, url) except ApiError: raise IntegrationError("Failed to get Discord access token from API.") except KeyError: raise IntegrationError("Failed to get Discord access token from key.") try: user_id = self.client.get_user_id(self.access_token) except ApiError: raise IntegrationError("Failed to get Discord user ID from API.") except KeyError: raise IntegrationError("Failed to get Discord user ID from key.") return user_id def get_params_for_oauth( self, ): return { "client_id": self.application_id, "permissions": self.bot_permissions, "scope": " ".join(self.oauth_scopes), "response_type": "code", } def _credentials_exist(self) -> bool: has_credentials = all( (self.application_id, self.public_key, self.bot_token, self.client_secret) ) if not has_credentials: logger.error( "discord.install.fail.credentials_exist", extra={ "application_id": self.application_id, "has_public_key": bool(self.public_key), "has_bot_token": bool(self.bot_token), "has_client_secret": bool(self.client_secret), }, ) return has_credentials
DiscordIntegrationProvider
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/freshness_policy.py
{ "start": 173, "end": 576 }
class ____(graphene.ObjectType): # How old is the current data currentLagMinutes = graphene.Field(graphene.Float) # How overdue is the current data (currentLagMinutes - maximumLagMinutes) currentMinutesLate = graphene.Field(graphene.Float) latestMaterializationMinutesLate = graphene.Field(graphene.Float) class Meta: name = "AssetFreshnessInfo"
GrapheneAssetFreshnessInfo
python
getsentry__sentry
src/sentry/grouping/enhancer/matchers.py
{ "start": 12454, "end": 12517 }
class ____(FrameFieldMatch): field = "category"
CategoryMatch
python
PyCQA__pylint
tests/functional/n/no/no_member_decorator.py
{ "start": 77, "end": 450 }
class ____: # pylint: disable=too-few-public-methods """https://github.com/pylint-dev/pylint/issues/9246""" @classmethod @lru_cache def __cached_fun(cls, arg: int) -> str: return str(arg) @classmethod def cache_clear(cls): """__cached_fun()'s @cache decorator supplies cache_clear().""" cls.__cached_fun.cache_clear()
SomeClass
python
airbytehq__airbyte
airbyte-integrations/connectors/source-iterable/source_iterable/streams.py
{ "start": 18464, "end": 18559 }
class ____(IterableExportEventsStreamAdjustableRange): data_field = "smsSendSkip"
SmsSendSkip
python
openai__openai-python
src/openai/resources/uploads/parts.py
{ "start": 7283, "end": 7488 }
class ____: def __init__(self, parts: Parts) -> None: self._parts = parts self.create = _legacy_response.to_raw_response_wrapper( parts.create, )
PartsWithRawResponse
python
fastai__fastai
fastai/data/core.py
{ "start": 19553, "end": 24416 }
class ____(FilteredBase): "A dataset that creates a tuple from each `tfms`" def __init__(self, items:list=None, # List of items to create `Datasets` tfms:MutableSequence|Pipeline=None, # List of `Transform`(s) or `Pipeline` to apply tls:TfmdLists=None, # If None, `self.tls` is generated from `items` and `tfms` n_inp:int=None, # Number of elements in `Datasets` tuple that should be considered part of input dl_type=None, # Default type of `DataLoader` used when function `FilteredBase.dataloaders` is called **kwargs ): super().__init__(dl_type=dl_type) self.tls = L(tls if tls else [TfmdLists(items, t, **kwargs) for t in L(ifnone(tfms,[None]))]) self.n_inp = ifnone(n_inp, max(1, len(self.tls)-1)) def __getitem__(self, it): res = tuple([tl[it] for tl in self.tls]) return res if is_indexer(it) else list(zip(*res)) def __getattr__(self,k): return gather_attrs(self, k, 'tls') def __dir__(self): return super().__dir__() + gather_attr_names(self, 'tls') def __len__(self): return len(self.tls[0]) def __iter__(self): return (self[i] for i in range(len(self))) def __repr__(self): return coll_repr(self) def decode(self, o, full=True): return tuple(tl.decode(o_, full=full) for o_,tl in zip(o,tuplify(self.tls, match=o))) def subset(self, i): return type(self)(tls=L(tl.subset(i) for tl in self.tls), n_inp=self.n_inp) def _new(self, items, *args, **kwargs): return super()._new(items, tfms=self.tfms, do_setup=False, **kwargs) def overlapping_splits(self): return self.tls[0].overlapping_splits() def new_empty(self): return type(self)(tls=[tl.new_empty() for tl in self.tls], n_inp=self.n_inp) @property def splits(self): return self.tls[0].splits @property def split_idx(self): return self.tls[0].tfms.split_idx @property def items(self): return self.tls[0].items @items.setter def items(self, v): for tl in self.tls: tl.items = v def show(self, o, ctx=None, **kwargs): for o_,tl in zip(o,self.tls): ctx = tl.show(o_, ctx=ctx, **kwargs) return ctx @contextmanager def set_split_idx(self, i): old_split_idx = self.split_idx for tl in self.tls: tl.tfms.split_idx = i try: yield self finally: for tl in self.tls: tl.tfms.split_idx = old_split_idx _docs=dict( decode="Compose `decode` of all `tuple_tfms` then all `tfms` on `i`", show="Show item `o` in `ctx`", dataloaders="Get a `DataLoaders`", overlapping_splits="All splits that are in more than one split", subset="New `Datasets` that only includes subset `i`", new_empty="Create a new empty version of the `self`, keeping only the transforms", set_split_idx="Contextmanager to use the same `Datasets` with another `split_idx`" ) # %% ../../nbs/03_data.core.ipynb 108 def test_set( dsets:Datasets|TfmdLists, # Map- or iterable-style dataset from which to load the data test_items, # Items in test dataset rm_tfms=None, # Start index of `Transform`(s) from validation set in `dsets` to apply with_labels:bool=False # Whether the test items contain labels ): "Create a test set from `test_items` using validation transforms of `dsets`" if isinstance(dsets, Datasets): tls = dsets.tls if with_labels else dsets.tls[:dsets.n_inp] test_tls = [tl._new(test_items, split_idx=1) for tl in tls] if rm_tfms is None: rm_tfms = [tl.infer_idx(get_first(test_items)) for tl in test_tls] else: rm_tfms = tuplify(rm_tfms, match=test_tls) for i,j in enumerate(rm_tfms): test_tls[i].tfms.fs = test_tls[i].tfms.fs[j:] return Datasets(tls=test_tls) elif isinstance(dsets, TfmdLists): test_tl = dsets._new(test_items, split_idx=1) if rm_tfms is None: rm_tfms = dsets.infer_idx(get_first(test_items)) test_tl.tfms.fs = test_tl.tfms.fs[rm_tfms:] return test_tl else: raise Exception(f"This method requires using the fastai library to assemble your data. Expected a `Datasets` or a `TfmdLists` but got {dsets.__class__.__name__}") # %% ../../nbs/03_data.core.ipynb 113 @patch @delegates(TfmdDL.__init__) def test_dl(self:DataLoaders, test_items, # Items in test dataset rm_type_tfms=None, # Start index of `Transform`(s) from validation set in `dsets` to apply with_labels:bool=False, # Whether the test items contain labels **kwargs ): "Create a test dataloader from `test_items` using validation transforms of `dls`" test_ds = test_set(self.valid_ds, test_items, rm_tfms=rm_type_tfms, with_labels=with_labels ) if isinstance(self.valid_ds, (Datasets, TfmdLists)) else test_items return self.valid.new(test_ds, **kwargs)
Datasets
python
scipy__scipy
scipy/sparse/linalg/_interface.py
{ "start": 21317, "end": 21821 }
class ____(LinearOperator): """Adjoint of arbitrary Linear Operator""" def __init__(self, A): shape = (A.shape[1], A.shape[0]) super().__init__(dtype=A.dtype, shape=shape) self.A = A self.args = (A,) def _matvec(self, x): return self.A._rmatvec(x) def _rmatvec(self, x): return self.A._matvec(x) def _matmat(self, x): return self.A._rmatmat(x) def _rmatmat(self, x): return self.A._matmat(x)
_AdjointLinearOperator
python
getsentry__sentry
src/sentry/data_export/endpoints/data_export.py
{ "start": 1921, "end": 10420 }
class ____(serializers.Serializer[dict[str, Any]]): query_type = serializers.ChoiceField(choices=ExportQueryType.as_str_choices(), required=True) query_info = serializers.JSONField(required=True) def validate(self, data: dict[str, Any]) -> dict[str, Any]: organization = self.context["organization"] has_metrics = self.context["has_metrics"] query_info = data["query_info"] # Validate the project field, if provided # A PermissionDenied error will be raised in `get_projects_by_id` if the request is invalid project_query = query_info.get("project") if project_query: get_projects_by_id = self.context["get_projects_by_id"] # Coerce the query into a set if isinstance(project_query, list): projects = get_projects_by_id(set(map(int, project_query))) else: projects = get_projects_by_id({int(project_query)}) query_info["project"] = [project.id for project in projects] # Discover Pre-processing if data["query_type"] == ExportQueryType.DISCOVER_STR: # coerce the fields into a list as needed base_fields = query_info.get("field", []) if not isinstance(base_fields, list): base_fields = [base_fields] equations, fields = categorize_columns(base_fields) if len(base_fields) > MAX_FIELDS: detail = f"You can export up to {MAX_FIELDS} fields at a time. Please delete some and try again." raise serializers.ValidationError(detail) elif len(base_fields) == 0: raise serializers.ValidationError("at least one field is required to export") if "query" not in query_info: detail = "query is a required to export, please pass an empty string if you don't want to set one" raise serializers.ValidationError(detail) query_info["field"] = fields query_info["equations"] = equations if not query_info.get("project"): projects = self.context["get_projects"]() query_info["project"] = [project.id for project in projects] # make sure to fix the export start/end times to ensure consistent results try: start, end = get_date_range_from_params(query_info) except InvalidParams as e: sentry_sdk.set_tag("query.error_reason", "Invalid date params") raise serializers.ValidationError(str(e)) if "statsPeriod" in query_info: del query_info["statsPeriod"] if "statsPeriodStart" in query_info: del query_info["statsPeriodStart"] if "statsPeriodEnd" in query_info: del query_info["statsPeriodEnd"] query_info["start"] = start.isoformat() query_info["end"] = end.isoformat() dataset = query_info.get("dataset", "discover") if dataset not in SUPPORTED_DATASETS: raise serializers.ValidationError(f"{dataset} is not supported for csv exports") # validate the query string by trying to parse it processor = DiscoverProcessor( discover_query=query_info, organization=organization, ) try: query_builder_cls = DiscoverQueryBuilder config = QueryBuilderConfig( auto_fields=True, auto_aggregations=True, has_metrics=has_metrics, ) if dataset == "errors": query_builder_cls = ErrorsQueryBuilder config.parser_config_overrides = PARSER_CONFIG_OVERRIDES builder = query_builder_cls( SUPPORTED_DATASETS[dataset], params={}, snuba_params=processor.snuba_params, query=query_info["query"], selected_columns=fields.copy(), equations=equations, config=config, ) builder.get_snql_query() except InvalidSearchQuery as err: raise serializers.ValidationError(str(err)) elif data["query_type"] == ExportQueryType.EXPLORE_STR: # coerce the fields into a list as needed base_fields = query_info.get("field", []) if not isinstance(base_fields, list): base_fields = [base_fields] equations, fields = categorize_columns(base_fields) if len(base_fields) > MAX_FIELDS: detail = f"You can export up to {MAX_FIELDS} fields at a time. Please delete some and try again." raise serializers.ValidationError(detail) elif len(base_fields) == 0: raise serializers.ValidationError("at least one field is required to export") if "query" not in query_info: detail = "query is a required to export, please pass an empty string if you don't want to set one" raise serializers.ValidationError(detail) query_info["field"] = fields query_info["equations"] = equations if not query_info.get("project"): projects = self.context["get_projects"]() query_info["project"] = [project.id for project in projects] # make sure to fix the export start/end times to ensure consistent results try: start, end = get_date_range_from_params(query_info) except InvalidParams as err: sentry_sdk.set_tag("query.error_reason", "Invalid date params") raise serializers.ValidationError(str(err)) if "statsPeriod" in query_info: del query_info["statsPeriod"] if "statsPeriodStart" in query_info: del query_info["statsPeriodStart"] if "statsPeriodEnd" in query_info: del query_info["statsPeriodEnd"] query_info["start"] = start.isoformat() query_info["end"] = end.isoformat() dataset = query_info.get("dataset") if not dataset: raise serializers.ValidationError( f"Please specify dataset. Supported datasets for this query type are {str(SUPPORTED_TRACE_ITEM_DATASETS.keys())}." ) if dataset not in SUPPORTED_TRACE_ITEM_DATASETS: raise serializers.ValidationError(f"{dataset} is not supported for csv exports") sort = query_info.get("sort", []) if sort and isinstance(sort, str): sort = [sort] query_info["sort"] = sort sampling_mode = query_info.get("sampling", None) if sampling_mode is not None: if sampling_mode.upper() not in SAMPLING_MODE_MAP: raise serializers.ValidationError( f"sampling mode: {sampling_mode} is not supported" ) explore_processor = ExploreProcessor( explore_query=query_info, organization=organization, ) try: rpc_dataset_common.TableQuery( query_string=query_info["query"], selected_columns=fields, orderby=sort, offset=0, limit=1, referrer=Referrer.DATA_EXPORT_TASKS_EXPLORE, sampling_mode=explore_processor.sampling_mode, resolver=explore_processor.search_resolver, equations=equations, ) except InvalidSearchQuery as err: sentry_sdk.capture_exception(err) raise serializers.ValidationError("Invalid table query") elif data["query_type"] == ExportQueryType.ISSUES_BY_TAG_STR: issues_by_tag_validate(query_info) return data def issues_by_tag_validate(query_info: dict[str, Any]) -> None: group = query_info.get("group") if group is not None: try: query_info["group"] = int(group) except (ValueError, TypeError): raise serializers.ValidationError("Invalid group ID") @region_silo_endpoint
DataExportQuerySerializer
python
getsentry__sentry
tests/sentry/sentry_apps/api/parsers/test_markdown.py
{ "start": 201, "end": 804 }
class ____(unittest.TestCase): def setUp(self) -> None: self.schema: dict[str, Any] = { "type": "markdown", "text": """ # This Is a Title - this - is - a - list """, } def test_valid_schema(self) -> None: validate_component(self.schema) @invalid_schema def test_missing_text(self) -> None: del self.schema["text"] validate_component(self.schema) @invalid_schema def test_invalid_text_type(self) -> None: self.schema["text"] = 1 validate_component(self.schema)
TestMarkdownSchemaValidation
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_data_labels29.py
{ "start": 315, "end": 1481 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_data_labels29.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "column"}) chart.axis_ids = [67858816, 67863296] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series( { "values": "=Sheet1!$A$1:$A$5", "data_labels": {"value": True, "custom": [{"delete": 1}]}, } ) chart.add_series({"values": "=Sheet1!$B$1:$B$5"}) chart.add_series({"values": "=Sheet1!$C$1:$C$5"}) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
keras-team__keras
keras/src/distillation/distiller.py
{ "start": 301, "end": 22984 }
class ____(Model): """Distillation model for transferring knowledge from teacher to student. Knowledge distillation transfers knowledge from a large, complex model (teacher) to a smaller, simpler model (student). The student learns from both ground truth labels and the teacher's predictions, often achieving better performance than training on labels alone. Arguments: teacher: A trained `keras.Model` that serves as the knowledge source. The teacher model is frozen during distillation. student: A `keras.Model` to be trained through distillation. distillation_losses: List of distillation losses to apply. Can be a single distillation loss or a list of distillation losses like `keras.distillation.LogitsDistillation`, `keras.distillation.FeatureDistillation`, or custom distillation losses. distillation_loss_weights: List of weights for each distillation loss. Must have the same length as `distillation_losses`. If `None`, equal weights are used. student_loss_weight: Weight for the student's supervised loss component. Must be between 0 and 1. Defaults to 0.5. name: Name for the distiller model. Defaults to `"distiller"`. **kwargs: Additional keyword arguments passed to the parent `Model` class. Attributes: student: The student model being trained. Access this to get the trained student model for independent use after distillation training. teacher: The teacher model providing knowledge. This model is frozen during training. Examples: ```python # Basic distillation with KerasHub models import keras_hub as hub teacher = hub.models.CausalLM.from_preset("gemma_2b_en") student = hub.models.CausalLM.from_preset( "gemma_1.1_2b_en", load_weights=False ) # Single distillation loss distiller = Distiller( teacher=teacher, student=student, distillation_losses=LogitsDistillation(temperature=3.0), ) # Compile the distiller (like any Keras model) distiller.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) # Train the distiller distiller.fit(x_train, y_train, epochs=10) # Access the trained student model trained_student = distiller.student # Multiple distillation losses distiller = Distiller( teacher=teacher, student=student, distillation_losses=[ LogitsDistillation(temperature=3.0), FeatureDistillation( teacher_layer_name="dense_1", student_layer_name="dense_1" ) ], distillation_loss_weights=[1.0, 0.5], ) # Compile with custom settings distiller.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) ``` """ def __init__( self, teacher, student, distillation_losses, distillation_loss_weights=None, student_loss_weight=0.5, name="distiller", **kwargs, ): super().__init__(name=name, **kwargs) # Validate inputs self._validate_models(teacher, student) # Store configuration self.teacher = teacher self.student = student # Validate student_loss_weight if not isinstance(student_loss_weight, (int, float)): raise ValueError( f"student_loss_weight must be a number, got " f"{type(student_loss_weight)}" ) if student_loss_weight < 0.0 or student_loss_weight > 1.0: raise ValueError( f"student_loss_weight must be between 0.0 and 1.0, " f"got {student_loss_weight}" ) self.student_loss_weight = student_loss_weight # Handle distillation losses configuration if distillation_losses is None: raise ValueError( "'distillation_losses' cannot be `None`. Provide a " "distillation loss (e.g., LogitsDistillation or " "FeatureDistillation) or a list of distillation losses." ) # Convert single distillation loss to list for uniform handling if not isinstance(distillation_losses, (list, tuple)): self.distillation_losses = [distillation_losses] self.distillation_loss_weights = [1.0] else: self.distillation_losses = distillation_losses # Set default weights if not provided if distillation_loss_weights is None: self.distillation_loss_weights = [1.0] * len( distillation_losses ) else: if len(distillation_loss_weights) != len(distillation_losses): raise ValueError( f"Number of distillation_loss_weights " f"({len(distillation_loss_weights)}) must match " f"number of distillation_losses " f"({len(distillation_losses)})" ) self.distillation_loss_weights = distillation_loss_weights # Validate distillation loss compatibility and create extractors for distillation_loss in self.distillation_losses: self._validate_distillation_loss_compatibility( teacher, student, distillation_loss ) self._create_multi_feature_extractors() # Freeze teacher model self.teacher.trainable = False # Initialize loss tracking metrics self.student_loss_tracker = keras.metrics.Mean(name="student_loss") self.distillation_loss_tracker = keras.metrics.Mean( name="distillation_loss" ) self.total_loss_tracker = keras.metrics.Mean(name="total_loss") def _validate_models(self, teacher, student): """Validate that teacher and student models are compatible.""" if not isinstance(teacher, keras.Model): raise ValueError( f"Teacher must be a keras.Model, got {type(teacher)}" ) if not isinstance(student, keras.Model): raise ValueError( f"Student must be a keras.Model, got {type(student)}" ) self._validate_input_compatibility(teacher, student) self._validate_output_compatibility(teacher, student) self._validate_dtype_compatibility(teacher, student) def _assert_shapes_are_compatible(self, shape1, shape2, context): """Assert that two shapes are compatible.""" if len(shape1) != len(shape2): raise ValueError( f"Teacher and student {context} shapes have different " f"dimensions. Teacher: {shape1}, Student: {shape2}." ) for dim1, dim2 in zip(shape1, shape2): if dim1 is not None and dim2 is not None and dim1 != dim2: raise ValueError( f"Teacher and student {context} shapes are incompatible. " f"Teacher: {shape1}, Student: {shape2}. " f"All dimensions must match." ) def _assert_same_dtype(self, teacher_dtype, student_dtype, context): """Assert that teacher and student dtypes are the same.""" if teacher_dtype != student_dtype: raise ValueError( f"Teacher and student {context} dtypes must match. " f"Teacher: {teacher_dtype}, Student: {student_dtype}." ) def _validate_input_compatibility(self, teacher, student): """Validate that teacher and student have compatible input shapes.""" if not hasattr(teacher, "inputs") or not hasattr(student, "inputs"): return teacher_inputs = getattr(teacher, "inputs") student_inputs = getattr(student, "inputs") if teacher_inputs is None or student_inputs is None: return tree.map_structure( lambda ti, si: self._assert_shapes_are_compatible( ti.shape, si.shape, "input" ), teacher_inputs, student_inputs, ) def _validate_output_compatibility(self, teacher, student): """Validate that teacher and student have compatible output shapes.""" if not hasattr(teacher, "outputs") or not hasattr(student, "outputs"): return teacher_outputs = getattr(teacher, "outputs") student_outputs = getattr(student, "outputs") if teacher_outputs is None or student_outputs is None: return tree.map_structure( lambda to, so: self._assert_shapes_are_compatible( to.shape, so.shape, "output" ), teacher_outputs, student_outputs, ) def _validate_dtype_compatibility(self, teacher, student): """Validate that teacher and student have compatible data types.""" if not hasattr(teacher, "inputs") or not hasattr(student, "inputs"): return if teacher.inputs is None or student.inputs is None: return tree.map_structure( lambda ti, si: self._assert_same_dtype(ti.dtype, si.dtype, "input"), teacher.inputs, student.inputs, ) if not hasattr(teacher, "outputs") or not hasattr(student, "outputs"): return if teacher.outputs is None or student.outputs is None: return tree.map_structure( lambda to, so: self._assert_same_dtype( to.dtype, so.dtype, "output" ), teacher.outputs, student.outputs, ) def _validate_distillation_loss_compatibility( self, teacher, student, distillation_loss ): """Validate that the distillation loss is compatible with teacher and student models.""" distillation_loss.validate_model_compatibility(teacher, student) def _create_multi_feature_extractors(self): """Create feature extractors for efficient multi-layer extraction.""" teacher_layer_names = [] student_layer_names = [] for distillation_loss in self.distillation_losses: if ( hasattr(distillation_loss, "teacher_layer_name") and distillation_loss.teacher_layer_name ): if ( distillation_loss.teacher_layer_name not in teacher_layer_names ): teacher_layer_names.append( distillation_loss.teacher_layer_name ) if ( hasattr(distillation_loss, "student_layer_name") and distillation_loss.student_layer_name ): if ( distillation_loss.student_layer_name not in student_layer_names ): student_layer_names.append( distillation_loss.student_layer_name ) self._teacher_feature_extractor = self._create_feature_extractor( self.teacher, teacher_layer_names ) self._student_feature_extractor = self._create_feature_extractor( self.student, student_layer_names ) def _create_feature_extractor(self, model, layer_names): """Create a feature extractor for a model. Arguments: model: The model to create an extractor for. layer_names: List of layer names to extract features from. Returns: Feature extractor model or `None` if no layer names provided. Raises: ValueError: If model has no symbolic inputs/outputs. """ if not layer_names: return None if not hasattr(model, "inputs") or model.inputs is None: raise ValueError( f"Cannot create feature extractor for {model.name}. " f"The model has no symbolic inputs attribute." ) if isinstance(model, keras.Sequential): final_output = model.layers[-1].output else: final_output = model.output outputs = {"final_output": final_output} for layer_name in layer_names: layer = model.get_layer(name=layer_name) outputs[layer_name] = layer.output return keras.Model( inputs=model.inputs, outputs=outputs, name=f"{model.name}_multi_feature_extractor", ) def _extract_all_teacher_features(self, x): """Extract all teacher features in a single forward pass.""" if self._teacher_feature_extractor is not None: return self._teacher_feature_extractor(x, training=False) else: return {"final_output": self.teacher(x, training=False)} def _extract_all_student_features(self, x, y_pred): """Extract all student features in a single forward pass.""" if self._student_feature_extractor is not None: return self._student_feature_extractor(x, training=True) else: return {"final_output": y_pred} def _get_distillation_loss_features( self, distillation_loss, all_features, is_teacher ): """Get the specific features needed by a distillation loss.""" if is_teacher: layer_name = distillation_loss.teacher_layer_name or "final_output" else: layer_name = distillation_loss.student_layer_name or "final_output" if layer_name not in all_features: raise ValueError( f"Layer '{layer_name}' not found in extracted features. " f"Available: {list(all_features.keys())}" ) return all_features[layer_name] def compile(self, optimizer="adam", loss=None, metrics=None, **kwargs): """Compile the distiller with proper integration. Arguments: optimizer: Optimizer for training the student model. loss: Student loss function for the student's supervised learning. Can be a string identifier or a loss function instance. metrics: Additional metrics to track during training. **kwargs: Additional arguments passed to parent compile. """ if loss is None: raise ValueError("'loss' cannot be `None`.") self._student_loss = tree.map_structure(_convert_loss_to_function, loss) self._student_loss_for_serialization = loss if metrics is not None and not isinstance(metrics, (list, tuple)): raise ValueError( f"metrics must be a list or tuple, got {type(metrics)}" ) super().compile( optimizer=optimizer, loss=None, metrics=metrics, **kwargs, ) def call(self, inputs, training=None, **kwargs): """Forward pass returns student predictions.""" return self.student(inputs, training=training, **kwargs) def compute_loss( self, x=None, y=None, y_pred=None, sample_weight=None, training=True ): """Compute combined distillation loss. Arguments: x: Input data. y: Target data. y_pred: Model predictions. sample_weight: Sample weights (currently unused). training: Whether the model is in training mode. Returns: Combined loss tensor. """ # Handle case where y_pred is not provided if y_pred is None: y_pred = self(x, training=training) # Compute student loss student_loss = 0.0 if self.student_loss_weight > 0.0 and y is not None: loss_values = tree.map_structure( lambda l, o, o_pred: l(o, o_pred), self._student_loss, y, y_pred, ) flat_losses = tree.flatten(loss_values) student_loss = ( keras.ops.sum(keras.ops.stack(flat_losses)) if len(flat_losses) > 1 else flat_losses[0] ) # Ensure student_loss is a scalar if hasattr(student_loss, "shape") and len(student_loss.shape) > 0: student_loss = keras.ops.mean(student_loss) # Compute distillation loss distillation_loss = 0.0 if self.student_loss_weight < 1.0: teacher_features = self._extract_all_teacher_features(x) student_features = self._extract_all_student_features(x, y_pred) # Apply distillation losses using pre-extracted features for distillation_loss_fn, weight in zip( self.distillation_losses, self.distillation_loss_weights ): # Get appropriate outputs/features for this distillation loss if ( hasattr(distillation_loss_fn, "teacher_layer_name") and distillation_loss_fn.teacher_layer_name is not None ): # FeatureDistillation with specific layers try: distillation_loss_teacher_output = ( self._get_distillation_loss_features( distillation_loss_fn, teacher_features, is_teacher=True, ) ) distillation_loss_student_output = ( self._get_distillation_loss_features( distillation_loss_fn, student_features, is_teacher=False, ) ) except ValueError as e: # Re-raise with context about which loss failed raise RuntimeError( f"Failed to extract features for " f"{type(distillation_loss_fn).__name__} " f"targeting teacher layer " f"'{distillation_loss_fn.teacher_layer_name}' " f"and student layer " f"'{distillation_loss_fn.student_layer_name}'. " f"Original error: {e}" ) from e else: # LogitsDistillation or FeatureDistillation (final outputs) distillation_loss_teacher_output = teacher_features[ "final_output" ] distillation_loss_student_output = y_pred # Validate outputs are compatible for this distillation loss distillation_loss_fn.validate_outputs( distillation_loss_teacher_output, distillation_loss_student_output, ) # Compute loss for this distillation loss current_distillation_loss = distillation_loss_fn.compute_loss( distillation_loss_teacher_output, distillation_loss_student_output, ) # Validate that distillation loss returns a scalar if ( hasattr(current_distillation_loss, "shape") and len(current_distillation_loss.shape) > 0 ): raise ValueError( f"Distillation loss " f"{distillation_loss_fn.__class__.__name__} " f"returned a non-scalar loss with shape " f"{current_distillation_loss.shape}. " f"The compute_loss method must return a scalar " f"tensor." ) # Apply weight and add to total distillation_loss = keras.ops.add( distillation_loss, keras.ops.multiply(weight, current_distillation_loss), ) # Combine losses total_loss = keras.ops.add( keras.ops.multiply(self.student_loss_weight, student_loss), keras.ops.multiply( keras.ops.subtract(1.0, self.student_loss_weight), distillation_loss, ), ) # Update metrics self.student_loss_tracker.update_state(student_loss) self.distillation_loss_tracker.update_state(distillation_loss) self.total_loss_tracker.update_state(total_loss) return total_loss def reset_metrics(self): """Reset all metrics.""" super().reset_metrics() self.student_loss_tracker.reset_state() self.distillation_loss_tracker.reset_state() self.total_loss_tracker.reset_state() def get_config(self): """Get configuration for serialization.""" config = super().get_config() config.update( { "teacher": serialization_lib.serialize_keras_object( self.teacher ), "student": serialization_lib.serialize_keras_object( self.student ), "distillation_losses": [ serialization_lib.serialize_keras_object(distillation_loss) for distillation_loss in self.distillation_losses ], "distillation_loss_weights": self.distillation_loss_weights, "student_loss_weight": self.student_loss_weight, } ) return config @classmethod def from_config(cls, config): """Create instance from configuration.""" config = config.copy() # Deserialize objects config["teacher"] = serialization_lib.deserialize_keras_object( config["teacher"] ) config["student"] = serialization_lib.deserialize_keras_object( config["student"] ) config["distillation_losses"] = [ serialization_lib.deserialize_keras_object(distillation_loss) for distillation_loss in config["distillation_losses"] ] return cls(**config)
Distiller
python
kamyu104__LeetCode-Solutions
Python/max-sum-of-sub-matrix-no-larger-than-k.py
{ "start": 116, "end": 1234 }
class ____(object): def maxSumSubmatrix(self, matrix, k): """ :type matrix: List[List[int]] :type k: int :rtype: int """ if not matrix: return 0 m = min(len(matrix), len(matrix[0])) n = max(len(matrix), len(matrix[0])) result = float("-inf") for i in xrange(m): sums = [0] * n for j in xrange(i, m): for l in xrange(n): sums[l] += matrix[j][l] if m == len(matrix) else matrix[l][j] # Find the max subarray no more than K. accu_sum_set, accu_sum = [0], 0 for sum in sums: accu_sum += sum it = bisect_left(accu_sum_set, accu_sum - k) # Time: O(logn) if it != len(accu_sum_set): result = max(result, accu_sum - accu_sum_set[it]) insort(accu_sum_set, accu_sum) # Time: O(n) return result # Time: O(min(m, n)^2 * max(m, n) * log(max(m, n))) ~ O(min(m, n)^2 * max(m, n)^2) # Space: O(max(m, n))
Solution
python
great-expectations__great_expectations
great_expectations/expectations/metrics/column_map_metrics/column_values_match_regex.py
{ "start": 1923, "end": 3732 }
class ____(MetricProvider): metric_name = "column_values.match_regex.count" metric_value_kwargs = ("regex",) @metric_value(engine=PandasExecutionEngine) def _pandas(*, metrics, **kwargs): return metrics[ f"column_values.not_match_regex.{SummarizationMetricNameSuffixes.UNEXPECTED_COUNT.value}" ] @metric_value(engine=SqlAlchemyExecutionEngine) def _sqlalchemy(*, metrics, **kwargs): return metrics[ f"column_values.not_match_regex.{SummarizationMetricNameSuffixes.UNEXPECTED_COUNT.value}" ] @metric_value(engine=SparkDFExecutionEngine) def _spark(*, metrics, **kwargs): return metrics[ f"column_values.not_match_regex.{SummarizationMetricNameSuffixes.UNEXPECTED_COUNT.value}" ] @classmethod @override def _get_evaluation_dependencies( cls, metric: MetricConfiguration, configuration: Optional[ExpectationConfiguration] = None, execution_engine: Optional[ExecutionEngine] = None, runtime_configuration: Optional[dict] = None, ): dependencies: dict = super()._get_evaluation_dependencies( metric=metric, configuration=configuration, execution_engine=execution_engine, runtime_configuration=runtime_configuration, ) dependencies[ f"column_values.not_match_regex.{SummarizationMetricNameSuffixes.UNEXPECTED_COUNT.value}" ] = MetricConfiguration( metric_name=f"column_values.not_match_regex.{SummarizationMetricNameSuffixes.UNEXPECTED_COUNT.value}", metric_domain_kwargs=metric.metric_domain_kwargs, metric_value_kwargs=metric.metric_value_kwargs, ) return dependencies
ColumnValuesMatchRegexCount
python
pydata__xarray
xarray/core/nputils.py
{ "start": 5168, "end": 11105 }
class ____: """Object that implements indexing like vindex on a np.ndarray. This is a pure Python implementation of (some of) the logic in this NumPy proposal: https://github.com/numpy/numpy/pull/6256 """ def __init__(self, array): self._array = array def __getitem__(self, key): mixed_positions, vindex_positions = _advanced_indexer_subspaces(key) return np.moveaxis(self._array[key], mixed_positions, vindex_positions) def __setitem__(self, key, value): """Value must have dimensionality matching the key.""" mixed_positions, vindex_positions = _advanced_indexer_subspaces(key) self._array[key] = np.moveaxis(value, vindex_positions, mixed_positions) def _create_method(name, npmodule=np) -> Callable: def f(values, axis=None, **kwargs): dtype = kwargs.get("dtype") bn_func = getattr(bn, name, None) xp = get_array_namespace(values) if xp is not np: func = getattr(xp, name, None) if func is not None: return func(values, axis=axis, **kwargs) if ( module_available("numbagg") and OPTIONS["use_numbagg"] and isinstance(values, np.ndarray) # numbagg<0.7.0 uses ddof=1 only, but numpy uses ddof=0 by default and ( pycompat.mod_version("numbagg") >= Version("0.7.0") or ("var" not in name and "std" not in name) or kwargs.get("ddof", 0) == 1 ) # TODO: bool? and values.dtype.kind in "uif" # and values.dtype.isnative and (dtype is None or np.dtype(dtype) == values.dtype) # numbagg.nanquantile only available after 0.8.0 and with linear method and ( name != "nanquantile" or ( pycompat.mod_version("numbagg") >= Version("0.8.0") and kwargs.get("method", "linear") == "linear" ) ) ): import numbagg nba_func = getattr(numbagg, name, None) if nba_func is not None: # numbagg does not use dtype kwargs.pop("dtype", None) # prior to 0.7.0, numbagg did not support ddof; we ensure it's limited # to ddof=1 above. if pycompat.mod_version("numbagg") < Version("0.7.0"): kwargs.pop("ddof", None) if name == "nanquantile": kwargs["quantiles"] = kwargs.pop("q") kwargs.pop("method", None) return nba_func(values, axis=axis, **kwargs) if ( _BOTTLENECK_AVAILABLE and OPTIONS["use_bottleneck"] and isinstance(values, np.ndarray) and bn_func is not None and not isinstance(axis, tuple) and values.dtype.kind in "uifc" and values.dtype.isnative and (dtype is None or np.dtype(dtype) == values.dtype) ): # bottleneck does not take care dtype, min_count kwargs.pop("dtype", None) result = bn_func(values, axis=axis, **kwargs) # bottleneck returns python scalars for reduction over all axes if isinstance(result, float): result = np.float64(result) else: result = getattr(npmodule, name)(values, axis=axis, **kwargs) return result f.__name__ = name return f def _nanpolyfit_1d(arr, x, rcond=None): out = np.full((x.shape[1] + 1,), np.nan) mask = np.isnan(arr) if not np.all(mask): out[:-1], resid, rank, _ = np.linalg.lstsq(x[~mask, :], arr[~mask], rcond=rcond) out[-1] = resid[0] if resid.size > 0 else np.nan warn_on_deficient_rank(rank, x.shape[1]) return out def warn_on_deficient_rank(rank, order): if rank != order: warnings.warn("Polyfit may be poorly conditioned", RankWarning, stacklevel=2) def least_squares(lhs, rhs, rcond=None, skipna=False): if rhs.ndim > 2: out_shape = rhs.shape rhs = rhs.reshape(rhs.shape[0], -1) else: out_shape = None if skipna: added_dim = rhs.ndim == 1 if added_dim: rhs = rhs.reshape(rhs.shape[0], 1) nan_cols = np.any(np.isnan(rhs), axis=0) out = np.empty((lhs.shape[1] + 1, rhs.shape[1])) if np.any(nan_cols): out[:, nan_cols] = np.apply_along_axis( _nanpolyfit_1d, 0, rhs[:, nan_cols], lhs ) if np.any(~nan_cols): out[:-1, ~nan_cols], resids, rank, _ = np.linalg.lstsq( lhs, rhs[:, ~nan_cols], rcond=rcond ) out[-1, ~nan_cols] = resids if resids.size > 0 else np.nan warn_on_deficient_rank(rank, lhs.shape[1]) coeffs = out[:-1, :] residuals = out[-1, :] if added_dim: coeffs = coeffs.reshape(coeffs.shape[0]) residuals = residuals.reshape(residuals.shape[0]) else: coeffs, residuals, rank, _ = np.linalg.lstsq(lhs, rhs, rcond=rcond) if residuals.size == 0: residuals = coeffs[0] * np.nan warn_on_deficient_rank(rank, lhs.shape[1]) if out_shape is not None: coeffs = coeffs.reshape(-1, *out_shape[1:]) residuals = residuals.reshape(*out_shape[1:]) return coeffs, residuals nanmin = _create_method("nanmin") nanmax = _create_method("nanmax") nanmean = _create_method("nanmean") nanmedian = _create_method("nanmedian") nanvar = _create_method("nanvar") nanstd = _create_method("nanstd") nanprod = _create_method("nanprod") nancumsum = _create_method("nancumsum") nancumprod = _create_method("nancumprod") nanargmin = _create_method("nanargmin") nanargmax = _create_method("nanargmax") nanquantile = _create_method("nanquantile")
NumpyVIndexAdapter
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 429343, "end": 429508 }
class ____(Format): """Dict schema wrapper.""" _schema = {"$ref": "#/definitions/Dict"} def __init__(self, **kwds): super().__init__(**kwds)
Dict
python
numba__numba
numba/cuda/tests/cudapy/test_laplace.py
{ "start": 267, "end": 3211 }
class ____(CUDATestCase): def test_laplace_small(self): @cuda.jit(float64(float64, float64), device=True, inline=True) def get_max(a, b): if a > b: return a else: return b @cuda.jit(void(float64[:, :], float64[:, :], float64[:, :])) def jocabi_relax_core(A, Anew, error): err_sm = cuda.shared.array(SM_SIZE, dtype=float64) ty = cuda.threadIdx.x tx = cuda.threadIdx.y bx = cuda.blockIdx.x by = cuda.blockIdx.y n = A.shape[0] m = A.shape[1] i, j = cuda.grid(2) err_sm[ty, tx] = 0 if j >= 1 and j < n - 1 and i >= 1 and i < m - 1: Anew[j, i] = 0.25 * ( A[j, i + 1] + A[j, i - 1] + A[j - 1, i] + A[j + 1, i]) err_sm[ty, tx] = Anew[j, i] - A[j, i] cuda.syncthreads() # max-reduce err_sm vertically t = tpb // 2 while t > 0: if ty < t: err_sm[ty, tx] = get_max(err_sm[ty, tx], err_sm[ty + t, tx]) t //= 2 cuda.syncthreads() # max-reduce err_sm horizontally t = tpb // 2 while t > 0: if tx < t and ty == 0: err_sm[ty, tx] = get_max(err_sm[ty, tx], err_sm[ty, tx + t]) t //= 2 cuda.syncthreads() if tx == 0 and ty == 0: error[by, bx] = err_sm[0, 0] if config.ENABLE_CUDASIM: NN, NM = 4, 4 iter_max = 20 else: NN, NM = 256, 256 iter_max = 1000 A = np.zeros((NN, NM), dtype=np.float64) Anew = np.zeros((NN, NM), dtype=np.float64) n = NN tol = 1.0e-6 error = 1.0 for j in range(n): A[j, 0] = 1.0 Anew[j, 0] = 1.0 iter = 0 blockdim = (tpb, tpb) griddim = (NN // blockdim[0], NM // blockdim[1]) error_grid = np.zeros(griddim) stream = cuda.stream() dA = cuda.to_device(A, stream) # to device and don't come back dAnew = cuda.to_device(Anew, stream) # to device and don't come back derror_grid = cuda.to_device(error_grid, stream) while error > tol and iter < iter_max: self.assertTrue(error_grid.dtype == np.float64) jocabi_relax_core[griddim, blockdim, stream](dA, dAnew, derror_grid) derror_grid.copy_to_host(error_grid, stream=stream) # error_grid is available on host stream.synchronize() error = np.abs(error_grid).max() # swap dA and dAnew tmp = dA dA = dAnew dAnew = tmp iter += 1 if __name__ == '__main__': unittest.main()
TestCudaLaplace
python
networkx__networkx
networkx/classes/reportviews.py
{ "start": 24122, "end": 26340 }
class ____(EdgeViewABC): """EdgeDataView for outward edges of DiGraph; See EdgeDataView""" __slots__ = ( "_viewer", "_nbunch", "_data", "_default", "_adjdict", "_nodes_nbrs", "_report", ) def __getstate__(self): return { "viewer": self._viewer, "nbunch": self._nbunch, "data": self._data, "default": self._default, } def __setstate__(self, state): self.__init__(**state) def __init__(self, viewer, nbunch=None, data=False, *, default=None): self._viewer = viewer adjdict = self._adjdict = viewer._adjdict if nbunch is None: self._nodes_nbrs = adjdict.items else: # dict retains order of nodes but acts like a set nbunch = dict.fromkeys(viewer._graph.nbunch_iter(nbunch)) self._nodes_nbrs = lambda: [(n, adjdict[n]) for n in nbunch] self._nbunch = nbunch self._data = data self._default = default # Set _report based on data and default if data is True: self._report = lambda n, nbr, dd: (n, nbr, dd) elif data is False: self._report = lambda n, nbr, dd: (n, nbr) else: # data is attribute name self._report = ( lambda n, nbr, dd: (n, nbr, dd[data]) if data in dd else (n, nbr, default) ) def __len__(self): return sum(len(nbrs) for n, nbrs in self._nodes_nbrs()) def __iter__(self): return ( self._report(n, nbr, dd) for n, nbrs in self._nodes_nbrs() for nbr, dd in nbrs.items() ) def __contains__(self, e): u, v = e[:2] if self._nbunch is not None and u not in self._nbunch: return False # this edge doesn't start in nbunch try: ddict = self._adjdict[u][v] except KeyError: return False return e == self._report(u, v, ddict) def __str__(self): return str(list(self)) def __repr__(self): return f"{self.__class__.__name__}({list(self)})"
OutEdgeDataView
python
tensorflow__tensorflow
tensorflow/python/training/server_lib_same_variables_clear_container_test.py
{ "start": 1002, "end": 3161 }
class ____(test.TestCase): # Verifies behavior of tf.Session.reset() with multiple containers using # default container names as defined by the target name. # TODO(b/34465411): Starting multiple servers with different configurations # in the same test is flaky. Move this test case back into # "server_lib_test.py" when this is no longer the case. def testSameVariablesClearContainer(self): # Starts two servers with different names so they map to different # resource "containers". server0 = server_lib.Server( { "local0": ["localhost:0"] }, protocol="grpc", start=True) server1 = server_lib.Server( { "local1": ["localhost:0"] }, protocol="grpc", start=True) # Creates a graph with 2 variables. with ops.Graph().as_default(): v0 = variables.Variable(1.0, name="v0") v1 = variables.Variable(2.0, name="v0") # Initializes the variables. Verifies that the values are correct. sess_0 = session.Session(server0.target) sess_1 = session.Session(server1.target) sess_0.run(v0.initializer) sess_1.run(v1.initializer) self.assertAllEqual(1.0, sess_0.run(v0)) self.assertAllEqual(2.0, sess_1.run(v1)) # Resets container "local0". Verifies that v0 is no longer initialized. session.Session.reset(server0.target, ["local0"]) _ = session.Session(server0.target) with self.assertRaises(errors_impl.FailedPreconditionError): self.evaluate(v0) # Reinitializes v0 for the following test. self.evaluate(v0.initializer) # Verifies that v1 is still valid. self.assertAllEqual(2.0, sess_1.run(v1)) # Resets container "local1". Verifies that v1 is no longer initialized. session.Session.reset(server1.target, ["local1"]) _ = session.Session(server1.target) with self.assertRaises(errors_impl.FailedPreconditionError): self.evaluate(v1) # Verifies that v0 is still valid. _ = session.Session(server0.target) self.assertAllEqual(1.0, self.evaluate(v0)) if __name__ == "__main__": test.main()
SameVariablesClearContainerTest
python
oauthlib__oauthlib
oauthlib/openid/connect/core/request_validator.py
{ "start": 261, "end": 13766 }
class ____(OAuth2RequestValidator): def get_authorization_code_scopes(self, client_id, code, redirect_uri, request): """ Extracts scopes from saved authorization code. The scopes returned by this method is used to route token requests based on scopes passed to Authorization Code requests. With that the token endpoint knows when to include OpenIDConnect id_token in token response only based on authorization code scopes. Only code param should be sufficient to retrieve grant code from any storage you are using, `client_id` and `redirect_uri` can have a blank value `""` don't forget to check it before using those values in a select query if a database is used. :param client_id: Unicode client identifier :param code: Unicode authorization code grant :param redirect_uri: Unicode absolute URI :return: A list of scope Method is used by: - Authorization Token Grant Dispatcher """ raise NotImplementedError('Subclasses must implement this method.') def get_authorization_code_nonce(self, client_id, code, redirect_uri, request): """ Extracts nonce from saved authorization code. If present in the Authentication Request, Authorization Servers MUST include a nonce Claim in the ID Token with the Claim Value being the nonce value sent in the Authentication Request. Authorization Servers SHOULD perform no other processing on nonce values used. The nonce value is a case-sensitive string. Only code param should be sufficient to retrieve grant code from any storage you are using. However, `client_id` and `redirect_uri` have been validated and can be used also. :param client_id: Unicode client identifier :param code: Unicode authorization code grant :param redirect_uri: Unicode absolute URI :return: Unicode nonce Method is used by: - Authorization Token Grant Dispatcher """ raise NotImplementedError('Subclasses must implement this method.') def get_jwt_bearer_token(self, token, token_handler, request): """Get JWT Bearer token or OpenID Connect ID token If using OpenID Connect this SHOULD call `oauthlib.oauth2.RequestValidator.get_id_token` :param token: A Bearer token dict :param token_handler: the token handler (BearerToken class) :param request: OAuthlib request. :type request: oauthlib.common.Request :return: The JWT Bearer token or OpenID Connect ID token (a JWS signed JWT) Method is used by JWT Bearer and OpenID Connect tokens: - JWTToken.create_token """ raise NotImplementedError('Subclasses must implement this method.') def get_id_token(self, token, token_handler, request): """Get OpenID Connect ID token This method is OPTIONAL and is NOT RECOMMENDED. `finalize_id_token` SHOULD be implemented instead. However, if you want a full control over the minting of the `id_token`, you MAY want to override `get_id_token` instead of using `finalize_id_token`. In the OpenID Connect workflows when an ID Token is requested this method is called. Subclasses should implement the construction, signing and optional encryption of the ID Token as described in the OpenID Connect spec. In addition to the standard OAuth2 request properties, the request may also contain these OIDC specific properties which are useful to this method: - nonce, if workflow is implicit or hybrid and it was provided - claims, if provided to the original Authorization Code request The token parameter is a dict which may contain an ``access_token`` entry, in which case the resulting ID Token *should* include a calculated ``at_hash`` claim. Similarly, when the request parameter has a ``code`` property defined, the ID Token *should* include a calculated ``c_hash`` claim. http://openid.net/specs/openid-connect-core-1_0.html (sections `3.1.3.6`_, `3.2.2.10`_, `3.3.2.11`_) .. _`3.1.3.6`: http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken .. _`3.2.2.10`: http://openid.net/specs/openid-connect-core-1_0.html#ImplicitIDToken .. _`3.3.2.11`: http://openid.net/specs/openid-connect-core-1_0.html#HybridIDToken :param token: A Bearer token dict :param token_handler: the token handler (BearerToken class) :param request: OAuthlib request. :type request: oauthlib.common.Request :return: The ID Token (a JWS signed JWT) """ return None def finalize_id_token(self, id_token, token, token_handler, request): """Finalize OpenID Connect ID token & Sign or Encrypt. In the OpenID Connect workflows when an ID Token is requested this method is called. Subclasses should implement the construction, signing and optional encryption of the ID Token as described in the OpenID Connect spec. The `id_token` parameter is a dict containing a couple of OIDC technical fields related to the specification. Prepopulated attributes are: - `aud`, equals to `request.client_id`. - `iat`, equals to current time. - `nonce`, if present, is equals to the `nonce` from the authorization request. - `at_hash`, hash of `access_token`, if relevant. - `c_hash`, hash of `code`, if relevant. This method MUST provide required fields as below: - `iss`, REQUIRED. Issuer Identifier for the Issuer of the response. - `sub`, REQUIRED. Subject Identifier - `exp`, REQUIRED. Expiration time on or after which the ID Token MUST NOT be accepted by the RP when performing authentication with the OP. Additional claims must be added, note that `request.scope` should be used to determine the list of claims. More information can be found at `OpenID Connect Core#Claims`_ .. _`OpenID Connect Core#Claims`: https://openid.net/specs/openid-connect-core-1_0.html#Claims :param id_token: A dict containing technical fields of id_token :param token: A Bearer token dict :param token_handler: the token handler (BearerToken class) :param request: OAuthlib request. :type request: oauthlib.common.Request :return: The ID Token (a JWS signed JWT or JWE encrypted JWT) """ raise NotImplementedError('Subclasses must implement this method.') def validate_jwt_bearer_token(self, token, scopes, request): """Ensure the JWT Bearer token or OpenID Connect ID token are valids and authorized access to scopes. If using OpenID Connect this SHOULD call `oauthlib.oauth2.RequestValidator.get_id_token` If not using OpenID Connect this can `return None` to avoid 5xx rather 401/3 response. OpenID connect core 1.0 describe how to validate an id_token: - http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation - http://openid.net/specs/openid-connect-core-1_0.html#ImplicitIDTValidation - http://openid.net/specs/openid-connect-core-1_0.html#HybridIDTValidation - http://openid.net/specs/openid-connect-core-1_0.html#HybridIDTValidation2 :param token: Unicode Bearer token :param scopes: List of scopes (defined by you) :param request: OAuthlib request. :type request: oauthlib.common.Request :rtype: True or False Method is indirectly used by all core OpenID connect JWT token issuing grant types: - Authorization Code Grant - Implicit Grant - Hybrid Grant """ raise NotImplementedError('Subclasses must implement this method.') def validate_id_token(self, token, scopes, request): """Ensure the id token is valid and authorized access to scopes. OpenID connect core 1.0 describe how to validate an id_token: - http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation - http://openid.net/specs/openid-connect-core-1_0.html#ImplicitIDTValidation - http://openid.net/specs/openid-connect-core-1_0.html#HybridIDTValidation - http://openid.net/specs/openid-connect-core-1_0.html#HybridIDTValidation2 :param token: Unicode Bearer token :param scopes: List of scopes (defined by you) :param request: OAuthlib request. :type request: oauthlib.common.Request :rtype: True or False Method is indirectly used by all core OpenID connect JWT token issuing grant types: - Authorization Code Grant - Implicit Grant - Hybrid Grant """ raise NotImplementedError('Subclasses must implement this method.') def validate_silent_authorization(self, request): """Ensure the logged in user has authorized silent OpenID authorization. Silent OpenID authorization allows access tokens and id tokens to be granted to clients without any user prompt or interaction. :param request: OAuthlib request. :type request: oauthlib.common.Request :rtype: True or False Method is used by: - OpenIDConnectAuthCode - OpenIDConnectImplicit - OpenIDConnectHybrid """ raise NotImplementedError('Subclasses must implement this method.') def validate_silent_login(self, request): """Ensure session user has authorized silent OpenID login. If no user is logged in or has not authorized silent login, this method should return False. If the user is logged in but associated with multiple accounts and not selected which one to link to the token then this method should raise an oauthlib.oauth2.AccountSelectionRequired error. :param request: OAuthlib request. :type request: oauthlib.common.Request :rtype: True or False Method is used by: - OpenIDConnectAuthCode - OpenIDConnectImplicit - OpenIDConnectHybrid """ raise NotImplementedError('Subclasses must implement this method.') def validate_user_match(self, id_token_hint, scopes, claims, request): """Ensure client supplied user id hint matches session user. If the sub claim or id_token_hint is supplied then the session user must match the given ID. :param id_token_hint: User identifier string. :param scopes: List of OAuth 2 scopes and OpenID claims (strings). :param claims: OpenID Connect claims dict. :param request: OAuthlib request. :type request: oauthlib.common.Request :rtype: True or False Method is used by: - OpenIDConnectAuthCode - OpenIDConnectImplicit - OpenIDConnectHybrid """ raise NotImplementedError('Subclasses must implement this method.') def get_userinfo_claims(self, request): """Return the UserInfo claims in JSON or Signed or Encrypted. The UserInfo Claims MUST be returned as the members of a JSON object unless a signed or encrypted response was requested during Client Registration. The Claims defined in Section 5.1 can be returned, as can additional Claims not specified there. For privacy reasons, OpenID Providers MAY elect to not return values for some requested Claims. If a Claim is not returned, that Claim Name SHOULD be omitted from the JSON object representing the Claims; it SHOULD NOT be present with a null or empty string value. The sub (subject) Claim MUST always be returned in the UserInfo Response. Upon receipt of the UserInfo Request, the UserInfo Endpoint MUST return the JSON Serialization of the UserInfo Response as in Section 13.3 in the HTTP response body unless a different format was specified during Registration [OpenID.Registration]. If the UserInfo Response is signed and/or encrypted, then the Claims are returned in a JWT and the content-type MUST be application/jwt. The response MAY be encrypted without also being signed. If both signing and encryption are requested, the response MUST be signed then encrypted, with the result being a Nested JWT, as defined in [JWT]. If signed, the UserInfo Response SHOULD contain the Claims iss (issuer) and aud (audience) as members. The iss value SHOULD be the OP's Issuer Identifier URL. The aud value SHOULD be or include the RP's Client ID value. :param request: OAuthlib request. :type request: oauthlib.common.Request :rtype: Claims as a dict OR JWT/JWS/JWE as a string Method is used by: UserInfoEndpoint """ def refresh_id_token(self, request): """Whether the id token should be refreshed. Default, True :param request: OAuthlib request. :type request: oauthlib.common.Request :rtype: True or False Method is used by: RefreshTokenGrant """ return True
RequestValidator
python
apache__airflow
airflow-core/src/airflow/traces/tracer.py
{ "start": 2106, "end": 3268 }
class ____: """If no Tracer is configured, EmptySpan is used as a fallback.""" def __enter__(self) -> Self: """Enter.""" return self def __exit__(self, *args, **kwargs): """Exit.""" pass def __call__(self, obj): """Call.""" return obj def get_span_context(self): """Get span context.""" return EMPTY_CTX def set_attribute(self, key, value) -> None: """Set an attribute to the span.""" pass def set_attributes(self, attributes) -> None: """Set multiple attributes at once.""" pass def is_recording(self): return False def add_event( self, name: str, attributes: Any | None = None, timestamp: int | None = None, ) -> None: """Add event to span.""" pass def add_link( self, context: Any, attributes: Any | None = None, ) -> None: """Add link to the span.""" pass def end(self, end_time=None, *args, **kwargs) -> None: """End.""" pass EMPTY_SPAN = EmptySpan() EMPTY_CTX = EmptyContext()
EmptySpan
python
django__django
tests/decorators/tests.py
{ "start": 12742, "end": 20723 }
class ____(SimpleTestCase): """ Tests for async method_decorator """ async def test_preserve_signature(self): class Test: @async_simple_dec_m async def say(self, msg): return f"Saying {msg}" self.assertEqual(await Test().say("hello"), "returned: Saying hello") def test_preserve_attributes(self): async def func(*args, **kwargs): await asyncio.sleep(0.01) return args, kwargs def myattr_dec(func): async def wrapper(*args, **kwargs): return await func(*args, **kwargs) wrapper.myattr = True return wrapper def myattr2_dec(func): async def wrapper(*args, **kwargs): return await func(*args, **kwargs) wrapper.myattr2 = True return wrapper # Sanity check myattr_dec and myattr2_dec func = myattr_dec(func) self.assertIs(getattr(func, "myattr", False), True) func = myattr2_dec(func) self.assertIs(getattr(func, "myattr2", False), True) func = myattr_dec(myattr2_dec(func)) self.assertIs(getattr(func, "myattr", False), True) self.assertIs(getattr(func, "myattr2", False), False) myattr_dec_m = method_decorator(myattr_dec) myattr2_dec_m = method_decorator(myattr2_dec) # Decorate using method_decorator() on the async method. class TestPlain: @myattr_dec_m @myattr2_dec_m async def method(self): "A method" # Decorate using method_decorator() on both the class and the method. # The decorators applied to the methods are applied before the ones # applied to the class. @method_decorator(myattr_dec_m, "method") class TestMethodAndClass: @method_decorator(myattr2_dec_m) async def method(self): "A method" # Decorate using an iterable of function decorators. @method_decorator((myattr_dec, myattr2_dec), "method") class TestFunctionIterable: async def method(self): "A method" # Decorate using an iterable of method decorators. @method_decorator((myattr_dec_m, myattr2_dec_m), "method") class TestMethodIterable: async def method(self): "A method" tests = ( TestPlain, TestMethodAndClass, TestFunctionIterable, TestMethodIterable, ) for Test in tests: with self.subTest(Test=Test): self.assertIs(getattr(Test().method, "myattr", False), True) self.assertIs(getattr(Test().method, "myattr2", False), True) self.assertIs(getattr(Test.method, "myattr", False), True) self.assertIs(getattr(Test.method, "myattr2", False), True) self.assertEqual(Test.method.__doc__, "A method") self.assertEqual(Test.method.__name__, "method") async def test_new_attribute(self): """A decorator that sets a new attribute on the method.""" def decorate(func): func.x = 1 return func class MyClass: @method_decorator(decorate) async def method(self): return True obj = MyClass() self.assertEqual(obj.method.x, 1) self.assertIs(await obj.method(), True) def test_bad_iterable(self): decorators = {async_simple_dec} msg = "'set' object is not subscriptable" with self.assertRaisesMessage(TypeError, msg): @method_decorator(decorators, "method") class TestIterable: async def method(self): await asyncio.sleep(0.01) async def test_argumented(self): class ClsDecAsync: def __init__(self, myattr): self.myattr = myattr def __call__(self, f): async def wrapper(): result = await f() return f"{result} appending {self.myattr}" return update_wrapper(wrapper, f) class Test: @method_decorator(ClsDecAsync(False)) async def method(self): return True self.assertEqual(await Test().method(), "True appending False") async def test_descriptors(self): class bound_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ async def __call__(self, *args, **kwargs): return await self.wrapped(*args, **kwargs) def __get__(self, instance, cls=None): return self class descriptor_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __get__(self, instance, cls=None): return bound_wrapper(self.wrapped.__get__(instance, cls)) class Test: @async_simple_dec_m @descriptor_wrapper async def method(self, arg): return arg self.assertEqual(await Test().method(1), "returned: 1") async def test_class_decoration(self): """ @method_decorator can be used to decorate a class and its methods. """ @method_decorator(async_simple_dec, name="method") class Test: async def method(self): return False async def not_method(self): return "a string" self.assertEqual(await Test().method(), "returned: False") self.assertEqual(await Test().not_method(), "a string") async def test_tuple_of_decorators(self): """ @method_decorator can accept a tuple of decorators. """ def add_question_mark(func): async def _wrapper(*args, **kwargs): await asyncio.sleep(0.01) return await func(*args, **kwargs) + "?" return _wrapper def add_exclamation_mark(func): async def _wrapper(*args, **kwargs): await asyncio.sleep(0.01) return await func(*args, **kwargs) + "!" return _wrapper decorators = (add_exclamation_mark, add_question_mark) @method_decorator(decorators, name="method") class TestFirst: async def method(self): return "hello world" class TestSecond: @method_decorator(decorators) async def method(self): return "world hello" self.assertEqual(await TestFirst().method(), "hello world?!") self.assertEqual(await TestSecond().method(), "world hello?!") async def test_wrapper_assignments(self): """@method_decorator preserves wrapper assignments.""" func_data = {} def decorator(func): @wraps(func) async def inner(*args, **kwargs): func_data["func_name"] = getattr(func, "__name__", None) func_data["func_module"] = getattr(func, "__module__", None) return await func(*args, **kwargs) return inner class Test: @method_decorator(decorator) async def method(self): return "tests" await Test().method() expected = {"func_name": "method", "func_module": "decorators.tests"} self.assertEqual(func_data, expected) async def test_markcoroutinefunction_applied(self): class Test: @async_simple_dec_m async def method(self): return "tests" method = Test().method self.assertIs(iscoroutinefunction(method), True) self.assertEqual(await method(), "returned: tests")
AsyncMethodDecoratorTests
python
ipython__ipython
tests/test_async_helpers.py
{ "start": 552, "end": 10709 }
class ____(TestCase): def test_should_be_async(self): self.assertFalse(_should_be_async("False")) self.assertTrue(_should_be_async("await bar()")) self.assertTrue(_should_be_async("x = await bar()")) self.assertFalse( _should_be_async( dedent( """ async def awaitable(): pass """ ) ) ) def _get_top_level_cases(self): # These are test cases that should be valid in a function # but invalid outside of a function. test_cases = [] test_cases.append(("basic", "{val}")) # Note, in all conditional cases, I use True instead of # False so that the peephole optimizer won't optimize away # the return, so CPython will see this as a syntax error: # # while True: # break # return # # But not this: # # while False: # return # # See https://bugs.python.org/issue1875 test_cases.append( ( "if", dedent( """ if True: {val} """ ), ) ) test_cases.append( ( "while", dedent( """ while True: {val} break """ ), ) ) test_cases.append( ( "try", dedent( """ try: {val} except: pass """ ), ) ) test_cases.append( ( "except", dedent( """ try: pass except: {val} """ ), ) ) test_cases.append( ( "finally", dedent( """ try: pass except: pass finally: {val} """ ), ) ) test_cases.append( ( "for", dedent( """ for _ in range(4): {val} """ ), ) ) test_cases.append( ( "nested", dedent( """ if True: while True: {val} break """ ), ) ) test_cases.append( ( "deep-nested", dedent( """ if True: while True: break for x in range(3): if True: while True: for x in range(3): {val} """ ), ) ) return test_cases def _get_ry_syntax_errors(self): # This is a mix of tests that should be a syntax error if # return or yield whether or not they are in a function test_cases = [] test_cases.append( ( "class", dedent( """ class V: {val} """ ), ) ) test_cases.append( ( "nested-class", dedent( """ class V: class C: {val} """ ), ) ) return test_cases def test_top_level_return_error(self): tl_err_test_cases = self._get_top_level_cases() tl_err_test_cases.extend(self._get_ry_syntax_errors()) vals = ( "return", "yield", "yield from (_ for _ in range(3))", dedent( """ def f(): pass return """ ), ) for test_name, test_case in tl_err_test_cases: # This example should work if 'pass' is used as the value with self.subTest((test_name, "pass")): iprc(test_case.format(val="pass")) # It should fail with all the values for val in vals: with self.subTest((test_name, val)): msg = "Syntax error not raised for %s, %s" % (test_name, val) with self.assertRaises(SyntaxError, msg=msg): iprc(test_case.format(val=val)) def test_in_func_no_error(self): # Test that the implementation of top-level return/yield # detection isn't *too* aggressive, and works inside a function func_contexts = [] func_contexts.append( ( "func", False, dedent( """ def f():""" ), ) ) func_contexts.append( ( "method", False, dedent( """ class MyClass: def __init__(self): """ ), ) ) func_contexts.append( ( "async-func", True, dedent( """ async def f():""" ), ) ) func_contexts.append( ( "async-method", True, dedent( """ class MyClass: async def f(self):""" ), ) ) func_contexts.append( ( "closure", False, dedent( """ def f(): def g(): """ ), ) ) def nest_case(context, case): # Detect indentation lines = context.strip().splitlines() prefix_len = 0 for c in lines[-1]: if c != " ": break prefix_len += 1 indented_case = indent(case, " " * (prefix_len + 4)) return context + "\n" + indented_case # Gather and run the tests # yield is allowed in async functions, starting in Python 3.6, # and yield from is not allowed in any version vals = ("return", "yield", "yield from (_ for _ in range(3))") success_tests = zip(self._get_top_level_cases(), repeat(False)) failure_tests = zip(self._get_ry_syntax_errors(), repeat(True)) tests = chain(success_tests, failure_tests) for context_name, async_func, context in func_contexts: for (test_name, test_case), should_fail in tests: nested_case = nest_case(context, test_case) for val in vals: test_id = (context_name, test_name, val) cell = nested_case.format(val=val) with self.subTest(test_id): if should_fail: msg = "SyntaxError not raised for %s" % str(test_id) with self.assertRaises(SyntaxError, msg=msg): iprc(cell) print(cell) else: iprc(cell) def test_nonlocal(self): # fails if outer scope is not a function scope or if var not defined with self.assertRaises(SyntaxError): iprc("nonlocal x") iprc( """ x = 1 def f(): nonlocal x x = 10000 yield x """ ) iprc( """ def f(): def g(): nonlocal x x = 10000 yield x """ ) # works if outer scope is a function scope and var exists iprc( """ def f(): x = 20 def g(): nonlocal x x = 10000 yield x """ ) def test_execute(self): iprc( """ import asyncio await asyncio.sleep(0.001) """ ) def test_autoawait(self): iprc("%autoawait False") iprc("%autoawait True") iprc( """ from asyncio import sleep await sleep(0.1) """ ) def test_memory_error(self): """ The pgen parser in 3.8 or before use to raise MemoryError on too many nested parens anymore""" iprc("(" * 200 + ")" * 200) @pytest.mark.xfail(reason="fail on curio 1.6 and before on Python 3.12") @pytest.mark.skip( reason="skip_without(curio) fails on 3.12 for now even with other skip so must uncond skip" ) # @skip_without("curio") def test_autoawait_curio(self): iprc("%autoawait curio") @skip_without("trio") def test_autoawait_trio(self): iprc("%autoawait trio") @skip_without("trio") def test_autoawait_trio_wrong_sleep(self): iprc("%autoawait trio") res = iprc_nr( """ import asyncio await asyncio.sleep(0) """ ) with self.assertRaises(TypeError): res.raise_error() @skip_without("trio") def test_autoawait_asyncio_wrong_sleep(self): iprc("%autoawait asyncio") res = iprc_nr( """ import trio await trio.sleep(0) """ ) with self.assertRaises(RuntimeError): res.raise_error() def tearDown(self): ip.loop_runner = "asyncio"
AsyncTest
python
walkccc__LeetCode
solutions/1894. Find the Student that Will Replace the Chalk/1894.py
{ "start": 0, "end": 207 }
class ____: def chalkReplacer(self, chalk: list[int], k: int) -> int: k %= sum(chalk) if k == 0: return 0 for i, c in enumerate(chalk): k -= c if k < 0: return i
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/workspace/autodiscovery.py
{ "start": 528, "end": 5309 }
class ____(NamedTuple): attribute: str target_definition: object def loadable_targets_from_python_file( python_file: str, working_directory: Optional[str] = None ) -> Sequence[LoadableTarget]: loaded_module = load_python_file(python_file, working_directory) return loadable_targets_from_loaded_module(loaded_module) def loadable_targets_from_python_module( module_name: str, working_directory: Optional[str], remove_from_path_fn: Optional[Callable[[], Sequence[str]]] = None, ) -> Sequence[LoadableTarget]: module = load_python_module( module_name, working_directory=working_directory, remove_from_path_fn=remove_from_path_fn, ) return loadable_targets_from_loaded_module(module) def loadable_targets_from_python_package( package_name: str, working_directory: Optional[str], remove_from_path_fn: Optional[Callable[[], Sequence[str]]] = None, ) -> Sequence[LoadableTarget]: module = load_python_module( package_name, working_directory, remove_from_path_fn=remove_from_path_fn ) return loadable_targets_from_loaded_module(module) def _format_loadable_def(module: ModuleType, loadable_target: LoadableTarget) -> str: return f"{module.__name__}.{loadable_target.attribute}" def loadable_targets_from_loaded_module(module: ModuleType) -> Sequence[LoadableTarget]: from dagster._core.definitions import JobDefinition from dagster._utils.test.definitions import LazyDefinitions loadable_def_loaders = _loadable_targets_of_type(module, LazyDefinitions) if loadable_def_loaders: if len(loadable_def_loaders) > 1: raise DagsterInvariantViolationError( "Cannot have more than one function decorated with @lazy_definitions defined in module scope" ) return loadable_def_loaders loadable_defs = _loadable_targets_of_type(module, Definitions) if loadable_defs: if len(loadable_defs) > 1: loadable_def_names = ", ".join( _format_loadable_def(module, loadable_def) for loadable_def in loadable_defs ) raise DagsterInvariantViolationError( "Cannot have more than one Definitions object defined at module scope." f" Found Definitions objects: {loadable_def_names}" ) return loadable_defs loadable_repos = _loadable_targets_of_type(module, RepositoryDefinition) if loadable_repos: return loadable_repos loadable_jobs = _loadable_targets_of_type(module, JobDefinition) loadable_jobs = _loadable_targets_of_type(module, JobDefinition) if len(loadable_jobs) == 1: return loadable_jobs elif len(loadable_jobs) > 1: target_type = "job" if len(loadable_jobs) > 1 else "pipeline" raise DagsterInvariantViolationError( f'No repository and more than one {target_type} found in "{module.__name__}". If you' f" load a file or module directly it must have only one {target_type} in scope." f" Found {target_type}s defined in variables or decorated functions:" f" {[p.attribute for p in loadable_jobs]!r}." ) loadable_graphs = _loadable_targets_of_type(module, GraphDefinition) if len(loadable_graphs) == 1: return loadable_graphs elif len(loadable_graphs) > 1: raise DagsterInvariantViolationError( f'More than one graph found in "{module.__name__}". ' "If you load a file or module directly and it has no repositories, jobs, or " "pipelines in scope, it must have no more than one graph in scope. " f"Found graphs defined in variables or decorated functions: {[g.attribute for g in loadable_graphs]!r}." ) assets = load_assets_from_modules([module]) if len(assets) > 0: return [LoadableTarget(LOAD_ALL_ASSETS, assets)] raise DagsterInvariantViolationError( "No Definitions, RepositoryDefinition, Job, Pipeline, Graph, or AssetsDefinition found in " f'"{module.__name__}".' ) def _loadable_targets_of_type( module: ModuleType, klass: Union[type, tuple[type, ...]] ) -> Sequence[LoadableTarget]: loadable_targets = [] for name, value in inspect.getmembers(module): if isinstance(value, klass): loadable_targets.append(LoadableTarget(name, value)) return loadable_targets def autodefs_module_target(autoload_defs_module_name: str, working_directory: Optional[str]): from dagster.components import load_defs module = load_python_module(autoload_defs_module_name, working_directory) defs = load_defs(module) return LoadableTarget( attribute="", target_definition=defs, )
LoadableTarget
python
getsentry__sentry
src/sentry/models/rulefirehistory.py
{ "start": 297, "end": 998 }
class ____(Model): __relocation_scope__ = RelocationScope.Excluded project = FlexibleForeignKey("sentry.Project", db_constraint=False) rule = FlexibleForeignKey("sentry.Rule") group = FlexibleForeignKey("sentry.Group", db_constraint=False) event_id = CharField("event_id", max_length=32, null=True) date_added = DateTimeField(default=timezone.now, db_index=True) notification_uuid = UUIDField("notification_uuid", null=True) class Meta: db_table = "sentry_rulefirehistory" app_label = "sentry" indexes = [Index(fields=["rule", "date_added"])] __repr__ = sane_repr("rule_id", "group_id", "project_id", "event_id", "date_added")
RuleFireHistory
python
PyCQA__pylint
pylint/pyreverse/inspector.py
{ "start": 11161, "end": 12078 }
class ____(RelationshipHandlerInterface): """ Chain of Responsibility for handling types of relationships, useful to expand in the future if we want to add more distinct relationships. Every link of the chain checks if it's a certain type of relationship. If no relationship is found it's set as a generic relationship in `relationships_type`. The default chaining behavior is implemented inside the base handler class. """ _next_handler: RelationshipHandlerInterface def set_next( self, handler: RelationshipHandlerInterface ) -> RelationshipHandlerInterface: self._next_handler = handler return handler @abstractmethod def handle( self, node: nodes.AssignAttr | nodes.AssignName, parent: nodes.ClassDef ) -> None: if self._next_handler: self._next_handler.handle(node, parent)
AbstractRelationshipHandler
python
scipy__scipy
scipy/sparse/tests/test_minmax1d.py
{ "start": 2643, "end": 4269 }
class ____: def test_minmax(self, spcreator): dat = np.array([[-1, 5, 0, 3], [0, 0, -1, -2], [0, 0, 1, 2]]) datsp = spcreator(dat) for (spminmax, npminmax) in [ (datsp.min, np.min), (datsp.max, np.max), (datsp.nanmin, np.nanmin), (datsp.nanmax, np.nanmax), ]: for ax, result_shape in [(0, (4,)), (1, (3,))]: assert_equal(toarray(spminmax(axis=ax)), npminmax(dat, axis=ax)) assert_equal(spminmax(axis=ax).shape, result_shape) assert spminmax(axis=ax).format == "coo" for spminmax in [datsp.argmin, datsp.argmax]: for ax in [0, 1]: assert isinstance(spminmax(axis=ax), np.ndarray) # verify spmatrix behavior spmat_form = { 'coo': coo_matrix, 'csr': csr_matrix, 'csc': csc_matrix, 'bsr': bsr_matrix, } datspm = spmat_form[datsp.format](dat) for spm, npm in [ (datspm.min, np.min), (datspm.max, np.max), (datspm.nanmin, np.nanmin), (datspm.nanmax, np.nanmax), ]: for ax, result_shape in [(0, (1, 4)), (1, (3, 1))]: assert_equal(toarray(spm(axis=ax)), npm(dat, axis=ax, keepdims=True)) assert_equal(spm(axis=ax).shape, result_shape) assert spm(axis=ax).format == "coo" for spminmax in [datspm.argmin, datspm.argmax]: for ax in [0, 1]: assert isinstance(spminmax(axis=ax), np.ndarray)
Test_ShapeMinMax2DWithAxis
python
scrapy__scrapy
scrapy/spiderloader.py
{ "start": 956, "end": 1639 }
class ____(Protocol): @classmethod def from_settings(cls, settings: BaseSettings) -> Self: """Return an instance of the class for the given settings""" def load(self, spider_name: str) -> type[Spider]: """Return the Spider class for the given spider name. If the spider name is not found, it must raise a KeyError.""" def list(self) -> list[str]: """Return a list with the names of all spiders available in the project""" def find_by_request(self, request: Request) -> __builtins__.list[str]: """Return the list of spiders names that can handle the given request""" @implementer(ISpiderLoader)
SpiderLoaderProtocol
python
pandas-dev__pandas
pandas/tests/indexing/test_scalar.py
{ "start": 8504, "end": 9929 }
class ____: def test_multiindex_at_get(self): # GH 26989 # DataFrame.at and DataFrame.loc getter works with MultiIndex df = DataFrame({"a": [1, 2]}, index=[[1, 2], [3, 4]]) assert df.index.nlevels == 2 assert df.at[(1, 3), "a"] == 1 assert df.loc[(1, 3), "a"] == 1 # Series.at and Series.loc getter works with MultiIndex series = df["a"] assert series.index.nlevels == 2 assert series.at[1, 3] == 1 assert series.loc[1, 3] == 1 @pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") def test_multiindex_at_set(self): # GH 26989 # DataFrame.at and DataFrame.loc setter works with MultiIndex df = DataFrame({"a": [1, 2]}, index=[[1, 2], [3, 4]]) assert df.index.nlevels == 2 df.at[(1, 3), "a"] = 3 assert df.at[(1, 3), "a"] == 3 df.loc[(1, 3), "a"] = 4 assert df.loc[(1, 3), "a"] == 4 # Series.at and Series.loc setter works with MultiIndex series = df["a"] assert series.index.nlevels == 2 series.at[1, 3] = 5 assert series.at[1, 3] == 5 series.loc[1, 3] = 6 assert series.loc[1, 3] == 6 def test_multiindex_at_get_one_level(self): # GH#38053 s2 = Series((0, 1), index=[[False, True]]) result = s2.at[False] assert result == 0
TestMultiIndexScalar
python
modin-project__modin
asv_bench/benchmarks/benchmarks.py
{ "start": 10757, "end": 11830 }
class ____: param_names = ["shape", "item_length", "loc", "is_equal_indices"] @staticmethod def get_loc(df, loc, axis, item_length): locs_dict = { "zero": 0, "middle": len(df.axes[axis]) // 2, "last": len(df.axes[axis]) - 1, } base_loc = locs_dict[loc] range_based_loc = np.arange( base_loc, min(len(df.axes[axis]), base_loc + item_length) ) return ( (df.axes[axis][base_loc], base_loc) if len(range_based_loc) == 1 else (df.axes[axis][range_based_loc], range_based_loc) ) def setup(self, shape, item_length, loc, is_equal_indices): self.df = generate_dataframe("int", *shape, RAND_LOW, RAND_HIGH).copy() self.loc, self.iloc = self.get_loc( self.df, loc, item_length=item_length, axis=1 ) self.item = self.df[self.loc] + 1 self.item_raw = self.item.to_numpy() if not is_equal_indices: self.item.index = reversed(self.item.index)
BaseTimeSetItem
python
tensorflow__tensorflow
tensorflow/python/distribute/distribute_coordinator_test.py
{ "start": 4301, "end": 4635 }
class ____(object): def __init__(self): self._joined = False self._started = False def start(self): self._started = True def join(self): assert not self._joined self._joined = True @property def joined(self): return self._joined @property def started(self): return self._started
MockServer
python
PrefectHQ__prefect
tests/test_tasks.py
{ "start": 130790, "end": 137615 }
class ____: async def test_task_cannot_configure_poorly_typed_retry_delay(self): with pytest.raises(TypeError, match="Invalid"): @task(retries=42, retry_delay_seconds=dict(x=4)) async def insanity(): raise RuntimeError("try again!") with pytest.raises(TypeError, match="Invalid"): @task(retries=42, retry_delay_seconds=2) async def sanity(): raise RuntimeError("try again!") more_insanity = sanity.with_options(retry_delay_seconds=dict(x=4)) # noqa: F841 async def test_task_cannot_configure_too_many_custom_retry_delays(self): with pytest.raises(ValueError, match="Can not configure more"): @task(retries=42, retry_delay_seconds=list(range(51))) async def insanity(): raise RuntimeError("try again!") async def test_task_cannot_configure_negative_relative_jitter(self): with pytest.raises(ValueError, match="`retry_jitter_factor` must be >= 0"): @task(retries=42, retry_delay_seconds=100, retry_jitter_factor=-10) async def insanity(): raise RuntimeError("try again!") def test_task_accepts_fractional_retry_delay_seconds(self): @task(retries=2, retry_delay_seconds=1.5) def task_with_float_delay(): return "success" @task(retries=3, retry_delay_seconds=[0.5, 1.1, 2.7]) def task_with_float_list_delay(): return "success" assert task_with_float_delay.retries == 2 assert task_with_float_delay.retry_delay_seconds == 1.5 assert task_with_float_list_delay.retries == 3 assert task_with_float_list_delay.retry_delay_seconds == [0.5, 1.1, 2.7] async def test_task_run_name_is_set(prefect_client, events_pipeline): @task(task_run_name="fixed-name") def my_task(name): return name @flow def my_flow(name): return my_task(name, return_state=True) tr_state = my_flow(name="chris") await events_pipeline.process_events() # Check that the state completed happily assert tr_state.is_completed() task_run = await prefect_client.read_task_run(tr_state.state_details.task_run_id) assert task_run.name == "fixed-name" async def test_task_run_name_is_set_with_kwargs_including_defaults( prefect_client, events_pipeline ): @task(task_run_name="{name}-wuz-{where}") def my_task(name, where="here"): return name @flow def my_flow(name): return my_task(name, return_state=True) tr_state = my_flow(name="chris") await events_pipeline.process_events() # Check that the state completed happily assert tr_state.is_completed() task_run = await prefect_client.read_task_run(tr_state.state_details.task_run_id) assert task_run.name == "chris-wuz-here" async def test_task_run_name_is_set_with_function(prefect_client, events_pipeline): def generate_task_run_name(): return "is-this-a-bird" @task(task_run_name=generate_task_run_name) def my_task(name, where="here"): return name @flow def my_flow(name): return my_task(name, return_state=True) tr_state = my_flow(name="butterfly") await events_pipeline.process_events() # Check that the state completed happily assert tr_state.is_completed() task_run = await prefect_client.read_task_run(tr_state.state_details.task_run_id) assert task_run.name == "is-this-a-bird" async def test_task_run_name_is_set_with_function_using_runtime_context( prefect_client, events_pipeline ): def generate_task_run_name(): params = task_run_ctx.parameters tokens = [] tokens.append("anon" if "name" not in params else str(params["name"])) tokens.append("wuz") tokens.append("where?" if "where" not in params else str(params["where"])) return "-".join(tokens) @task(task_run_name=generate_task_run_name) def my_task(name, where="here"): return name @flow def my_flow(name): return my_task(name, return_state=True) tr_state = my_flow(name="chris") await events_pipeline.process_events() # Check that the state completed happily assert tr_state.is_completed() task_run = await prefect_client.read_task_run(tr_state.state_details.task_run_id) assert task_run.name == "chris-wuz-here" async def test_task_run_name_is_set_with_function_not_returning_string(prefect_client): def generate_task_run_name(): pass @task(task_run_name=generate_task_run_name) def my_task(name, where="here"): return name @flow def my_flow(name): return my_task(name) with pytest.raises( TypeError, match=( r"Callable <function" r" test_task_run_name_is_set_with_function_not_returning_string.<locals>.generate_task_run_name" r" at .*> for 'task_run_name' returned type NoneType but a string is" r" required" ), ): my_flow("anon") async def test_sets_run_name_once(): generate_task_run_name = MagicMock(return_value="some-string") mocked_task_method = MagicMock(side_effect=RuntimeError("Oh-no!, anyway")) decorated_task_method = task(task_run_name=generate_task_run_name, retries=3)( mocked_task_method ) @flow def my_flow(name): return decorated_task_method() state = my_flow(name="some-name", return_state=True) assert state.type == StateType.FAILED assert mocked_task_method.call_count == 4 assert generate_task_run_name.call_count == 1 async def test_sets_run_name_once_per_call(): task_calls = 0 generate_task_run_name = MagicMock(return_value="some-string") def test_task(x: str): nonlocal task_calls task_calls += 1 decorated_task_method = task(task_run_name=generate_task_run_name)(test_task) @flow def my_flow(name): decorated_task_method("a") decorated_task_method("b") return "hi" state = my_flow(name="some-name", return_state=True) assert state.type == StateType.COMPLETED assert task_calls == 2 assert generate_task_run_name.call_count == 2 def test_task_parameter_annotations_can_be_non_pydantic_classes(): class Test: pass @task def my_task(instance: Test): return instance @flow def my_flow(instance: Test): return my_task(instance) instance = my_flow(Test()) assert isinstance(instance, Test) def create_hook(mock_obj): def my_hook(task, task_run, state): mock_obj() return my_hook def create_async_hook(mock_obj): async def my_hook(task, task_run, state): mock_obj() return my_hook
TestTaskConstructorValidation
python
scipy__scipy
benchmarks/benchmarks/fft_basic.py
{ "start": 4531, "end": 5162 }
class ____(Benchmark): params = [ ["100x100", "313x100", "1000x100", "256x256", "512x512"], ['real', 'cmplx'], ['scipy.fftpack', 'scipy.fft', 'numpy.fft'] ] param_names = ['size', 'type', 'module'] def setup(self, size, cmplx, module): size = list(map(int, size.split("x"))) if cmplx != 'cmplx': self.x = random(size).astype(double) else: self.x = random(size).astype(cdouble)+random(size).astype(cdouble)*1j self.fftn = getattr(get_module(module), 'fftn') def time_fftn(self, size, cmplx, module): self.fftn(self.x)
Fftn
python
encode__django-rest-framework
tests/test_requests_client.py
{ "start": 1933, "end": 2957 }
class ____(APIView): @method_decorator(ensure_csrf_cookie) def get(self, request): if request.user.is_authenticated: username = request.user.username else: username = None return Response({ 'username': username }) @method_decorator(csrf_protect) def post(self, request): username = request.data['username'] password = request.data['password'] user = authenticate(username=username, password=password) if user is None: return Response({'error': 'incorrect credentials'}) login(request, user) return redirect('/auth/') urlpatterns = [ path('', Root.as_view(), name='root'), path('headers/', HeadersView.as_view(), name='headers'), path('session/', SessionView.as_view(), name='session'), path('auth/', AuthView.as_view(), name='auth'), ] @unittest.skipUnless(requests, 'requests not installed') @override_settings(ROOT_URLCONF='tests.test_requests_client')
AuthView
python
mlflow__mlflow
mlflow/data/evaluation_dataset.py
{ "start": 8940, "end": 20783 }
class ____: """ An input dataset for model evaluation. This is intended for use with the :py:func:`mlflow.models.evaluate()` API. """ NUM_SAMPLE_ROWS_FOR_HASH = 5 SPARK_DATAFRAME_LIMIT = 10000 def __init__( self, data, *, targets=None, name=None, path=None, feature_names=None, predictions=None, digest=None, ): """ The values of the constructor arguments comes from the `evaluate` call. """ if name is not None and '"' in name: raise MlflowException( message=f'Dataset name cannot include a double quote (") but got {name}', error_code=INVALID_PARAMETER_VALUE, ) if path is not None and '"' in path: raise MlflowException( message=f'Dataset path cannot include a double quote (") but got {path}', error_code=INVALID_PARAMETER_VALUE, ) self._user_specified_name = name self._path = path self._hash = None self._supported_dataframe_types = (pd.DataFrame,) self._spark_df_type = None self._labels_data = None self._targets_name = None self._has_targets = False self._predictions_data = None self._predictions_name = None self._has_predictions = predictions is not None self._digest = digest try: # add checking `'pyspark' in sys.modules` to avoid importing pyspark when user # run code not related to pyspark. if "pyspark" in sys.modules: from mlflow.utils.spark_utils import get_spark_dataframe_type spark_df_type = get_spark_dataframe_type() self._supported_dataframe_types = (pd.DataFrame, spark_df_type) self._spark_df_type = spark_df_type except ImportError: pass if feature_names is not None and len(set(feature_names)) < len(list(feature_names)): raise MlflowException( message="`feature_names` argument must be a list containing unique feature names.", error_code=INVALID_PARAMETER_VALUE, ) if self._has_predictions: _validate_dataset_type_supports_predictions( data=data, supported_predictions_dataset_types=self._supported_dataframe_types, ) has_targets = targets is not None if has_targets: self._has_targets = True if isinstance(data, (np.ndarray, list)): if has_targets and not isinstance(targets, (np.ndarray, list)): raise MlflowException( message="If data is a numpy array or list of evaluation features, " "`targets` argument must be a numpy array or list of evaluation labels.", error_code=INVALID_PARAMETER_VALUE, ) shape_message = ( "If the `data` argument is a numpy array, it must be a 2-dimensional " "array, with the second dimension representing the number of features. If the " "`data` argument is a list, each of its elements must be a feature array of " "the numpy array or list, and all elements must have the same length." ) if isinstance(data, list): try: data = np.array(data) except ValueError as e: raise MlflowException( message=shape_message, error_code=INVALID_PARAMETER_VALUE ) from e if len(data.shape) != 2: raise MlflowException( message=shape_message, error_code=INVALID_PARAMETER_VALUE, ) self._features_data = data if has_targets: self._labels_data = ( targets if isinstance(targets, np.ndarray) else np.array(targets) ) if len(self._features_data) != len(self._labels_data): raise MlflowException( message="The input features example rows must be the same length " "with labels array.", error_code=INVALID_PARAMETER_VALUE, ) num_features = data.shape[1] if feature_names is not None: feature_names = list(feature_names) if num_features != len(feature_names): raise MlflowException( message="feature name list must be the same length with feature data.", error_code=INVALID_PARAMETER_VALUE, ) self._feature_names = feature_names else: self._feature_names = [ f"feature_{str(i + 1).zfill(math.ceil(math.log10(num_features + 1)))}" for i in range(num_features) ] elif isinstance(data, self._supported_dataframe_types): if has_targets and not isinstance(targets, str): raise MlflowException( message="If data is a Pandas DataFrame or Spark DataFrame, `targets` argument " "must be the name of the column which contains evaluation labels in the `data` " "dataframe.", error_code=INVALID_PARAMETER_VALUE, ) if self._spark_df_type and isinstance(data, self._spark_df_type): if data.count() > EvaluationDataset.SPARK_DATAFRAME_LIMIT: _logger.warning( "Specified Spark DataFrame is too large for model evaluation. Only " f"the first {EvaluationDataset.SPARK_DATAFRAME_LIMIT} rows will be used. " "If you want evaluate on the whole spark dataframe, please manually call " "`spark_dataframe.toPandas()`." ) data = data.limit(EvaluationDataset.SPARK_DATAFRAME_LIMIT).toPandas() if has_targets: self._labels_data = data[targets].to_numpy() self._targets_name = targets if self._has_predictions: self._predictions_data = data[predictions].to_numpy() self._predictions_name = predictions if feature_names is not None: self._features_data = data[list(feature_names)] self._feature_names = feature_names else: features_data = data if has_targets: features_data = features_data.drop(targets, axis=1, inplace=False) if self._has_predictions: features_data = features_data.drop(predictions, axis=1, inplace=False) self._features_data = features_data self._feature_names = [ generate_feature_name_if_not_string(c) for c in self._features_data.columns ] else: raise MlflowException( message="The data argument must be a numpy array, a list or a Pandas DataFrame, or " "spark DataFrame if pyspark package installed.", error_code=INVALID_PARAMETER_VALUE, ) # generate dataset hash md5_gen = hashlib.md5(usedforsecurity=False) _gen_md5_for_arraylike_obj(md5_gen, self._features_data) if self._labels_data is not None: _gen_md5_for_arraylike_obj(md5_gen, self._labels_data) if self._predictions_data is not None: _gen_md5_for_arraylike_obj(md5_gen, self._predictions_data) md5_gen.update(",".join(list(map(str, self._feature_names))).encode("UTF-8")) self._hash = md5_gen.hexdigest() @property def feature_names(self): return self._feature_names @property def features_data(self): """ return features data as a numpy array or a pandas DataFrame. """ return self._features_data @property def labels_data(self): """ return labels data as a numpy array """ return self._labels_data @property def has_targets(self): """ Returns True if the dataset has targets, False otherwise. """ return self._has_targets @property def targets_name(self): """ return targets name """ return self._targets_name @property def predictions_data(self): """ return labels data as a numpy array """ return self._predictions_data @property def has_predictions(self): """ Returns True if the dataset has targets, False otherwise. """ return self._has_predictions @property def predictions_name(self): """ return predictions name """ return self._predictions_name @property def name(self): """ Dataset name, which is specified dataset name or the dataset hash if user don't specify name. """ return self._user_specified_name if self._user_specified_name is not None else self.hash @property def path(self): """ Dataset path """ return self._path @property def hash(self): """ Dataset hash, includes hash on first 20 rows and last 20 rows. """ return self._hash @property def _metadata(self): """ Return dataset metadata containing name, hash, and optional path. """ metadata = { "name": self.name, "hash": self.hash, } if self.path is not None: metadata["path"] = self.path return metadata @property def digest(self): """ Return the digest of the dataset. """ return self._digest def _log_dataset_tag(self, client, run_id, model_uuid): """ Log dataset metadata as a tag "mlflow.datasets", if the tag already exists, it will append current dataset metadata into existing tag content. """ existing_dataset_metadata_str = client.get_run(run_id).data.tags.get( "mlflow.datasets", "[]" ) dataset_metadata_list = json.loads(existing_dataset_metadata_str) for metadata in dataset_metadata_list: if ( metadata["hash"] == self.hash and metadata["name"] == self.name and metadata["model"] == model_uuid ): break else: dataset_metadata_list.append({**self._metadata, "model": model_uuid}) dataset_metadata_str = json.dumps(dataset_metadata_list, separators=(",", ":")) client.log_batch( run_id, tags=[RunTag("mlflow.datasets", dataset_metadata_str)], ) def __hash__(self): return hash(self.hash) def __eq__(self, other): if not isinstance(other, EvaluationDataset): return False if isinstance(self._features_data, np.ndarray): is_features_data_equal = np.array_equal(self._features_data, other._features_data) else: is_features_data_equal = self._features_data.equals(other._features_data) return ( is_features_data_equal and np.array_equal(self._labels_data, other._labels_data) and self.name == other.name and self.path == other.path and self._feature_names == other._feature_names )
EvaluationDataset
python
bokeh__bokeh
tests/unit/bokeh/command/subcommands/test_serve.py
{ "start": 1612, "end": 2880 }
class ____: def __init__(self, stream) -> None: ''' stream: the stream to read from. Usually a process' stdout or stderr. ''' self._s = stream self._q = Queue() def _populateQueue(stream, queue): ''' Collect lines from 'stream' and put them in 'queue'. ''' while True: line = stream.readline() if line: queue.put(line) else: break self._t = Thread(target = _populateQueue, args = (self._s, self._q)) self._t.daemon = True self._t.start() #start collecting lines from the stream def readline(self, timeout = None): try: return self._q.get(block = timeout is not None, timeout = timeout) except Empty: return None #----------------------------------------------------------------------------- # General API #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Dev API #-----------------------------------------------------------------------------
NBSR
python
getsentry__sentry
src/sentry/integrations/analytics.py
{ "start": 1809, "end": 1978 }
class ____(analytics.Event): provider: str | None id: int organization_id: int @analytics.eventclass("integration.stacktrace.linked")
IntegrationResolvePREvent
python
getsentry__sentry
src/sentry/incidents/grouptype.py
{ "start": 6147, "end": 12527 }
class ____(StatefulDetectorHandler[MetricUpdate, MetricResult]): def build_detector_evidence_data( self, evaluation_result: ProcessedDataConditionGroup, data_packet: DataPacket[MetricUpdate], priority: DetectorPriorityLevel, ) -> dict[str, Any]: try: alert_rule_detector = AlertRuleDetector.objects.get(detector=self.detector) return {"alert_id": alert_rule_detector.alert_rule_id} except AlertRuleDetector.DoesNotExist: logger.warning( "No alert rule detector found for detector id %s", self.detector.id, extra={ "detector_id": self.detector.id, }, ) return {"alert_id": None} def create_occurrence( self, evaluation_result: ProcessedDataConditionGroup, data_packet: DataPacket[MetricUpdate], priority: DetectorPriorityLevel, ) -> tuple[DetectorOccurrence, EventData]: try: detector_trigger = DataCondition.objects.get( condition_group=self.detector.workflow_condition_group, condition_result=priority ) except DataCondition.DoesNotExist: raise DetectorException( f"Failed to find detector trigger for detector id {self.detector.id}, cannot create metric issue occurrence" ) try: query_subscription = QuerySubscription.objects.get(id=data_packet.source_id) except QuerySubscription.DoesNotExist: raise DetectorException( f"Failed to find query subscription for detector id {self.detector.id}, cannot create metric issue occurrence" ) try: snuba_query = SnubaQuery.objects.get(id=query_subscription.snuba_query_id) except SnubaQuery.DoesNotExist: raise DetectorException( f"Failed to find snuba query for detector id {self.detector.id}, cannot create metric issue occurrence" ) try: assignee = parse_and_validate_actor( str(self.detector.created_by_id), self.detector.project.organization_id ) except Exception: assignee = None return ( DetectorOccurrence( issue_title=self.detector.name, subtitle=self.construct_title(snuba_query, detector_trigger, priority), evidence_data={ **self.build_detector_evidence_data(evaluation_result, data_packet, priority), }, evidence_display=[], # XXX: may need to pass more info here for the front end type=MetricIssue, level="error", culprit="", assignee=assignee, priority=priority, ), {}, ) def extract_dedupe_value(self, data_packet: DataPacket[MetricUpdate]) -> int: return int(data_packet.packet.timestamp.timestamp()) def extract_value(self, data_packet: DataPacket[MetricUpdate]) -> MetricResult: # this is a bit of a hack - anomaly detection data packets send extra data we need to pass along values = data_packet.packet.values if isinstance(data_packet.packet, AnomalyDetectionUpdate): return {None: values} return values.get("value") def construct_title( self, snuba_query: SnubaQuery, detector_trigger: DataCondition, priority: DetectorPriorityLevel, ) -> str: comparison_delta = self.detector.config.get("comparison_delta") detection_type = self.detector.config.get("detection_type") agg_display_key = snuba_query.aggregate if is_mri_field(agg_display_key): aggregate = format_mri_field(agg_display_key) elif CRASH_RATE_ALERT_AGGREGATE_ALIAS in agg_display_key: agg_display_key = agg_display_key.split(f"AS {CRASH_RATE_ALERT_AGGREGATE_ALIAS}")[ 0 ].strip() aggregate = QUERY_AGGREGATION_DISPLAY.get(agg_display_key, agg_display_key) else: aggregate = QUERY_AGGREGATION_DISPLAY.get(agg_display_key, agg_display_key) if detection_type == "dynamic": alert_type = aggregate try: dataset = Dataset(snuba_query.dataset) alert_type = get_alert_type_from_aggregate_dataset( agg_display_key, dataset, self.detector.project.organization ) except ValueError: logger.exception( "Failed to get alert type from aggregate and dataset", extra={ "aggregate": aggregate, "dataset": snuba_query.dataset, "detector_id": self.detector.id, }, ) return f"Detected an anomaly in the query for {alert_type}" # Determine the higher or lower comparison higher_or_lower = "" if detector_trigger.type == Condition.GREATER: higher_or_lower = "greater than" if comparison_delta else "above" else: higher_or_lower = "less than" if comparison_delta else "below" label = "Warning" if priority == DetectorPriorityLevel.MEDIUM else "Critical" # Format the time window for the threshold time_window = format_duration_idiomatic(snuba_query.time_window // 60) # If the detector_trigger has a comparison delta, format the comparison string comparison: str | int | float = "threshold" if comparison_delta: comparison_delta_minutes = comparison_delta // 60 comparison = TEXT_COMPARISON_DELTA.get( comparison_delta_minutes, f"same time {comparison_delta_minutes} minutes ago " ) else: comparison = detector_trigger.comparison template = "{label}: {metric} in the last {time_window} {higher_or_lower} {comparison}" return template.format( label=label.capitalize(), metric=aggregate, higher_or_lower=higher_or_lower, comparison=comparison, time_window=time_window, ) @dataclass(frozen=True)
MetricIssueDetectorHandler
python
sqlalchemy__sqlalchemy
test/ext/test_mutable.py
{ "start": 34518, "end": 35066 }
class ____( _MutableDictTestBase, fixtures.MappedTest ): @classmethod def define_tables(cls, metadata): MutableDict = cls._type_fixture() MutableDict.associate_with(PickleType) Table( "foo", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("skip", PickleType), Column("data", PickleType), Column("unrelated_data", String(50)), )
MutableAssociationScalarPickleTest
python
python-openxml__python-docx
src/docx/oxml/shape.py
{ "start": 8216, "end": 8883 }
class ____(BaseOxmlElement): """``<a:xfrm>`` element, specifies size and shape of picture container.""" off = ZeroOrOne("a:off", successors=("a:ext",)) ext = ZeroOrOne("a:ext", successors=()) @property def cx(self): ext = self.ext if ext is None: return None return ext.cx @cx.setter def cx(self, value): ext = self.get_or_add_ext() ext.cx = value @property def cy(self): ext = self.ext if ext is None: return None return ext.cy @cy.setter def cy(self, value): ext = self.get_or_add_ext() ext.cy = value
CT_Transform2D
python
spack__spack
lib/spack/spack/test/installer.py
{ "start": 25723, "end": 25935 }
class ____(inst.InstallStatus): def next_pkg(self, *args, **kwargs): pass def set_term_title(self, *args, **kwargs): pass def get_progress(self): return "1/1"
MockInstallStatus
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/random/parameterized_truncated_normal_op_test.py
{ "start": 3896, "end": 18808 }
class ____(test.TestCase): z_limit = 6.0 # Stop at moment 10 to avoid numerical errors in the theoretical moments. max_moment = 10 def validateMoments(self, shape, mean, stddev, minval, maxval, use_stateless=False, seed=1618): try: # TruncatedNormalMoments requires scipy.stats. # Give up early if we are unable to import it. random_seed.set_random_seed(seed) with self.cached_session(): if use_stateless: # Generate a seed that stateless ops can use. new_seed = random_ops.random_uniform([2], seed=seed, minval=0, maxval=(2**31 - 1), dtype=np.int32) samples = stateless.stateless_parameterized_truncated_normal( shape, new_seed, mean, stddev, minval, maxval).eval() else: samples = random_ops.parameterized_truncated_normal( shape, mean, stddev, minval, maxval).eval() assert (~np.isnan(samples)).all() moments = calculate_moments(samples, self.max_moment) expected_moments = TruncatedNormalMoments(mean, stddev, minval, maxval) num_samples = functools.reduce(lambda x, y: x * y, shape, 1) for i in range(1, len(moments)): self.assertLess( z_test(moments, expected_moments, i, num_samples), self.z_limit) except ImportError as e: tf_logging.warn("Cannot test truncated normal op: %s" % str(e)) def validateKolmogorovSmirnov(self, shape, mean, stddev, minval, maxval, use_stateless=False, seed=1618): try: import scipy.stats # pylint: disable=g-import-not-at-top random_seed.set_random_seed(seed) with self.cached_session(): if use_stateless: new_seed = random_ops.random_uniform([2], seed=seed, minval=0, maxval=(2**31 - 1), dtype=np.int32) samples = stateless.stateless_parameterized_truncated_normal( shape, new_seed, mean, stddev, minval, maxval).eval() else: samples = random_ops.parameterized_truncated_normal( shape, mean, stddev, minval, maxval).eval() assert (~np.isnan(samples)).all() minval = max(mean - stddev * 10, minval) maxval = min(mean + stddev * 10, maxval) dist = scipy.stats.norm(loc=mean, scale=stddev) cdf_min = dist.cdf(minval) cdf_max = dist.cdf(maxval) def truncated_cdf(x): return np.clip((dist.cdf(x) - cdf_min) / (cdf_max - cdf_min), 0.0, 1.0) pvalue = scipy.stats.kstest(samples, truncated_cdf)[1] self.assertGreater(pvalue, 1e-10) except ImportError as e: tf_logging.warn("Cannot test truncated normal op: %s" % str(e)) @test_util.run_deprecated_v1 def testDefaults(self): self.validateMoments([int(1e5)], 0.0, 1.0, -2.0, 2.0) self.validateMoments([int(1e5)], 0.0, 1.0, -2.0, 2.0, use_stateless=True) @test_util.run_deprecated_v1 def testShifted(self): self.validateMoments([int(1e5)], -1.0, 1.0, -2.0, 2.0) self.validateMoments([int(1e5)], -1.0, 1.0, -2.0, 2.0, use_stateless=True) @test_util.run_deprecated_v1 def testRightTail(self): self.validateMoments([int(1e5)], 0.0, 1.0, 4.0, np.inf) self.validateMoments([int(1e5)], 0.0, 1.0, 4.0, np.inf, use_stateless=True) @test_util.run_deprecated_v1 def testLeftTail(self): self.validateMoments([int(1e5)], 0.0, 1.0, -np.inf, -4.0) self.validateMoments([int(1e5)], 0.0, 1.0, -np.inf, -4.0, use_stateless=True) @test_util.run_deprecated_v1 def testLeftTailTwoSidedBounds(self): self.validateMoments([int(1e5)], 0.0, 1.0, -6.0, -3.0) self.validateMoments([int(1e5)], 0.0, 1.0, -6.0, -3.0, use_stateless=True) @test_util.run_deprecated_v1 @test_util.disable_xla("Low probability region") def testTwoSidedLeftTailShifted(self): self.validateKolmogorovSmirnov([int(1e5)], 6.0, 1.0, -1.0, 1.0) self.validateKolmogorovSmirnov([int(1e5)], 6.0, 1.0, -1.0, 1.0, use_stateless=True) @test_util.run_deprecated_v1 @test_util.disable_xla("Low probability region") def testRightTailShifted(self): self.validateMoments([int(1e5)], -5.0, 1.0, 2.0, np.inf) self.validateMoments([int(1e5)], -5.0, 1.0, 2.0, np.inf, use_stateless=True) # Take the normal distribution around the mean, but truncating the left tail # far from the mean. @test_util.run_deprecated_v1 def testTruncateOnLeft_entireTailOnRight(self): self.validateKolmogorovSmirnov([int(1e5)], 10.0, 1.0, 4.0, np.inf) self.validateKolmogorovSmirnov([int(1e5)], 10.0, 1.0, 4.0, np.inf, use_stateless=True) # Take the normal distribution around the mean, but truncating the right tail. @test_util.run_deprecated_v1 def testTruncateOnRight_entireTailOnLeft(self): self.validateKolmogorovSmirnov([int(1e5)], -8, 1.0, -np.inf, -4.0) self.validateKolmogorovSmirnov([int(1e5)], -8., 1.0, -np.inf, -4.0, use_stateless=True) @test_util.run_deprecated_v1 def testSmallStddev(self): self.validateKolmogorovSmirnov([int(1e5)], 0.0, 0.1, 0.05, 0.10) self.validateKolmogorovSmirnov([int(1e5)], 0.0, 0.1, 0.05, 0.10, use_stateless=True) @test_util.run_deprecated_v1 def testSamplingWithSmallStdDevFarFromBound(self): sample_op = random_ops.parameterized_truncated_normal( shape=(int(1e5),), means=0.8, stddevs=0.05, minvals=-1., maxvals=1.) new_seed = random_ops.random_uniform([2], seed=1234, minval=0, maxval=(2**31 - 1), dtype=np.int32) sample_op_stateless = stateless.stateless_parameterized_truncated_normal( shape=(int(1e5),), seed=new_seed, means=0.8, stddevs=0.05, minvals=-1., maxvals=1.) with self.session() as sess: samples, samples_stateless = sess.run([sample_op, sample_op_stateless]) # 0. is more than 16 standard deviations from the mean, and # should have a likelihood < 1e-57. assert (~np.isnan(samples)).all() assert (~np.isnan(samples_stateless)).all() self.assertAllGreater(samples, 0.) self.assertAllGreater(samples_stateless, 0.) def testShapeTypes(self): for shape_dtype in [np.int32, np.int64]: shape = np.array([1000], dtype=shape_dtype) sample_op = random_ops.parameterized_truncated_normal( shape=shape, means=0.0, stddevs=0.1, minvals=-1., maxvals=1.) new_seed = random_ops.random_uniform([2], seed=1234, minval=0, maxval=(2**31 - 1), dtype=np.int32) sample_op_stateless = stateless.stateless_parameterized_truncated_normal( shape=shape, seed=new_seed, means=0.0, stddevs=0.1, minvals=-1., maxvals=1.) samples = self.evaluate(sample_op) stateless_samples = self.evaluate(sample_op_stateless) self.assertAllEqual(samples.shape, shape) self.assertAllEqual(stateless_samples.shape, shape) def testStatelessParameterizedTruncatedNormalHasGrads(self): mean = variables.Variable(0.01) stddev = variables.Variable(1.) minval = variables.Variable(-1.) maxval = variables.Variable(1.) with self.cached_session() as sess: with backprop.GradientTape(persistent=True) as tape: samples = stateless.stateless_parameterized_truncated_normal( [1], [1, 2], mean, stddev, minval, maxval) sess.run(variables.variables_initializer([mean, stddev, minval, maxval])) [mean_grad, std_grad], mean_actual_grad, std_actual_grad = sess.run([ tape.gradient(samples, [mean, stddev]), array_ops.ones_like(mean), (samples - mean) / stddev]) self.assertAllClose(mean_grad, mean_actual_grad) self.assertAllClose(std_grad, std_actual_grad[0]) try: import scipy.stats # pylint:disable=g-import-not-at-top truncnorm = scipy.stats.truncnorm(a=-1., b=1., loc=0., scale=1.) samples_np, [minval_grad, maxval_grad] = sess.run([ samples, tape.gradient(samples, [minval, maxval])]) sample_cdf = truncnorm.cdf(samples_np) # These come from the implicit reparameterization trick. scipy_maxval_grad = np.exp( 0.5 * (samples_np ** 2 - ((1. - 0.01) / 1.) ** 2) + np.log(sample_cdf)) scipy_minval_grad = np.exp( 0.5 * (samples_np ** 2 - ((-1. - 0.01) / 1.) ** 2) + np.log1p(-sample_cdf)) self.assertAllClose(minval_grad, scipy_minval_grad[0], rtol=1e-2) self.assertAllClose(maxval_grad, scipy_maxval_grad[0], rtol=1e-2) except ImportError as e: tf_logging.warn("Cannot test truncated normal op: %s" % str(e)) @test_util.run_deprecated_v1 def testSamplingAtRandnSwitchover(self): # The randn sampler is used as the bounds are moved farther from the mean, # and the probability of accepting a sample increases the farther the # bounds are from the mean. # This test asserts that at the point of switchover, both samplers are # working (not raising an error or returning nan) and returning the # expected moments. use_gpu = test.is_gpu_available() stddev_inside_bounds_before_using_randn = ( _get_stddev_inside_bounds_before_using_randn(use_gpu)) epsilon = 0.001 self.validateMoments( shape=[int(1e6)], mean=0., stddev=1.0, minval=-epsilon, maxval=stddev_inside_bounds_before_using_randn - epsilon) self.validateMoments( shape=[int(1e6)], mean=0., stddev=1.0, minval=-epsilon, maxval=stddev_inside_bounds_before_using_randn + epsilon) self.validateMoments( shape=[int(1e6)], mean=0., stddev=1.0, minval=-epsilon, maxval=stddev_inside_bounds_before_using_randn - epsilon, use_stateless=True) self.validateMoments( shape=[int(1e6)], mean=0., stddev=1.0, minval=-epsilon, maxval=stddev_inside_bounds_before_using_randn + epsilon, use_stateless=True) # Benchmarking code def parameterized_vs_naive(shape, num_iters, use_gpu=False): np.random.seed(1618) # Make it reproducible. # No CSE/CF. optimizer_options = config_pb2.OptimizerOptions( opt_level=config_pb2.OptimizerOptions.L0) config = config_pb2.ConfigProto(graph_options=config_pb2.GraphOptions( optimizer_options=optimizer_options)) with session.Session(config=config) as sess: with ops.device("/cpu:0" if not use_gpu else None): param_op = control_flow_ops.group( random_ops.parameterized_truncated_normal(shape)) naive_op = control_flow_ops.group(random_ops.truncated_normal(shape)) # Burn-in to avoid session setup costs in the timing. sess.run(param_op) sess.run(param_op) param_dt = timeit.timeit(lambda: sess.run(param_op), number=num_iters) sess.run(naive_op) sess.run(naive_op) naive_dt = timeit.timeit(lambda: sess.run(naive_op), number=num_iters) return param_dt, naive_dt def randn_sampler_switchover(shape, num_iters, use_gpu=False): # Benchmark by constructing samplers on the threshold of using the randn # rejection sampling and check that this threshold is set correctly by # benchmarking with bounds just above and below this threshold. # The uniform and randn samplers should have about the same performance # at this point. stddev_inside_bounds_before_using_randn = ( _get_stddev_inside_bounds_before_using_randn(use_gpu)) epsilon = 0.001 np.random.seed(1618) # Make it reproducible. # No CSE/CF. optimizer_options = config_pb2.OptimizerOptions( opt_level=config_pb2.OptimizerOptions.L0) config = config_pb2.ConfigProto( graph_options=config_pb2.GraphOptions( optimizer_options=optimizer_options)) with session.Session(config=config) as sess: with ops.device("/cpu:0" if not use_gpu else "/gpu:0"): uniform_sampler_op = control_flow_ops.group( random_ops.parameterized_truncated_normal( shape, means=0., stddevs=1.0, minvals=-stddev_inside_bounds_before_using_randn + epsilon, maxvals=0.01)) randn_sampler_op = control_flow_ops.group( random_ops.parameterized_truncated_normal( shape, means=0., stddevs=1.0, minvals=-stddev_inside_bounds_before_using_randn - epsilon, maxvals=0.01)) # Burn-in to avoid session setup costs in the timing. sess.run(uniform_sampler_op) sess.run(uniform_sampler_op) uniform_dt = timeit.timeit( lambda: sess.run(uniform_sampler_op), number=num_iters) sess.run(randn_sampler_op) sess.run(randn_sampler_op) randn_dt = timeit.timeit( lambda: sess.run(randn_sampler_op), number=num_iters) return randn_dt, uniform_dt
ParameterizedTruncatedNormalTest
python
wandb__wandb
wandb/util.py
{ "start": 47914, "end": 61418 }
class ____: def __init__(self) -> None: self.modules: dict[str, ModuleType] = dict() self.on_import: dict[str, list] = dict() def add(self, fullname: str, on_import: Callable) -> None: self.on_import.setdefault(fullname, []).append(on_import) def install(self) -> None: sys.meta_path.insert(0, self) # type: ignore def uninstall(self) -> None: sys.meta_path.remove(self) # type: ignore def find_module( self, fullname: str, path: str | None = None ) -> ImportMetaHook | None: if fullname in self.on_import: return self return None def load_module(self, fullname: str) -> ModuleType: self.uninstall() mod = importlib.import_module(fullname) self.install() self.modules[fullname] = mod on_imports = self.on_import.get(fullname) if on_imports: for f in on_imports: f() return mod def get_modules(self) -> tuple[str, ...]: return tuple(self.modules) def get_module(self, module: str) -> ModuleType: return self.modules[module] _import_hook: ImportMetaHook | None = None def add_import_hook(fullname: str, on_import: Callable) -> None: global _import_hook if _import_hook is None: _import_hook = ImportMetaHook() _import_hook.install() _import_hook.add(fullname, on_import) def host_from_path(path: str | None) -> str: """Return the host of the path.""" url = urllib.parse.urlparse(path) return str(url.netloc) def uri_from_path(path: str | None) -> str: """Return the URI of the path.""" url = urllib.parse.urlparse(path) uri = url.path if url.path[0] != "/" else url.path[1:] return str(uri) def is_unicode_safe(stream: TextIO) -> bool: """Return True if the stream supports UTF-8.""" encoding = getattr(stream, "encoding", None) return encoding.lower() in {"utf-8", "utf_8"} if encoding else False def rand_alphanumeric( length: int = 8, rand: ModuleType | random.Random | None = None ) -> str: wandb.termerror("rand_alphanumeric is deprecated, use 'secrets.token_hex'") rand = rand or random return "".join(rand.choice("0123456789ABCDEF") for _ in range(length)) @contextlib.contextmanager def fsync_open( path: StrPath, mode: str = "w", encoding: str | None = None ) -> Generator[IO[Any], None, None]: """Open a path for I/O and guarantee that the file is flushed and synced.""" with open(path, mode, encoding=encoding) as f: yield f f.flush() os.fsync(f.fileno()) def _is_kaggle() -> bool: return ( os.getenv("KAGGLE_KERNEL_RUN_TYPE") is not None or "kaggle_environments" in sys.modules ) def _has_internet() -> bool: """Returns whether we have internet access. Checks for internet access by attempting to open a DNS connection to Google's root servers. """ try: s = socket.create_connection(("8.8.8.8", 53), 0.5) s.close() except OSError: return False return True def _is_likely_kaggle() -> bool: # Telemetry to mark first runs from Kagglers. return ( _is_kaggle() or os.path.exists( os.path.expanduser(os.path.join("~", ".kaggle", "kaggle.json")) ) or "kaggle" in sys.modules ) def _is_databricks() -> bool: # check if we are running inside a databricks notebook by # inspecting sys.modules, searching for dbutils and verifying that # it has the appropriate structure if "dbutils" in sys.modules: dbutils = sys.modules["dbutils"] if hasattr(dbutils, "shell"): shell = dbutils.shell if hasattr(shell, "sc"): sc = shell.sc if hasattr(sc, "appName"): return bool(sc.appName == "Databricks Shell") return False def _is_py_requirements_or_dockerfile(path: str) -> bool: file = os.path.basename(path) return ( file.endswith(".py") or file.startswith("Dockerfile") or file == "requirements.txt" ) def artifact_to_json(artifact: Artifact) -> dict[str, Any]: return { "_type": "artifactVersion", "_version": "v0", "id": artifact.id, "version": artifact.source_version, "sequenceName": artifact.source_name.split(":")[0], "usedAs": artifact.use_as, } def check_dict_contains_nested_artifact(d: dict, nested: bool = False) -> bool: for item in d.values(): if isinstance(item, dict): contains_artifacts = check_dict_contains_nested_artifact(item, True) if contains_artifacts: return True elif (isinstance(item, wandb.Artifact) or _is_artifact_string(item)) and nested: return True return False def load_json_yaml_dict(config: str) -> Any: import yaml ext = os.path.splitext(config)[-1] if ext == ".json": with open(config) as f: return json.load(f) elif ext == ".yaml": with open(config) as f: return yaml.safe_load(f) else: try: return json.loads(config) except ValueError: return None def _parse_entity_project_item(path: str) -> tuple: """Parse paths with the following formats: {item}, {project}/{item}, & {entity}/{project}/{item}. Args: path: `str`, input path; must be between 0 and 3 in length. Returns: tuple of length 3 - (item, project, entity) Example: alias, project, entity = _parse_entity_project_item("myproj/mymodel:best") assert entity == "" assert project == "myproj" assert alias == "mymodel:best" """ words = path.split("/") if len(words) > 3: raise ValueError( "Invalid path: must be str the form {item}, {project}/{item}, or {entity}/{project}/{item}" ) padded_words = [""] * (3 - len(words)) + words return tuple(reversed(padded_words)) def _resolve_aliases(aliases: str | Iterable[str] | None) -> list[str]: """Add the 'latest' alias and ensure that all aliases are unique. Takes in `aliases` which can be None, str, or List[str] and returns list[str]. Ensures that "latest" is always present in the returned list. Args: aliases: `aliases: str | Iterable[str] | None` Returns: list[str], with "latest" always present. Usage: ```python aliases = _resolve_aliases(["best", "dev"]) assert aliases == ["best", "dev", "latest"] aliases = _resolve_aliases("boom") assert aliases == ["boom", "latest"] ``` """ aliases = aliases or ["latest"] if isinstance(aliases, str): aliases = [aliases] try: return list(set(aliases) | {"latest"}) except TypeError as exc: raise ValueError("`aliases` must be Iterable or None") from exc def _is_artifact_object(v: Any) -> TypeGuard[wandb.Artifact]: return isinstance(v, wandb.Artifact) def _is_artifact_string(v: Any) -> TypeGuard[str]: return isinstance(v, str) and v.startswith("wandb-artifact://") def _is_artifact_version_weave_dict(v: Any) -> TypeGuard[dict]: return isinstance(v, dict) and v.get("_type") == "artifactVersion" def _is_artifact_representation(v: Any) -> bool: return ( _is_artifact_object(v) or _is_artifact_string(v) or _is_artifact_version_weave_dict(v) ) def parse_artifact_string(v: str) -> tuple[str, str | None, bool]: if not v.startswith("wandb-artifact://"): raise ValueError(f"Invalid artifact string: {v}") parsed_v = v[len("wandb-artifact://") :] base_uri = None url_info = urllib.parse.urlparse(parsed_v) if url_info.scheme != "": base_uri = f"{url_info.scheme}://{url_info.netloc}" parts = url_info.path.split("/")[1:] else: parts = parsed_v.split("/") if parts[0] == "_id": # for now can't fetch paths but this will be supported in the future # when we allow passing typed media objects, this can be extended # to include paths return parts[1], base_uri, True if len(parts) < 3: raise ValueError(f"Invalid artifact string: {v}") # for now can't fetch paths but this will be supported in the future # when we allow passing typed media objects, this can be extended # to include paths entity, project, name_and_alias_or_version = parts[:3] return f"{entity}/{project}/{name_and_alias_or_version}", base_uri, False def _get_max_cli_version() -> str | None: max_cli_version = wandb.api.max_cli_version() return str(max_cli_version) if max_cli_version is not None else None def ensure_text( string: str | bytes, encoding: str = "utf-8", errors: str = "strict" ) -> str: """Coerce s to str.""" if isinstance(string, bytes): return string.decode(encoding, errors) elif isinstance(string, str): return string else: raise TypeError(f"not expecting type {type(string)!r}") def make_artifact_name_safe(name: str) -> str: """Make an artifact name safe for use in artifacts.""" # artifact names may only contain alphanumeric characters, dashes, underscores, and dots. cleaned = re.sub(r"[^a-zA-Z0-9_\-.]", "_", name) if len(cleaned) <= 128: return cleaned # truncate with dots in the middle using regex return re.sub(r"(^.{63}).*(.{63}$)", r"\g<1>..\g<2>", cleaned) def make_docker_image_name_safe(name: str) -> str: """Make a docker image name safe for use in artifacts.""" safe_chars = RE_DOCKER_IMAGE_NAME_CHARS.sub("__", name.lower()) deduped = RE_DOCKER_IMAGE_NAME_SEPARATOR_REPEAT.sub("__", safe_chars) trimmed_start = RE_DOCKER_IMAGE_NAME_SEPARATOR_START.sub("", deduped) trimmed = RE_DOCKER_IMAGE_NAME_SEPARATOR_END.sub("", trimmed_start) return trimmed if trimmed else "image" def merge_dicts( source: dict[str, Any], destination: dict[str, Any], ) -> dict[str, Any]: """Recursively merge two dictionaries. This mutates the destination and its nested dictionaries and lists. Instances of `dict` are recursively merged and instances of `list` are appended to the destination. If the destination type is not `dict` or `list`, respectively, the key is overwritten with the source value. For all other types, the source value overwrites the destination value. """ for key, value in source.items(): if isinstance(value, dict): node = destination.get(key) if isinstance(node, dict): merge_dicts(value, node) else: destination[key] = value elif isinstance(value, list): dest_value = destination.get(key) if isinstance(dest_value, list): dest_value.extend(value) else: destination[key] = value else: destination[key] = value return destination def coalesce(*arg: Any) -> Any: """Return the first non-none value in the list of arguments. Similar to ?? in C#. """ return next((a for a in arg if a is not None), None) def recursive_cast_dictlike_to_dict(d: dict[str, Any]) -> dict[str, Any]: for k, v in d.items(): if isinstance(v, dict): recursive_cast_dictlike_to_dict(v) elif hasattr(v, "keys"): d[k] = dict(v) recursive_cast_dictlike_to_dict(d[k]) return d def remove_keys_with_none_values(d: dict[str, Any] | Any) -> dict[str, Any] | Any: # otherwise iterrows will create a bunch of ugly charts if not isinstance(d, dict): return d if isinstance(d, dict): new_dict = {} for k, v in d.items(): new_v = remove_keys_with_none_values(v) if new_v is not None and not (isinstance(new_v, dict) and len(new_v) == 0): new_dict[k] = new_v return new_dict if new_dict else None def batched(n: int, iterable: Iterable[T]) -> Generator[list[T], None, None]: i = iter(iterable) batch = list(itertools.islice(i, n)) while batch: yield batch batch = list(itertools.islice(i, n)) def random_string(length: int = 12) -> str: """Generate a random string of a given length. :param length: Length of the string to generate. :return: Random string. """ return "".join( secrets.choice(string.ascii_lowercase + string.digits) for _ in range(length) ) def sample_with_exponential_decay_weights( xs: Iterable | Iterable[Iterable], ys: Iterable[Iterable], keys: Iterable | None = None, sample_size: int = 1500, ) -> tuple[list, list, list | None]: """Sample from a list of lists with weights that decay exponentially. May be used with the wandb.plot.line_series function. """ xs_array = np.array(xs) ys_array = np.array(ys) keys_array = np.array(keys) if keys else None weights = np.exp(-np.arange(len(xs_array)) / len(xs_array)) weights /= np.sum(weights) sampled_indices = np.random.choice(len(xs_array), size=sample_size, p=weights) sampled_xs = xs_array[sampled_indices].tolist() sampled_ys = ys_array[sampled_indices].tolist() sampled_keys = keys_array[sampled_indices].tolist() if keys_array else None return sampled_xs, sampled_ys, sampled_keys @dataclasses.dataclass(frozen=True)
ImportMetaHook
python
getsentry__sentry
tests/snuba/api/endpoints/test_organization_events.py
{ "start": 246309, "end": 253913 }
class ____( OrganizationEventsEndpointTestBase, SearchIssueTestMixin, PerformanceIssueTestCase ): def test_performance_issue_id_filter(self) -> None: event = self.create_performance_issue() assert event.group is not None query = { "field": ["count()"], "statsPeriod": "2h", "query": f"issue.id:{event.group.id}", "dataset": "issuePlatform", } response = self.do_request(query) assert response.status_code == 200, response.content assert response.data["data"][0]["count()"] == 1 def test_generic_issue_ids_filter(self) -> None: user_data = { "id": self.user.id, "username": "user", "email": "hellboy@bar.com", "ip_address": "127.0.0.1", } event, _, group_info = self.store_search_issue( self.project.id, self.user.id, [f"{ProfileFileIOGroupType.type_id}-group1"], "prod", before_now(hours=1), user=user_data, ) event, _, group_info = self.store_search_issue( self.project.id, self.user.id, [f"{ProfileFileIOGroupType.type_id}-group2"], "prod", before_now(hours=1), user=user_data, ) assert group_info is not None query = { "field": ["title", "release", "environment", "user.display", "timestamp"], "statsPeriod": "90d", "query": f"issue.id:{group_info.group.id}", "dataset": "issuePlatform", } with self.feature(["organizations:profiling"]): response = self.do_request(query) assert response.status_code == 200, response.content assert len(response.data["data"]) == 1 assert response.data["data"][0]["title"] == group_info.group.title assert response.data["data"][0]["environment"] == "prod" assert response.data["data"][0]["user.display"] == user_data["email"] assert response.data["data"][0]["timestamp"] == event.timestamp query = { "field": ["title", "release", "environment", "user.display", "timestamp"], "statsPeriod": "90d", "query": f"issue:{group_info.group.qualified_short_id}", "dataset": "issuePlatform", } with self.feature(["organizations:profiling"]): response = self.do_request(query) assert response.status_code == 200, response.content assert len(response.data["data"]) == 1 assert response.data["data"][0]["title"] == group_info.group.title assert response.data["data"][0]["environment"] == "prod" assert response.data["data"][0]["user.display"] == user_data["email"] assert response.data["data"][0]["timestamp"] == event.timestamp def test_performance_short_group_id(self) -> None: event = self.create_performance_issue() assert event.group is not None query = { "field": ["count()"], "statsPeriod": "1h", "query": f"project:{event.group.project.slug} issue:{event.group.qualified_short_id}", "dataset": "issuePlatform", } response = self.do_request(query) assert response.status_code == 200, response.content assert response.data["data"][0]["count()"] == 1 def test_multiple_performance_short_group_ids_filter(self) -> None: event1 = self.create_performance_issue() event2 = self.create_performance_issue() assert event1.group is not None assert event2.group is not None query = { "field": ["count()"], "statsPeriod": "1h", "query": f"project:{event1.group.project.slug} issue:[{event1.group.qualified_short_id},{event2.group.qualified_short_id}]", "dataset": "issuePlatform", } response = self.do_request(query) assert response.status_code == 200, response.content assert response.data["data"][0]["count()"] == 2 def test_user_display_issue_platform(self) -> None: project1 = self.create_project() user_data = { "id": self.user.id, "username": "user", "email": "hellboy@bar.com", "ip_address": "127.0.0.1", } _, _, group_info = self.store_search_issue( project1.id, 1, ["group1-fingerprint"], None, before_now(hours=1), user=user_data, ) assert group_info is not None features = { "organizations:discover-basic": True, "organizations:profiling": True, } query = { "field": ["user.display"], "query": f"user.display:hell* issue.id:{group_info.group.id}", "statsPeriod": "24h", "dataset": "issuePlatform", } response = self.do_request(query, features=features) assert response.status_code == 200, response.content data = response.data["data"] assert len(data) == 1 result = {r["user.display"] for r in data} assert result == {user_data["email"]} def test_all_events_fields(self) -> None: user_data = { "id": self.user.id, "username": "user", "email": "hellboy@bar.com", "ip_address": "127.0.0.1", } replay_id = str(uuid.uuid4()) profile_id = str(uuid.uuid4()) event = self.create_performance_issue( contexts={ "trace": { "trace_id": str(uuid.uuid4().hex), "span_id": "933e5c9a8e464da9", "type": "trace", }, "replay": {"replay_id": replay_id}, "profile": {"profile_id": profile_id}, }, user_data=user_data, ) assert event.group is not None query = { "field": [ "id", "transaction", "title", "release", "environment", "user.display", "device", "os", "url", "runtime", "replayId", "profile.id", "transaction.duration", "timestamp", ], "statsPeriod": "1h", "query": f"project:{event.group.project.slug} issue:{event.group.qualified_short_id}", "dataset": "issuePlatform", } response = self.do_request(query) assert response.status_code == 200, response.content data = response.data["data"][0] assert data == { "id": event.event_id, "transaction": event.transaction, "project.name": event.project.name.lower(), "title": event.group.title, "release": event.release, "environment": event.get_environment().name, "user.display": user_data["email"], "device": "Mac", "os": "", "url": event.interfaces["request"].full_url, "runtime": dict(event.get_raw_data()["tags"])["runtime"], "replayId": replay_id.replace("-", ""), "profile.id": profile_id.replace("-", ""), "transaction.duration": 3000, "timestamp": event.datetime.replace(microsecond=0).isoformat(), }
OrganizationEventsIssuePlatformDatasetEndpointTest
python
pikepdf__pikepdf
src/pikepdf/codec.py
{ "start": 3578, "end": 4041 }
class ____(codecs.Codec): """Implement PdfDocEncoding character map used inside PDFs.""" def encode(self, input: str, errors: str = 'strict') -> tuple[bytes, int]: """Implement codecs.Codec.encode for pdfdoc.""" return pdfdoc_encode(input, errors) def decode(self, input: Buffer, errors: str = 'strict') -> tuple[str, int]: """Implement codecs.Codec.decode for pdfdoc.""" return pdfdoc_decode(input, errors)
PdfDocCodec
python
numpy__numpy
numpy/ma/tests/test_extras.py
{ "start": 70946, "end": 72625 }
class ____: def test_ndenumerate_nomasked(self): ordinary = np.arange(6.).reshape((1, 3, 2)) empty_mask = np.zeros_like(ordinary, dtype=bool) with_mask = masked_array(ordinary, mask=empty_mask) assert_equal(list(np.ndenumerate(ordinary)), list(ndenumerate(ordinary))) assert_equal(list(ndenumerate(ordinary)), list(ndenumerate(with_mask))) assert_equal(list(ndenumerate(with_mask)), list(ndenumerate(with_mask, compressed=False))) def test_ndenumerate_allmasked(self): a = masked_all(()) b = masked_all((100,)) c = masked_all((2, 3, 4)) assert_equal(list(ndenumerate(a)), []) assert_equal(list(ndenumerate(b)), []) assert_equal(list(ndenumerate(b, compressed=False)), list(zip(np.ndindex((100,)), 100 * [masked]))) assert_equal(list(ndenumerate(c)), []) assert_equal(list(ndenumerate(c, compressed=False)), list(zip(np.ndindex((2, 3, 4)), 2 * 3 * 4 * [masked]))) def test_ndenumerate_mixedmasked(self): a = masked_array(np.arange(12).reshape((3, 4)), mask=[[1, 1, 1, 1], [1, 1, 0, 1], [0, 0, 0, 0]]) items = [((1, 2), 6), ((2, 0), 8), ((2, 1), 9), ((2, 2), 10), ((2, 3), 11)] assert_equal(list(ndenumerate(a)), items) assert_equal(len(list(ndenumerate(a, compressed=False))), a.size) for coordinate, value in ndenumerate(a, compressed=False): assert_equal(a[coordinate], value)
TestNDEnumerate
python
sphinx-doc__sphinx
sphinx/builders/latex/theming.py
{ "start": 356, "end": 1245 }
class ____: """A set of LaTeX configurations.""" LATEX_ELEMENTS_KEYS = ['papersize', 'pointsize'] UPDATABLE_KEYS = ['papersize', 'pointsize'] def __init__(self, name: str) -> None: self.name = name self.docclass = name self.wrapperclass = name self.papersize = 'letterpaper' self.pointsize = '10pt' self.toplevel_sectioning = 'chapter' def update(self, config: Config) -> None: """Override theme settings by user's configuration.""" for key in self.LATEX_ELEMENTS_KEYS: if config.latex_elements.get(key): value = config.latex_elements[key] setattr(self, key, value) for key in self.UPDATABLE_KEYS: if key in config.latex_theme_options: value = config.latex_theme_options[key] setattr(self, key, value)
Theme
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 64357, "end": 64418 }
class ____(str, Enum): KEYWORD = "keyword"
KeywordIndexType
python
huggingface__transformers
tests/models/xmod/test_modeling_xmod.py
{ "start": 13816, "end": 26921 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( XmodForCausalLM, XmodForMaskedLM, XmodModel, XmodForSequenceClassification, XmodForTokenClassification, XmodForMultipleChoice, XmodForQuestionAnswering, ) if is_torch_available() else () ) pipeline_model_mapping = ( { "feature-extraction": XmodModel, "fill-mask": XmodForMaskedLM, "question-answering": XmodForQuestionAnswering, "text-classification": XmodForSequenceClassification, "text-generation": XmodForCausalLM, "token-classification": XmodForTokenClassification, "zero-shot": XmodForSequenceClassification, } if is_torch_available() else {} ) # TODO: Fix the failed tests def is_pipeline_test_to_skip( self, pipeline_test_case_name, config_class, model_architecture, tokenizer_name, image_processor_name, feature_extractor_name, processor_name, ): if pipeline_test_case_name == "QAPipelineTests" and not tokenizer_name.endswith("Fast"): return True return False # Overwriting to add `is_decoder` flag def prepare_config_and_inputs_for_generate(self, batch_size=2): config, inputs = super().prepare_config_and_inputs_for_generate(batch_size) config.is_decoder = True return config, inputs def setUp(self): self.model_tester = XmodModelTester(self) self.config_tester = ConfigTester(self, config_class=XmodConfig, hidden_size=37) def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_model_as_decoder(self): config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(*config_and_inputs) def test_model_as_decoder_with_default_input_mask(self): ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) = self.model_tester.prepare_config_and_inputs_for_decoder() input_mask = None self.model_tester.create_and_check_model_as_decoder( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def test_for_causal_lm(self): config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_for_causal_lm(*config_and_inputs) def test_decoder_model_past_with_large_inputs(self): config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) def test_for_masked_lm(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*config_and_inputs) def test_for_token_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*config_and_inputs) def test_for_multiple_choice(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs) def test_for_question_answering(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*config_and_inputs) def test_create_position_ids_respects_padding_index(self): """This is a regression test for https://github.com/huggingface/transformers/issues/1761 The position ids should be masked with the embedding object's padding index. Therefore, the first available non-padding position index is XmodEmbeddings.padding_idx + 1 """ config = self.model_tester.prepare_config_and_inputs()[0] model = XmodEmbeddings(config=config) input_ids = torch.as_tensor([[12, 31, 13, model.padding_idx]]) expected_positions = torch.as_tensor( [[0 + model.padding_idx + 1, 1 + model.padding_idx + 1, 2 + model.padding_idx + 1, model.padding_idx]] ) position_ids = XmodEmbeddings.create_position_ids_from_input_ids(input_ids, model.padding_idx) self.assertEqual(position_ids.shape, expected_positions.shape) self.assertTrue(torch.all(torch.eq(position_ids, expected_positions))) def test_create_position_ids_from_inputs_embeds(self): """This is a regression test for https://github.com/huggingface/transformers/issues/1761 The position ids should be masked with the embedding object's padding index. Therefore, the first available non-padding position index is XmodEmbeddings.padding_idx + 1 """ config = self.model_tester.prepare_config_and_inputs()[0] embeddings = XmodEmbeddings(config=config) inputs_embeds = torch.empty(2, 4, 30) expected_single_positions = [ 0 + embeddings.padding_idx + 1, 1 + embeddings.padding_idx + 1, 2 + embeddings.padding_idx + 1, 3 + embeddings.padding_idx + 1, ] expected_positions = torch.as_tensor([expected_single_positions, expected_single_positions]) position_ids = embeddings.create_position_ids_from_inputs_embeds(inputs_embeds, embeddings.padding_idx) self.assertEqual(position_ids.shape, expected_positions.shape) self.assertTrue(torch.all(torch.eq(position_ids, expected_positions))) def test_set_default_language(self): config = self.model_tester.prepare_config_and_inputs()[0] model = XmodForMaskedLM(config=config) model.set_default_language("en_XX") self.assertEqual(model.config.default_language, "en_XX") with self.assertRaises(ValueError): model.set_default_language("xx_XX") def test_freeze_embeddings_and_language_adapters(self): config = self.model_tester.prepare_config_and_inputs()[0] model = XmodForMaskedLM(config=config) num_trainable_params_before = sum(p.numel() for p in model.parameters() if p.requires_grad) model.freeze_embeddings_and_language_adapters() num_trainable_params_after = sum(p.numel() for p in model.parameters() if p.requires_grad) self.assertLess(num_trainable_params_after, num_trainable_params_before) def attention_mask_padding_matches_padding_free_with_position_ids( self, attn_implementation: str, fa_kwargs: bool = False ): """ Overwritten to account for the embeddings that rely on position ids. """ if not self.has_attentions: self.skipTest(reason="Model architecture does not support attentions") max_new_tokens = 30 support_flag = { "sdpa": "_supports_sdpa", "flash_attention_2": "_supports_flash_attn", "flash_attention_3": "_supports_flash_attn", } for model_class in self.all_generative_model_classes: if attn_implementation != "eager" and not getattr(model_class, support_flag[attn_implementation]): self.skipTest(f"{model_class.__name__} does not support {attn_implementation}") # can't infer if new attn mask API is supported by assume that only model with attention backend support it if not model_class._supports_attention_backend: self.skipTest(f"{model_class.__name__} does not support new attention mask API") if model_class._is_stateful: # non-transformer models most probably have no packing support self.skipTest(f"{model_class.__name__} doesn't support packing!") config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() if config.is_encoder_decoder: self.skipTest("Model is an encoder-decoder") if 0 not in inputs_dict.get("attention_mask", []) or "attention_mask" not in inputs_dict: self.skipTest("Model dummy inputs should contain padding in their attention mask") if "input_ids" not in inputs_dict or inputs_dict["input_ids"].ndim != 2: self.skipTest("Model dummy inputs should contain text input ids") # make sure that all models have enough positions for generation dummy_input_ids = inputs_dict["input_ids"] if hasattr(config, "max_position_embeddings"): config.max_position_embeddings = max_new_tokens + dummy_input_ids.shape[1] + 1 model = model_class(config) if "position_ids" not in inspect.signature(model.forward).parameters: self.skipTest("Model does not support position_ids") if (not fa_kwargs) and "position_ids" not in inspect.signature(model.forward).parameters: continue # this model doesn't accept position ids as input with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) # Drop all keys except for the minimal set. Hard to manipulate with multimodals etc inputs_dict = {k: v for k, v in inputs_dict.items() if k in ["input_ids", "attention_mask"]} # Ensure left padding, to adapt for some models if 0 in inputs_dict["attention_mask"][:, -1]: inputs_dict["attention_mask"] = inputs_dict["attention_mask"].flip(1) dummy_attention_mask = inputs_dict["attention_mask"] dummy_input_ids[~dummy_attention_mask.bool()] = config.get_text_config().pad_token_id # Main difference to other models, we need to prepare position ids according to the attention mask # as we use it to extract embeddings that rely on the correct position - naively increasing sequences do # not suffice anymore atp. The solution here calculates an increasing sequences for all 1s and puts 0s else. inputs_dict["position_ids"] = ((inputs_dict["attention_mask"] == 1).long().cumsum(dim=1) - 1) * ( inputs_dict["attention_mask"] == 1 ).long() model = ( model_class.from_pretrained( tmpdirname, dtype=torch.bfloat16, attn_implementation=attn_implementation, ) .to(torch_device) .eval() ) if fa_kwargs: # flatten features = [ {"input_ids": i[a.bool()].tolist()} for i, a in zip(dummy_input_ids, dummy_attention_mask) ] # add position_ids + fa_kwargs data_collator = DataCollatorWithFlattening(return_tensors="pt", return_flash_attn_kwargs=True) batch = data_collator(features) padfree_inputs_dict = { k: t.to(torch_device) if torch.is_tensor(t) else t for k, t in batch.items() } else: # create packed position_ids position_ids = ( torch.cat([torch.arange(length) for length in dummy_attention_mask.sum(1).tolist()]) .long() .unsqueeze(0) .to(torch_device) ) padfree_inputs_dict = { "input_ids": dummy_input_ids[dummy_attention_mask.bool()].unsqueeze(0), "position_ids": position_ids, } # We need to do simple forward without cache in order to trigger packed SDPA/flex/eager attention path res_padded = model(**inputs_dict, use_cache=False) res_padfree = model(**padfree_inputs_dict, use_cache=False) logits_padded = res_padded.logits[dummy_attention_mask.bool()] logits_padfree = res_padfree.logits[0] # acceptable numerical instability tol = torch.finfo(torch.bfloat16).eps torch.testing.assert_close(logits_padded, logits_padfree, rtol=tol, atol=tol) @require_sentencepiece @require_tokenizers @require_torch
XmodModelTest
python
jina-ai__jina
tests/unit/orchestrate/flow/flow-orchestrate/test_flow_routing.py
{ "start": 1524, "end": 2512 }
class ____(Executor): @requests def add_doc(self, docs, **kwargs): return docs @pytest.mark.parametrize('disable_reduce', [True, False]) def test_complex_flow(disable_reduce): f = ( Flow() .add(name='first', uses=SimpleAddExecutor, needs=['gateway']) .add(name='forth', uses=SimpleAddExecutor, needs=['first'], shards=2) .add( name='second_shards_needs', uses=SimpleAddExecutor, needs=['gateway'], shards=2, ) .add( name='third', uses=SimpleAddExecutor, shards=3, needs=['second_shards_needs'], ) .add( name='merger', uses=MergeDocsExecutor, needs=['forth', 'third'], disable_reduce=disable_reduce, ) ) with f: docs = f.post(on='/index', inputs=[Document(text='1')]) assert len(docs) == 6 if disable_reduce else 5
MergeDocsExecutor
python
rapidsai__cudf
python/cudf/cudf/core/series.py
{ "start": 123587, "end": 153765 }
class ____(BaseDatelikeProperties): """ Accessor object for datetimelike properties of the Series values. Returns ------- Returns a Series indexed like the original Series. Examples -------- >>> import cudf >>> import pandas as pd >>> seconds_series = cudf.Series(pd.date_range("2000-01-01", periods=3, ... freq="s")) >>> seconds_series 0 2000-01-01 00:00:00 1 2000-01-01 00:00:01 2 2000-01-01 00:00:02 dtype: datetime64[ns] >>> seconds_series.dt.second 0 0 1 1 2 2 dtype: int16 >>> hours_series = cudf.Series(pd.date_range("2000-01-01", periods=3, ... freq="h")) >>> hours_series 0 2000-01-01 00:00:00 1 2000-01-01 01:00:00 2 2000-01-01 02:00:00 dtype: datetime64[ns] >>> hours_series.dt.hour 0 0 1 1 2 2 dtype: int16 >>> weekday_series = cudf.Series(pd.date_range("2000-01-01", periods=3, ... freq="q")) >>> weekday_series 0 2000-03-31 1 2000-06-30 2 2000-09-30 dtype: datetime64[ns] >>> weekday_series.dt.weekday 0 4 1 4 2 5 dtype: int16 """ @property @_performance_tracking def year(self) -> Series: """ The year of the datetime. Examples -------- >>> import cudf >>> import pandas as pd >>> datetime_series = cudf.Series(pd.date_range("2000-01-01", ... periods=3, freq="Y")) >>> datetime_series 0 2000-12-31 1 2001-12-31 2 2002-12-31 dtype: datetime64[ns] >>> datetime_series.dt.year 0 2000 1 2001 2 2002 dtype: int16 """ return self._return_result_like_self(self.series._column.year) @property @_performance_tracking def month(self) -> Series: """ The month as January=1, December=12. Examples -------- >>> import pandas as pd >>> import cudf >>> datetime_series = cudf.Series(pd.date_range("2000-01-01", ... periods=3, freq="M")) >>> datetime_series 0 2000-01-31 1 2000-02-29 2 2000-03-31 dtype: datetime64[ns] >>> datetime_series.dt.month 0 1 1 2 2 3 dtype: int16 """ return self._return_result_like_self(self.series._column.month) @property @_performance_tracking def day(self) -> Series: """ The day of the datetime. Examples -------- >>> import pandas as pd >>> import cudf >>> datetime_series = cudf.Series(pd.date_range("2000-01-01", ... periods=3, freq="D")) >>> datetime_series 0 2000-01-01 1 2000-01-02 2 2000-01-03 dtype: datetime64[ns] >>> datetime_series.dt.day 0 1 1 2 2 3 dtype: int16 """ return self._return_result_like_self(self.series._column.day) @property @_performance_tracking def hour(self) -> Series: """ The hours of the datetime. Examples -------- >>> import pandas as pd >>> import cudf >>> datetime_series = cudf.Series(pd.date_range("2000-01-01", ... periods=3, freq="h")) >>> datetime_series 0 2000-01-01 00:00:00 1 2000-01-01 01:00:00 2 2000-01-01 02:00:00 dtype: datetime64[ns] >>> datetime_series.dt.hour 0 0 1 1 2 2 dtype: int16 """ return self._return_result_like_self(self.series._column.hour) @property @_performance_tracking def minute(self) -> Series: """ The minutes of the datetime. Examples -------- >>> import pandas as pd >>> import cudf >>> datetime_series = cudf.Series(pd.date_range("2000-01-01", ... periods=3, freq="T")) >>> datetime_series 0 2000-01-01 00:00:00 1 2000-01-01 00:01:00 2 2000-01-01 00:02:00 dtype: datetime64[ns] >>> datetime_series.dt.minute 0 0 1 1 2 2 dtype: int16 """ return self._return_result_like_self(self.series._column.minute) @property @_performance_tracking def second(self) -> Series: """ The seconds of the datetime. Examples -------- >>> import pandas as pd >>> import cudf >>> datetime_series = cudf.Series(pd.date_range("2000-01-01", ... periods=3, freq="s")) >>> datetime_series 0 2000-01-01 00:00:00 1 2000-01-01 00:00:01 2 2000-01-01 00:00:02 dtype: datetime64[ns] >>> datetime_series.dt.second 0 0 1 1 2 2 dtype: int16 """ return self._return_result_like_self(self.series._column.second) @property @_performance_tracking def microsecond(self) -> Series: """ The microseconds of the datetime. Examples -------- >>> import pandas as pd >>> import cudf >>> datetime_series = cudf.Series(pd.date_range("2000-01-01", ... periods=3, freq="us")) >>> datetime_series 0 2000-01-01 00:00:00.000000 1 2000-01-01 00:00:00.000001 2 2000-01-01 00:00:00.000002 dtype: datetime64[ns] >>> datetime_series.dt.microsecond 0 0 1 1 2 2 dtype: int32 """ micro = self.series._column.microsecond # Need to manually promote column to int32 because # pandas-matching binop behaviour requires that this # __mul__ returns an int16 column. extra = self.series._column.millisecond.astype( np.dtype(np.int32) ) * np.int32(1000) return self._return_result_like_self(micro + extra) @property @_performance_tracking def nanosecond(self) -> Series: """ The nanoseconds of the datetime. Examples -------- >>> import pandas as pd >>> import cudf >>> datetime_series = cudf.Series(pd.date_range("2000-01-01", ... periods=3, freq="ns")) >>> datetime_series 0 2000-01-01 00:00:00.000000000 1 2000-01-01 00:00:00.000000001 2 2000-01-01 00:00:00.000000002 dtype: datetime64[ns] >>> datetime_series.dt.nanosecond 0 0 1 1 2 2 dtype: int16 """ return self._return_result_like_self(self.series._column.nanosecond) @property @_performance_tracking def weekday(self) -> Series: """ The day of the week with Monday=0, Sunday=6. Examples -------- >>> import pandas as pd >>> import cudf >>> datetime_series = cudf.Series(pd.date_range('2016-12-31', ... '2017-01-08', freq='D')) >>> datetime_series 0 2016-12-31 1 2017-01-01 2 2017-01-02 3 2017-01-03 4 2017-01-04 5 2017-01-05 6 2017-01-06 7 2017-01-07 8 2017-01-08 dtype: datetime64[ns] >>> datetime_series.dt.weekday 0 5 1 6 2 0 3 1 4 2 5 3 6 4 7 5 8 6 dtype: int16 """ return self._return_result_like_self(self.series._column.weekday) @property @_performance_tracking def dayofweek(self) -> Series: """ The day of the week with Monday=0, Sunday=6. Examples -------- >>> import pandas as pd >>> import cudf >>> datetime_series = cudf.Series(pd.date_range('2016-12-31', ... '2017-01-08', freq='D')) >>> datetime_series 0 2016-12-31 1 2017-01-01 2 2017-01-02 3 2017-01-03 4 2017-01-04 5 2017-01-05 6 2017-01-06 7 2017-01-07 8 2017-01-08 dtype: datetime64[ns] >>> datetime_series.dt.dayofweek 0 5 1 6 2 0 3 1 4 2 5 3 6 4 7 5 8 6 dtype: int16 """ res = self.series._column.weekday if cudf.get_option("mode.pandas_compatible"): # Pandas returns int64 for weekday res = res.astype( get_dtype_of_same_kind( self.series._column.dtype, np.dtype("int64") ) ) return self._return_result_like_self(res) day_of_week = dayofweek @property @_performance_tracking def dayofyear(self) -> Series: """ The day of the year, from 1-365 in non-leap years and from 1-366 in leap years. Examples -------- >>> import pandas as pd >>> import cudf >>> datetime_series = cudf.Series(pd.date_range('2016-12-31', ... '2017-01-08', freq='D')) >>> datetime_series 0 2016-12-31 1 2017-01-01 2 2017-01-02 3 2017-01-03 4 2017-01-04 5 2017-01-05 6 2017-01-06 7 2017-01-07 8 2017-01-08 dtype: datetime64[ns] >>> datetime_series.dt.dayofyear 0 366 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 dtype: int16 """ return self._return_result_like_self(self.series._column.day_of_year) @property @_performance_tracking def day_of_year(self) -> Series: """ The day of the year, from 1-365 in non-leap years and from 1-366 in leap years. Examples -------- >>> import pandas as pd >>> import cudf >>> datetime_series = cudf.Series(pd.date_range('2016-12-31', ... '2017-01-08', freq='D')) >>> datetime_series 0 2016-12-31 1 2017-01-01 2 2017-01-02 3 2017-01-03 4 2017-01-04 5 2017-01-05 6 2017-01-06 7 2017-01-07 8 2017-01-08 dtype: datetime64[ns] >>> datetime_series.dt.day_of_year 0 366 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 dtype: int16 """ return self._return_result_like_self(self.series._column.day_of_year) @property @_performance_tracking def is_leap_year(self) -> Series: """ Boolean indicator if the date belongs to a leap year. A leap year is a year, which has 366 days (instead of 365) including 29th of February as an intercalary day. Leap years are years which are multiples of four with the exception of years divisible by 100 but not by 400. Returns ------- Series Booleans indicating if dates belong to a leap year. Examples -------- >>> import pandas as pd, cudf >>> s = cudf.Series( ... pd.date_range(start='2000-02-01', end='2013-02-01', freq='1Y')) >>> s 0 2000-12-31 1 2001-12-31 2 2002-12-31 3 2003-12-31 4 2004-12-31 5 2005-12-31 6 2006-12-31 7 2007-12-31 8 2008-12-31 9 2009-12-31 10 2010-12-31 11 2011-12-31 12 2012-12-31 dtype: datetime64[ns] >>> s.dt.is_leap_year 0 True 1 False 2 False 3 False 4 True 5 False 6 False 7 False 8 True 9 False 10 False 11 False 12 True dtype: bool """ return self._return_result_like_self( self.series._column.is_leap_year.fillna(False) ) @property @_performance_tracking def quarter(self) -> Series: """ Integer indicator for which quarter of the year the date belongs in. There are 4 quarters in a year. With the first quarter being from January - March, second quarter being April - June, third quarter being July - September and fourth quarter being October - December. Returns ------- Series Integer indicating which quarter the date belongs to. Examples -------- >>> import cudf >>> s = cudf.Series(["2020-05-31 08:00:00","1999-12-31 18:40:00"], ... dtype="datetime64[ms]") >>> s.dt.quarter 0 2 1 4 dtype: int8 """ return self._return_result_like_self( self.series._column.quarter.astype(np.dtype(np.int8)) ) @_performance_tracking def day_name(self, locale: str | None = None) -> Series: """ Return the day names. Currently supports English locale only. Examples -------- >>> import cudf >>> datetime_series = cudf.Series(cudf.date_range('2016-12-31', ... '2017-01-08', freq='D')) >>> datetime_series 0 2016-12-31 1 2017-01-01 2 2017-01-02 3 2017-01-03 4 2017-01-04 5 2017-01-05 6 2017-01-06 7 2017-01-07 8 2017-01-08 dtype: datetime64[ns] >>> datetime_series.dt.day_name() 0 Saturday 1 Sunday 2 Monday 3 Tuesday 4 Wednesday 5 Thursday 6 Friday 7 Saturday dtype: object """ return self._return_result_like_self( self.series._column.get_day_names(locale) ) @_performance_tracking def month_name(self, locale: str | None = None) -> Series: """ Return the month names. Currently supports English locale only. Examples -------- >>> import cudf >>> datetime_series = cudf.Series(cudf.date_range("2017-12-30", periods=6, freq='W')) >>> datetime_series 0 2017-12-30 1 2018-01-06 2 2018-01-13 3 2018-01-20 4 2018-01-27 5 2018-02-03 dtype: datetime64[ns] >>> datetime_series.dt.month_name() 0 December 1 January 2 January 3 January 4 January 5 February dtype: object """ return self._return_result_like_self( self.series._column.get_month_names(locale) ) @_performance_tracking def isocalendar(self) -> DataFrame: """ Returns a DataFrame with the year, week, and day calculated according to the ISO 8601 standard. Returns ------- DataFrame with columns year, week and day Examples -------- >>> ser = cudf.Series(pd.date_range(start="2021-07-25", ... end="2021-07-30")) >>> ser.dt.isocalendar() year week day 0 2021 29 7 1 2021 30 1 2 2021 30 2 3 2021 30 3 4 2021 30 4 5 2021 30 5 >>> ser.dt.isocalendar().week 0 29 1 30 2 30 3 30 4 30 5 30 Name: week, dtype: object >>> serIndex = cudf.to_datetime(pd.Series(["2010-01-01", pd.NaT])) >>> serIndex.dt.isocalendar() year week day 0 2009 53 5 1 <NA> <NA> <NA> >>> serIndex.dt.isocalendar().year 0 2009 1 <NA> Name: year, dtype: object """ ca = ColumnAccessor(self.series._column.isocalendar(), verify=False) return self.series._constructor_expanddim._from_data( ca, index=self.series.index, attrs=self.series.attrs ) @property @_performance_tracking def is_month_start(self) -> Series: """ Booleans indicating if dates are the first day of the month. """ return self._return_result_like_self( self.series._column.is_month_start ) @property @_performance_tracking def days_in_month(self) -> Series: """ Get the total number of days in the month that the date falls on. Returns ------- Series Integers representing the number of days in month Examples -------- >>> import pandas as pd, cudf >>> s = cudf.Series( ... pd.date_range(start='2000-08-01', end='2001-08-01', freq='1M')) >>> s 0 2000-08-31 1 2000-09-30 2 2000-10-31 3 2000-11-30 4 2000-12-31 5 2001-01-31 6 2001-02-28 7 2001-03-31 8 2001-04-30 9 2001-05-31 10 2001-06-30 11 2001-07-31 dtype: datetime64[ns] >>> s.dt.days_in_month 0 31 1 30 2 31 3 30 4 31 5 31 6 28 7 31 8 30 9 31 10 30 11 31 dtype: int16 """ res = self.series._column.days_in_month if cudf.get_option("mode.pandas_compatible"): # Pandas returns int64 for dayofweek res = res.astype( get_dtype_of_same_kind( self.series._column.dtype, np.dtype("int64") ) ) return self._return_result_like_self(res) daysinmonth = days_in_month @property def tz(self) -> str | None: return self.series._column.tz @property def freq(self) -> str | None: return self.series._column.freq @property def date(self): return self.series._column.date @property def time(self): return self.series._column.time @property def timetz(self): return self.series._column.timetz @property def unit(self) -> str: return self.series._column.time_unit @property @_performance_tracking def is_month_end(self) -> Series: """ Boolean indicator if the date is the last day of the month. Returns ------- Series Booleans indicating if dates are the last day of the month. Examples -------- >>> import pandas as pd, cudf >>> s = cudf.Series( ... pd.date_range(start='2000-08-26', end='2000-09-03', freq='1D')) >>> s 0 2000-08-26 1 2000-08-27 2 2000-08-28 3 2000-08-29 4 2000-08-30 5 2000-08-31 6 2000-09-01 7 2000-09-02 8 2000-09-03 dtype: datetime64[ns] >>> s.dt.is_month_end 0 False 1 False 2 False 3 False 4 False 5 True 6 False 7 False 8 False dtype: bool """ return self._return_result_like_self(self.series._column.is_month_end) @property @_performance_tracking def is_quarter_start(self) -> Series: """ Boolean indicator if the date is the first day of a quarter. Returns ------- Series Booleans indicating if dates are the beginning of a quarter Examples -------- >>> import pandas as pd, cudf >>> s = cudf.Series( ... pd.date_range(start='2000-09-26', end='2000-10-03', freq='1D')) >>> s 0 2000-09-26 1 2000-09-27 2 2000-09-28 3 2000-09-29 4 2000-09-30 5 2000-10-01 6 2000-10-02 7 2000-10-03 dtype: datetime64[ns] >>> s.dt.is_quarter_start 0 False 1 False 2 False 3 False 4 False 5 True 6 False 7 False dtype: bool """ return self._return_result_like_self( self.series._column.is_quarter_start ) @property @_performance_tracking def is_quarter_end(self) -> Series: """ Boolean indicator if the date is the last day of a quarter. Returns ------- Series Booleans indicating if dates are the end of a quarter Examples -------- >>> import pandas as pd, cudf >>> s = cudf.Series( ... pd.date_range(start='2000-09-26', end='2000-10-03', freq='1D')) >>> s 0 2000-09-26 1 2000-09-27 2 2000-09-28 3 2000-09-29 4 2000-09-30 5 2000-10-01 6 2000-10-02 7 2000-10-03 dtype: datetime64[ns] >>> s.dt.is_quarter_end 0 False 1 False 2 False 3 False 4 True 5 False 6 False 7 False dtype: bool """ return self._return_result_like_self( self.series._column.is_quarter_end ) @property @_performance_tracking def is_year_start(self) -> Series: """ Boolean indicator if the date is the first day of the year. Returns ------- Series Booleans indicating if dates are the first day of the year. Examples -------- >>> import pandas as pd, cudf >>> s = cudf.Series(pd.date_range("2017-12-30", periods=3)) >>> dates 0 2017-12-30 1 2017-12-31 2 2018-01-01 dtype: datetime64[ns] >>> dates.dt.is_year_start 0 False 1 False 2 True dtype: bool """ return self._return_result_like_self(self.series._column.is_year_start) @property @_performance_tracking def is_year_end(self) -> Series: """ Boolean indicator if the date is the last day of the year. Returns ------- Series Booleans indicating if dates are the last day of the year. Examples -------- >>> import pandas as pd, cudf >>> dates = cudf.Series(pd.date_range("2017-12-30", periods=3)) >>> dates 0 2017-12-30 1 2017-12-31 2 2018-01-01 dtype: datetime64[ns] >>> dates.dt.is_year_end 0 False 1 True 2 False dtype: bool """ return self._return_result_like_self(self.series._column.is_year_end) @_performance_tracking def ceil(self, freq: str) -> Series: """ Perform ceil operation on the data to the specified freq. Parameters ---------- freq : str One of ["D", "H", "T", "min", "S", "L", "ms", "U", "us", "N"]. Must be a fixed frequency like 'S' (second) not 'ME' (month end). See `frequency aliases <https://pandas.pydata.org/docs/\ user_guide/timeseries.html#timeseries-offset-aliases>`__ for more details on these aliases. Returns ------- Series Series with all timestamps rounded up to the specified frequency. The index is preserved. Examples -------- >>> import cudf >>> t = cudf.Series(["2001-01-01 00:04:45", "2001-01-01 00:04:58", ... "2001-01-01 00:05:04"], dtype="datetime64[ns]") >>> t.dt.ceil("T") 0 2001-01-01 00:05:00 1 2001-01-01 00:05:00 2 2001-01-01 00:06:00 dtype: datetime64[ns] """ return self._return_result_like_self(self.series._column.ceil(freq)) @_performance_tracking def floor(self, freq: str) -> Series: """ Perform floor operation on the data to the specified freq. Parameters ---------- freq : str One of ["D", "H", "T", "min", "S", "L", "ms", "U", "us", "N"]. Must be a fixed frequency like 'S' (second) not 'ME' (month end). See `frequency aliases <https://pandas.pydata.org/docs/\ user_guide/timeseries.html#timeseries-offset-aliases>`__ for more details on these aliases. Returns ------- Series Series with all timestamps rounded up to the specified frequency. The index is preserved. Examples -------- >>> import cudf >>> t = cudf.Series(["2001-01-01 00:04:45", "2001-01-01 00:04:58", ... "2001-01-01 00:05:04"], dtype="datetime64[ns]") >>> t.dt.floor("T") 0 2001-01-01 00:04:00 1 2001-01-01 00:04:00 2 2001-01-01 00:05:00 dtype: datetime64[ns] """ return self._return_result_like_self(self.series._column.floor(freq)) @_performance_tracking def round(self, freq: str) -> Series: """ Perform round operation on the data to the specified freq. Parameters ---------- freq : str One of ["D", "H", "T", "min", "S", "L", "ms", "U", "us", "N"]. Must be a fixed frequency like 'S' (second) not 'ME' (month end). See `frequency aliases <https://pandas.pydata.org/docs/\ user_guide/timeseries.html#timeseries-offset-aliases>`__ for more details on these aliases. Returns ------- Series Series with all timestamps rounded to the specified frequency. The index is preserved. Examples -------- >>> import cudf >>> dt_sr = cudf.Series([ ... "2001-01-01 00:04:45", ... "2001-01-01 00:04:58", ... "2001-01-01 00:05:04", ... ], dtype="datetime64[ns]") >>> dt_sr.dt.round("T") 0 2001-01-01 00:05:00 1 2001-01-01 00:05:00 2 2001-01-01 00:05:00 dtype: datetime64[ns] """ return self._return_result_like_self(self.series._column.round(freq)) @_performance_tracking def strftime(self, date_format: str, *args, **kwargs) -> Series: """ Convert to Series using specified ``date_format``. Return a Series of formatted strings specified by ``date_format``, which supports the same string format as the python standard library. Details of the string format can be found in `python string format doc <https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior>`_. Parameters ---------- date_format : str Date format string (e.g. "%Y-%m-%d"). Returns ------- Series Series of formatted strings. Examples -------- >>> import cudf >>> import pandas as pd >>> weekday_series = cudf.Series(pd.date_range("2000-01-01", periods=3, ... freq="q")) >>> weekday_series.dt.strftime("%Y-%m-%d") >>> weekday_series 0 2000-03-31 1 2000-06-30 2 2000-09-30 dtype: datetime64[ns] 0 2000-03-31 1 2000-06-30 2 2000-09-30 dtype: object >>> weekday_series.dt.strftime("%Y %d %m") 0 2000 31 03 1 2000 30 06 2 2000 30 09 dtype: object >>> weekday_series.dt.strftime("%Y / %d / %m") 0 2000 / 31 / 03 1 2000 / 30 / 06 2 2000 / 30 / 09 dtype: object .. pandas-compat:: :meth:`pandas.DatetimeIndex.strftime` The following date format identifiers are not yet supported: ``%c``, ``%x``, ``%X``. Timezone-aware datetimes will always be represented as UTC even if ``%z`` is not specified. """ if not isinstance(date_format, str): raise TypeError( f"'date_format' must be str, not {type(date_format)}" ) # TODO: Remove following validations # once https://github.com/rapidsai/cudf/issues/5991 # is implemented not_implemented_formats = { "%c", "%x", "%X", } for d_format in not_implemented_formats: if d_format in date_format: raise NotImplementedError( f"{d_format} date-time format is not " f"supported yet, Please follow this issue " f"https://github.com/rapidsai/cudf/issues/5991 " f"for tracking purposes." ) return self._return_result_like_self( self.series._column.strftime(format=date_format) ) @copy_docstring(DatetimeIndex.tz_localize) def tz_localize( self, tz: str | None, ambiguous: Literal["NaT"] = "NaT", nonexistent: Literal["NaT"] = "NaT", ) -> Series: return self._return_result_like_self( self.series._column.tz_localize(tz, ambiguous, nonexistent) ) @copy_docstring(DatetimeIndex.tz_convert) def tz_convert(self, tz: str | None) -> Series: """ Parameters ---------- tz : str Time zone for time. Corresponding timestamps would be converted to this time zone of the Datetime Array/Index. A `tz` of None will convert to UTC and remove the timezone information. """ return self._return_result_like_self( self.series._column.tz_convert(tz) )
DatetimeProperties
python
plotly__plotly.py
tests/test_core/test_figure_messages/test_plotly_relayout.py
{ "start": 101, "end": 5460 }
class ____(TestCase): def setUp(self): # Construct with mocked _send_relayout_msg method self.figure = go.Figure(layout={"xaxis": {"range": [-1, 4]}}) # Mock out the message method self.figure._send_relayout_msg = MagicMock() def test_property_assignment_toplevel(self): self.figure.layout.title.text = "hello" self.figure._send_relayout_msg.assert_called_once_with({"title.text": "hello"}) def test_property_assignment_nested(self): self.figure.layout.xaxis.title.font.family = "courier" self.figure._send_relayout_msg.assert_called_once_with( {"xaxis.title.font.family": "courier"} ) def test_property_assignment_nested_subplot2(self): # Initialize xaxis2 self.figure.layout.xaxis2 = {"range": [0, 1]} self.figure._send_relayout_msg.assert_called_once_with( {"xaxis2": {"range": [0, 1]}} ) # Reset mock and perform property assignment self.figure._send_relayout_msg = MagicMock() self.figure.layout.xaxis2.title.font.family = "courier" self.figure._send_relayout_msg.assert_called_once_with( {"xaxis2.title.font.family": "courier"} ) def test_property_assignment_nested_array(self): # Initialize images self.figure.layout.updatemenus = [ {}, go.layout.Updatemenu( buttons=[{}, {}, go.layout.updatemenu.Button(method="relayout")] ), {}, ] self.figure._send_relayout_msg.assert_called_once_with( {"updatemenus": [{}, {"buttons": [{}, {}, {"method": "relayout"}]}, {}]} ) # Reset mock and perform property assignment self.figure._send_relayout_msg = MagicMock() self.figure.layout.updatemenus[1].buttons[0].method = "restyle" self.figure._send_relayout_msg.assert_called_once_with( {"updatemenus.1.buttons.0.method": "restyle"} ) def test_property_assignment_template(self): # Initialize template object self.figure.layout.template = { "layout": {"xaxis": {"title": {"text": "x-label"}}} } self.figure._send_relayout_msg.assert_called_with( {"template": {"layout": {"xaxis": {"title": {"text": "x-label"}}}}} ) # template layout property self.figure.layout.template.layout.title.text = "Template Title" self.figure._send_relayout_msg.assert_called_with( {"template.layout.title.text": "Template Title"} ) # template add trace self.figure.layout.template.data = { "bar": [{"marker": {"color": "blue"}}, {"marker": {"color": "yellow"}}] } self.figure._send_relayout_msg.assert_called_with( { "template.data": { "bar": [ {"type": "bar", "marker": {"color": "blue"}}, {"type": "bar", "marker": {"color": "yellow"}}, ] } } ) # template set trace property self.figure.layout.template.data.bar[1].marker.opacity = 0.5 self.figure._send_relayout_msg.assert_called_with( {"template.data.bar.1.marker.opacity": 0.5} ) # Set elementdefaults property self.figure.layout.template.layout.imagedefaults.sizex = 300 self.figure._send_relayout_msg.assert_called_with( {"template.layout.imagedefaults.sizex": 300} ) def test_plotly_relayout_toplevel(self): self.figure.plotly_relayout({"title": "hello"}) self.figure._send_relayout_msg.assert_called_once_with({"title": "hello"}) def test_plotly_relayout_nested(self): self.figure.plotly_relayout({"xaxis.title.font.family": "courier"}) self.figure._send_relayout_msg.assert_called_once_with( {"xaxis.title.font.family": "courier"} ) def test_plotly_relayout_nested_subplot2(self): # Initialize xaxis2 self.figure.layout.xaxis2 = {"range": [0, 1]} self.figure._send_relayout_msg.assert_called_once_with( {"xaxis2": {"range": [0, 1]}} ) # Reset mock and perform property assignment self.figure._send_relayout_msg = MagicMock() self.figure.plotly_relayout({"xaxis2.title.font.family": "courier"}) self.figure._send_relayout_msg.assert_called_once_with( {"xaxis2.title.font.family": "courier"} ) def test_plotly_relayout_nested_array(self): # Initialize images self.figure.layout.updatemenus = [ {}, go.layout.Updatemenu( buttons=[{}, {}, go.layout.updatemenu.Button(method="relayout")] ), {}, ] self.figure._send_relayout_msg.assert_called_once_with( {"updatemenus": [{}, {"buttons": [{}, {}, {"method": "relayout"}]}, {}]} ) # Reset mock and perform property assignment self.figure._send_relayout_msg = MagicMock() self.figure.plotly_relayout({"updatemenus[1].buttons.0.method": "restyle"}) self.figure._send_relayout_msg.assert_called_once_with( {"updatemenus[1].buttons.0.method": "restyle"} )
TestRelayoutMessage
python
walkccc__LeetCode
solutions/453. Minimum Moves to Equal Array Elements/453.py
{ "start": 0, "end": 122 }
class ____: def minMoves(self, nums: list[int]) -> int: mn = min(nums) return sum(num - mn for num in nums)
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/event_log/polling_event_watcher.py
{ "start": 3877, "end": 8267 }
class ____(threading.Thread): """subclass of Thread that watches a given run_id for new Events by polling every POLLING_CADENCE. Holds a list of callbacks (_callback_fn_list) each passed in by an `Observer`. Note that the callbacks have a cursor associated; this means that the callbacks should be only executed on EventLogEntrys with an associated id >= callback.cursor Exits when `self.should_thread_exit` is set. LOCKING INFO: INVARIANTS: _callback_fn_list_lock protects _callback_fn_list """ def __init__(self, event_log_storage: EventLogStorage, run_id: str): super().__init__() self._event_log_storage = check.inst_param( event_log_storage, "event_log_storage", EventLogStorage ) self._run_id = check.str_param(run_id, "run_id") self._callback_fn_list_lock: threading.Lock = threading.Lock() self._callback_fn_list: list[CallbackAfterCursor] = [] self._should_thread_exit = threading.Event() self.name = f"sql-event-watch-run-id-{self._run_id}" @property def should_thread_exit(self) -> threading.Event: return self._should_thread_exit def add_callback(self, cursor: Optional[str], callback: Callable[[EventLogEntry, str], None]): """Observer has started watching this run. Add a callback to execute on new EventLogEntrys after the given cursor. Args: cursor (Optional[str]): event log cursor for the callback to execute callback (Callable[[EventLogEntry, str], None]): callback to update the Dagster UI """ cursor = check.opt_str_param(cursor, "cursor") callback = check.callable_param(callback, "callback") with self._callback_fn_list_lock: self._callback_fn_list.append(CallbackAfterCursor(cursor, callback)) def remove_callback(self, callback: Callable[[EventLogEntry, str], None]): """Observer has stopped watching this run; Remove a callback from the list of callbacks to execute on new EventLogEntrys. Also kill thread if no callbacks remaining (i.e. no Observers are watching this run_id) Args: callback (Callable[[EventLogEntry, str], None]): callback to remove from list of callbacks """ callback = check.callable_param(callback, "callback") with self._callback_fn_list_lock: self._callback_fn_list = [ callback_with_cursor for callback_with_cursor in self._callback_fn_list if callback_with_cursor.callback != callback ] if not self._callback_fn_list: self._should_thread_exit.set() def run(self) -> None: """Polling function to update Observers with EventLogEntrys from Event Log DB. Wakes every POLLING_CADENCE & 1. executes a SELECT query to get new EventLogEntrys 2. fires each callback (taking into account the callback.cursor) on the new EventLogEntrys Uses max_index_so_far as a cursor in the DB to make sure that only new records are retrieved. """ cursor = None wait_time = INIT_POLL_PERIOD chunk_limit = int(os.getenv("DAGSTER_POLLING_EVENT_WATCHER_BATCH_SIZE", "1000")) while not self._should_thread_exit.wait(wait_time): conn = self._event_log_storage.get_records_for_run( self._run_id, cursor=cursor, limit=chunk_limit, ) cursor = conn.cursor for event_record in conn.records: with self._callback_fn_list_lock: for callback_with_cursor in self._callback_fn_list: if ( callback_with_cursor.cursor is None or EventLogCursor.parse(callback_with_cursor.cursor).storage_id() < event_record.storage_id ): callback_with_cursor.callback( event_record.event_log_entry, str(EventLogCursor.from_storage_id(event_record.storage_id)), ) wait_time = INIT_POLL_PERIOD if conn.records else min(wait_time * 2, MAX_POLL_PERIOD)
SqlPollingRunIdEventWatcherThread
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 299652, "end": 301373 }
class ____(Response): """ Response of tasks.edit endpoint. :param updated: Number of tasks updated (0 or 1) :type updated: int :param fields: Updated fields names and values :type fields: dict """ _service = "tasks" _action = "edit" _version = "2.23" _schema = { "definitions": {}, "properties": { "fields": { "additionalProperties": True, "description": "Updated fields names and values", "type": ["object", "null"], }, "updated": { "description": "Number of tasks updated (0 or 1)", "enum": [0, 1], "type": ["integer", "null"], }, }, "type": "object", } def __init__(self, updated=None, fields=None, **kwargs): super(EditResponse, self).__init__(**kwargs) self.updated = updated self.fields = fields @schema_property("updated") def updated(self): return self._property_updated @updated.setter def updated(self, value): if value is None: self._property_updated = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "updated", six.integer_types) self._property_updated = value @schema_property("fields") def fields(self): return self._property_fields @fields.setter def fields(self, value): if value is None: self._property_fields = None return self.assert_isinstance(value, "fields", (dict,)) self._property_fields = value
EditResponse