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
ray-project__ray
python/ray/dashboard/modules/aggregator/tests/test_ray_event_publisher.py
{ "start": 1484, "end": 5217 }
class ____: """Test the main RayEventsPublisher functionality.""" @pytest.mark.asyncio async def test_publish_with_retries_failure_then_success(self, base_kwargs): """Test publish that fails then succeeds.""" call_count = {"count": 0} # fail the first publish call but succeed on retry def side_effect(batch): call_count["count"] += 1 if call_count["count"] == 1: return PublishStats(False, 0, 0) return PublishStats(True, 1, 0) client = MockPublisherClient(side_effect=side_effect) event_buffer = MultiConsumerEventBuffer(max_size=10, max_batch_size=10) publisher = RayEventPublisher( name=base_kwargs["name"] + str(uuid.uuid4()), publish_client=client, event_buffer=event_buffer, max_retries=base_kwargs["max_retries"], initial_backoff=base_kwargs["initial_backoff"], max_backoff=base_kwargs["max_backoff"], jitter_ratio=base_kwargs["jitter_ratio"], ) task = asyncio.create_task(publisher.run_forever()) try: # ensure consumer is registered assert await publisher.wait_until_running(2.0) # Enqueue one event into buffer e = events_base_event_pb2.RayEvent( event_id=b"1", source_type=events_base_event_pb2.RayEvent.SourceType.CORE_WORKER, event_type=events_base_event_pb2.RayEvent.EventType.TASK_DEFINITION_EVENT, timestamp=Timestamp(seconds=123, nanos=0), severity=events_base_event_pb2.RayEvent.Severity.INFO, message="hello", ) await event_buffer.add_event(e) # wait for two publish attempts (failure then success) await async_wait_for_condition(lambda: len(client.publish_calls) == 2) finally: task.cancel() with pytest.raises(asyncio.CancelledError): await task @pytest.mark.asyncio async def test_publish_with_retries_max_retries_exceeded(self, base_kwargs): """Test publish that fails all retries and records failed events.""" client = MockPublisherClient( side_effect=lambda batch: PublishStats(False, 0, 0) ) event_buffer = MultiConsumerEventBuffer(max_size=10, max_batch_size=10) publisher = RayEventPublisher( name=base_kwargs["name"] + str(uuid.uuid4()), publish_client=client, event_buffer=event_buffer, max_retries=2, # override to finite retries initial_backoff=0, max_backoff=0, jitter_ratio=0, ) task = asyncio.create_task(publisher.run_forever()) try: # ensure consumer is registered assert await publisher.wait_until_running(2.0) e = events_base_event_pb2.RayEvent( event_id=b"1", source_type=events_base_event_pb2.RayEvent.SourceType.CORE_WORKER, event_type=events_base_event_pb2.RayEvent.EventType.TASK_DEFINITION_EVENT, timestamp=Timestamp(seconds=123, nanos=0), severity=events_base_event_pb2.RayEvent.Severity.INFO, message="hello", ) await event_buffer.add_event(e) # wait for publish attempts (initial + 2 retries) await async_wait_for_condition(lambda: len(client.publish_calls) == 3) assert len(client.publish_calls) == 3 finally: task.cancel() with pytest.raises(asyncio.CancelledError): await task
TestRayEventPublisher
python
pandas-dev__pandas
pandas/tests/tools/test_to_datetime.py
{ "start": 1627, "end": 19341 }
class ____: def test_to_datetime_readonly(self, writable): # GH#34857 arr = np.array([], dtype=object) arr.setflags(write=writable) result = to_datetime(arr) expected = to_datetime([]) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "format, expected", [ [ "%d/%m/%Y", [Timestamp("20000101"), Timestamp("20000201"), Timestamp("20000301")], ], [ "%m/%d/%Y", [Timestamp("20000101"), Timestamp("20000102"), Timestamp("20000103")], ], ], ) def test_to_datetime_format(self, cache, index_or_series, format, expected): values = index_or_series(["1/1/2000", "1/2/2000", "1/3/2000"]) result = to_datetime(values, format=format, cache=cache) expected = index_or_series(expected) tm.assert_equal(result, expected) @pytest.mark.parametrize( "arg, expected, format", [ ["1/1/2000", "20000101", "%d/%m/%Y"], ["1/1/2000", "20000101", "%m/%d/%Y"], ["1/2/2000", "20000201", "%d/%m/%Y"], ["1/2/2000", "20000102", "%m/%d/%Y"], ["1/3/2000", "20000301", "%d/%m/%Y"], ["1/3/2000", "20000103", "%m/%d/%Y"], ], ) def test_to_datetime_format_scalar(self, cache, arg, expected, format): result = to_datetime(arg, format=format, cache=cache) expected = Timestamp(expected) assert result == expected def test_to_datetime_format_YYYYMMDD(self, cache): ser = Series([19801222, 19801222] + [19810105] * 5) expected = Series([Timestamp(x) for x in ser.apply(str)]) result = to_datetime(ser, format="%Y%m%d", cache=cache) tm.assert_series_equal(result, expected) result = to_datetime(ser.apply(str), format="%Y%m%d", cache=cache) tm.assert_series_equal(result, expected) def test_to_datetime_format_YYYYMMDD_with_nat(self, cache): # Explicit cast to float to explicit cast when setting np.nan ser = Series([19801222, 19801222] + [19810105] * 5, dtype="float") # with NaT expected = Series( [Timestamp("19801222"), Timestamp("19801222")] + [Timestamp("19810105")] * 5, dtype="M8[us]", ) expected[2] = np.nan ser[2] = np.nan result = to_datetime(ser, format="%Y%m%d", cache=cache) tm.assert_series_equal(result, expected) # string with NaT ser2 = ser.apply(str) ser2[2] = "nat" with pytest.raises( ValueError, match=( 'unconverted data remains when parsing with format "%Y%m%d": ".0". ' ), ): # https://github.com/pandas-dev/pandas/issues/50051 to_datetime(ser2, format="%Y%m%d", cache=cache) def test_to_datetime_format_YYYYMM_with_nat(self, cache): # https://github.com/pandas-dev/pandas/issues/50237 # Explicit cast to float to explicit cast when setting np.nan ser = Series([198012, 198012] + [198101] * 5, dtype="float") expected = Series( [Timestamp("19801201"), Timestamp("19801201")] + [Timestamp("19810101")] * 5, dtype="M8[us]", ) expected[2] = np.nan ser[2] = np.nan result = to_datetime(ser, format="%Y%m", cache=cache) tm.assert_series_equal(result, expected) def test_to_datetime_format_YYYYMMDD_oob_for_ns(self, cache): # coercion # GH 7930, GH 14487 ser = Series([20121231, 20141231, 99991231]) result = to_datetime(ser, format="%Y%m%d", errors="raise", cache=cache) expected = Series( np.array(["2012-12-31", "2014-12-31", "9999-12-31"], dtype="M8[s]"), dtype="M8[us]", ) tm.assert_series_equal(result, expected) def test_to_datetime_format_YYYYMMDD_coercion(self, cache): # coercion # GH 7930 ser = Series([20121231, 20141231, 999999999999999999999999999991231]) result = to_datetime(ser, format="%Y%m%d", errors="coerce", cache=cache) expected = Series(["20121231", "20141231", "NaT"], dtype="M8[us]") tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "input_s", [ # Null values with Strings ["19801222", "20010112", None], ["19801222", "20010112", np.nan], ["19801222", "20010112", NaT], ["19801222", "20010112", "NaT"], # Null values with Integers [19801222, 20010112, None], [19801222, 20010112, np.nan], [19801222, 20010112, NaT], [19801222, 20010112, "NaT"], ], ) def test_to_datetime_format_YYYYMMDD_with_none(self, input_s): # GH 30011 # format='%Y%m%d' # with None expected = Series([Timestamp("19801222"), Timestamp("20010112"), NaT]) result = Series(to_datetime(input_s, format="%Y%m%d")) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "input_s, expected", [ # NaN before strings with invalid date values [ ["19801222", np.nan, "20010012", "10019999"], [Timestamp("19801222"), np.nan, np.nan, np.nan], ], # NaN after strings with invalid date values [ ["19801222", "20010012", "10019999", np.nan], [Timestamp("19801222"), np.nan, np.nan, np.nan], ], # NaN before integers with invalid date values [ [20190813, np.nan, 20010012, 20019999], [Timestamp("20190813"), np.nan, np.nan, np.nan], ], # NaN after integers with invalid date values [ [20190813, 20010012, np.nan, 20019999], [Timestamp("20190813"), np.nan, np.nan, np.nan], ], ], ) def test_to_datetime_format_YYYYMMDD_overflow(self, input_s, expected): # GH 25512 # format='%Y%m%d', errors='coerce' input_s = Series(input_s) result = to_datetime(input_s, format="%Y%m%d", errors="coerce") expected = Series(expected) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "data, format, expected", [ ([pd.NA], "%Y%m%d%H%M%S", ["NaT"]), ([pd.NA], None, ["NaT"]), ( [pd.NA, "20210202202020"], "%Y%m%d%H%M%S", ["NaT", "2021-02-02 20:20:20"], ), (["201010", pd.NA], "%y%m%d", ["2020-10-10", "NaT"]), (["201010", pd.NA], "%d%m%y", ["2010-10-20", "NaT"]), ([None, np.nan, pd.NA], None, ["NaT", "NaT", "NaT"]), ([None, np.nan, pd.NA], "%Y%m%d", ["NaT", "NaT", "NaT"]), ], ) def test_to_datetime_with_NA(self, data, format, expected): # GH#42957 result = to_datetime(data, format=format) expected = DatetimeIndex(expected) tm.assert_index_equal(result, expected) def test_to_datetime_with_NA_with_warning(self): # GH#42957 result = to_datetime(["201010", pd.NA]) expected = DatetimeIndex(["2010-10-20", "NaT"]) tm.assert_index_equal(result, expected) def test_to_datetime_format_integer(self, cache): # GH 10178 ser = Series([2000, 2001, 2002]) expected = Series([Timestamp(x) for x in ser.apply(str)]) result = to_datetime(ser, format="%Y", cache=cache) tm.assert_series_equal(result, expected) ser = Series([200001, 200105, 200206]) expected = Series([Timestamp(x[:4] + "-" + x[4:]) for x in ser.apply(str)]) result = to_datetime(ser, format="%Y%m", cache=cache) tm.assert_series_equal(result, expected) def test_to_datetime_format_microsecond(self, cache): month_abbr = calendar.month_abbr[4] val = f"01-{month_abbr}-2011 00:00:01.978" format = "%d-%b-%Y %H:%M:%S.%f" result = to_datetime(val, format=format, cache=cache) exp = datetime.strptime(val, format) assert result == exp @pytest.mark.parametrize( "value, format, dt", [ ["01/10/2010 15:20", "%m/%d/%Y %H:%M", Timestamp("2010-01-10 15:20")], ["01/10/2010 05:43", "%m/%d/%Y %I:%M", Timestamp("2010-01-10 05:43")], [ "01/10/2010 13:56:01", "%m/%d/%Y %H:%M:%S", Timestamp("2010-01-10 13:56:01"), ], # The 3 tests below are locale-dependent. # They pass, except when the machine locale is zh_CN or it_IT . pytest.param( "01/10/2010 08:14 PM", "%m/%d/%Y %I:%M %p", Timestamp("2010-01-10 20:14"), marks=pytest.mark.xfail( locale.getlocale()[0] in ("zh_CN", "it_IT"), reason="fail on a CI build with LC_ALL=zh_CN.utf8/it_IT.utf8", strict=False, ), ), pytest.param( "01/10/2010 07:40 AM", "%m/%d/%Y %I:%M %p", Timestamp("2010-01-10 07:40"), marks=pytest.mark.xfail( locale.getlocale()[0] in ("zh_CN", "it_IT"), reason="fail on a CI build with LC_ALL=zh_CN.utf8/it_IT.utf8", strict=False, ), ), pytest.param( "01/10/2010 09:12:56 AM", "%m/%d/%Y %I:%M:%S %p", Timestamp("2010-01-10 09:12:56"), marks=pytest.mark.xfail( locale.getlocale()[0] in ("zh_CN", "it_IT"), reason="fail on a CI build with LC_ALL=zh_CN.utf8/it_IT.utf8", strict=False, ), ), ], ) def test_to_datetime_format_time(self, cache, value, format, dt): assert to_datetime(value, format=format, cache=cache) == dt @td.skip_if_not_us_locale def test_to_datetime_with_non_exact(self, cache): # GH 10834 # 8904 # exact kw ser = Series( ["19MAY11", "foobar19MAY11", "19MAY11:00:00:00", "19MAY11 00:00:00Z"] ) result = to_datetime(ser, format="%d%b%y", exact=False, cache=cache) expected = to_datetime( ser.str.extract(r"(\d+\w+\d+)", expand=False), format="%d%b%y", cache=cache ) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "format, expected", [ ("%Y-%m-%d", Timestamp(2000, 1, 3)), ("%Y-%d-%m", Timestamp(2000, 3, 1)), ("%Y-%m-%d %H", Timestamp(2000, 1, 3, 12)), ("%Y-%d-%m %H", Timestamp(2000, 3, 1, 12)), ("%Y-%m-%d %H:%M", Timestamp(2000, 1, 3, 12, 34)), ("%Y-%d-%m %H:%M", Timestamp(2000, 3, 1, 12, 34)), ("%Y-%m-%d %H:%M:%S", Timestamp(2000, 1, 3, 12, 34, 56)), ("%Y-%d-%m %H:%M:%S", Timestamp(2000, 3, 1, 12, 34, 56)), ("%Y-%m-%d %H:%M:%S.%f", Timestamp(2000, 1, 3, 12, 34, 56, 123456)), ("%Y-%d-%m %H:%M:%S.%f", Timestamp(2000, 3, 1, 12, 34, 56, 123456)), ( "%Y-%m-%d %H:%M:%S.%f%z", Timestamp(2000, 1, 3, 12, 34, 56, 123456, tz="UTC+01:00"), ), ( "%Y-%d-%m %H:%M:%S.%f%z", Timestamp(2000, 3, 1, 12, 34, 56, 123456, tz="UTC+01:00"), ), ], ) def test_non_exact_doesnt_parse_whole_string(self, cache, format, expected): # https://github.com/pandas-dev/pandas/issues/50412 # the formats alternate between ISO8601 and non-ISO8601 to check both paths result = to_datetime( "2000-01-03 12:34:56.123456+01:00", format=format, exact=False ) assert result == expected @pytest.mark.parametrize( "arg", [ "2012-01-01 09:00:00.000000001", "2012-01-01 09:00:00.000001", "2012-01-01 09:00:00.001", "2012-01-01 09:00:00.001000", "2012-01-01 09:00:00.001000000", ], ) def test_parse_nanoseconds_with_formula(self, cache, arg): # GH8989 # truncating the nanoseconds when a format was provided expected = to_datetime(arg, cache=cache) result = to_datetime(arg, format="%Y-%m-%d %H:%M:%S.%f", cache=cache) assert result == expected @pytest.mark.parametrize( "value,fmt,expected", [ ["2009324", "%Y%W%w", "2009-08-13"], ["2013020", "%Y%U%w", "2013-01-13"], ], ) def test_to_datetime_format_weeks(self, value, fmt, expected, cache): assert to_datetime(value, format=fmt, cache=cache) == Timestamp(expected) @pytest.mark.parametrize( "fmt,dates,expected_dates", [ [ "%Y-%m-%d %H:%M:%S %Z", ["2010-01-01 12:00:00 UTC"] * 2, [Timestamp("2010-01-01 12:00:00", tz="UTC")] * 2, ], [ "%Y-%m-%d %H:%M:%S%z", ["2010-01-01 12:00:00+0100"] * 2, [ Timestamp( "2010-01-01 12:00:00", tzinfo=timezone(timedelta(minutes=60)) ) ] * 2, ], [ "%Y-%m-%d %H:%M:%S %z", ["2010-01-01 12:00:00 +0100"] * 2, [ Timestamp( "2010-01-01 12:00:00", tzinfo=timezone(timedelta(minutes=60)) ) ] * 2, ], [ "%Y-%m-%d %H:%M:%S %z", ["2010-01-01 12:00:00 Z", "2010-01-01 12:00:00 Z"], [ Timestamp( "2010-01-01 12:00:00", tzinfo=timezone(timedelta(minutes=0)) ), Timestamp( "2010-01-01 12:00:00", tzinfo=timezone(timedelta(minutes=0)) ), ], ], ], ) def test_to_datetime_parse_tzname_or_tzoffset(self, fmt, dates, expected_dates): # GH 13486 result = to_datetime(dates, format=fmt) expected = Index(expected_dates) tm.assert_equal(result, expected) @pytest.mark.parametrize( "fmt,dates,expected_dates", [ [ "%Y-%m-%d %H:%M:%S %Z", [ "2010-01-01 12:00:00 UTC", "2010-01-01 12:00:00 GMT", "2010-01-01 12:00:00 US/Pacific", ], [ Timestamp("2010-01-01 12:00:00", tz="UTC"), Timestamp("2010-01-01 12:00:00", tz="GMT"), Timestamp("2010-01-01 12:00:00", tz="US/Pacific"), ], ], [ "%Y-%m-%d %H:%M:%S %z", ["2010-01-01 12:00:00 +0100", "2010-01-01 12:00:00 -0100"], [ Timestamp( "2010-01-01 12:00:00", tzinfo=timezone(timedelta(minutes=60)) ), Timestamp( "2010-01-01 12:00:00", tzinfo=timezone(timedelta(minutes=-60)) ), ], ], ], ) def test_to_datetime_parse_tzname_or_tzoffset_utc_false_removed( self, fmt, dates, expected_dates ): # GH#13486, GH#50887, GH#57275 msg = "Mixed timezones detected. Pass utc=True in to_datetime" with pytest.raises(ValueError, match=msg): to_datetime(dates, format=fmt) def test_to_datetime_parse_tzname_or_tzoffset_different_tz_to_utc(self): # GH 32792 dates = [ "2010-01-01 12:00:00 +0100", "2010-01-01 12:00:00 -0100", "2010-01-01 12:00:00 +0300", "2010-01-01 12:00:00 +0400", ] expected_dates = [ "2010-01-01 11:00:00+00:00", "2010-01-01 13:00:00+00:00", "2010-01-01 09:00:00+00:00", "2010-01-01 08:00:00+00:00", ] fmt = "%Y-%m-%d %H:%M:%S %z" result = to_datetime(dates, format=fmt, utc=True) expected = DatetimeIndex(expected_dates) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( "offset", ["+0", "-1foo", "UTCbar", ":10", "+01:000:01", ""] ) def test_to_datetime_parse_timezone_malformed(self, offset): fmt = "%Y-%m-%d %H:%M:%S %z" date = "2010-01-01 12:00:00 " + offset msg = "|".join( [ r'^time data ".*" doesn\'t match format ".*". ' f"{PARSING_ERR_MSG}$", r'^unconverted data remains when parsing with format ".*": ".*". ' f"{PARSING_ERR_MSG}$", ] ) with pytest.raises(ValueError, match=msg): to_datetime([date], format=fmt) def test_to_datetime_parse_timezone_keeps_name(self): # GH 21697 fmt = "%Y-%m-%d %H:%M:%S %z" arg = Index(["2010-01-01 12:00:00 Z"], name="foo") result = to_datetime(arg, format=fmt) expected = DatetimeIndex(["2010-01-01 12:00:00"], tz="UTC", name="foo") tm.assert_index_equal(result, expected)
TestTimeConversionFormats
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 270141, "end": 270631 }
class ____(sgqlc.types.Input): """Ways in which lists of git refs can be ordered upon return.""" __schema__ = github_schema __field_names__ = ("field", "direction") field = sgqlc.types.Field(sgqlc.types.non_null(RefOrderField), graphql_name="field") """The field in which to order refs by.""" direction = sgqlc.types.Field(sgqlc.types.non_null(OrderDirection), graphql_name="direction") """The direction in which to order refs by the specified field."""
RefOrder
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/tests/test_rl_trainer.py
{ "start": 8459, "end": 9749 }
class ____(unittest.TestCase): def test_warning_group_reward(self): with self.assertLogs("mlagents.trainers", level="WARN") as cm: rl_trainer = create_rl_trainer() # This one should warn trajectory = mb.make_fake_trajectory( length=10, observation_specs=create_observation_specs_with_shapes([(1,)]), max_step_complete=True, action_spec=ActionSpec.create_discrete((2,)), group_reward=1.0, ) buff = trajectory.to_agentbuffer() rl_trainer._warn_if_group_reward(buff) assert len(cm.output) > 0 len_of_first_warning = len(cm.output) rl_trainer = create_rl_trainer() # This one shouldn't trajectory = mb.make_fake_trajectory( length=10, observation_specs=create_observation_specs_with_shapes([(1,)]), max_step_complete=True, action_spec=ActionSpec.create_discrete((2,)), ) buff = trajectory.to_agentbuffer() rl_trainer._warn_if_group_reward(buff) # Make sure warnings don't get bigger assert len(cm.output) == len_of_first_warning
RLTrainerWarningTest
python
ray-project__ray
python/ray/experimental/channel/nccl_group.py
{ "start": 612, "end": 13562 }
class ____(Communicator): """ Represents an actor's NCCL communicator. This is the default NCCL communicator to be used in Compiled Graph if a custom communicator is not provided. This class is not thread-safe. """ def __init__( self, world_size: int, comm_id: tuple, rank: Optional[int], actor_handles: List["ray.actor.ActorHandle"], cuda_stream: Optional["torch.cuda.Stream"], use_communication_streams: bool = False, ): """ Initialize a NCCL communicator that can be used to communicate p2p with other GPU actors. This method blocks until the same call has been made on all other actors in the group, with the same arguments for world_size and comm_id. NOTE: A concurrent NCCL group can coexist with this one but using the two groups concurrently on different CUDA streams may cause deadlock. See https://docs.nvidia.com/deeplearning/nccl/user-guide/docs/usage/communicators.html #using-multiple-nccl-communicators-concurrently. If the user can guarantee that all involved actors execute the same ops in the same order, then the other NCCL group should use the given `cuda_stream`, and there will not be a concurrency issue. Otherwise, the other stream needs to synchronize with the given `cuda_stream` before and after it launches NCCL ops, e.g., at the beginning and end of a DAG task. Args: world_size: The number of participating actors/devices. comm_id: A unique communicator ID returned by cupy.cuda.nccl.get_unique_id(). rank: The rank of this actor. If None, then the caller is not a participant of the NCCL group. actor_handles: A list of actor handles, in rank order. cuda_stream: A raw CUDA stream to dispatch NCCL ops to. If rank is specified, then this must be specified too. use_communication_streams: Whether to use dedicated send and recv streams for communication. If True, communication and computation can be overlapped to improve performance. """ self._world_size = world_size self._rank: Optional[int] = rank self.nccl_util: Optional[ModuleType] = None self._actor_handles = actor_handles self._use_communication_streams = use_communication_streams if rank is not None: assert ray.get_gpu_ids(), "NCCL actor has no GPUs assigned" assert cuda_stream is not None, "NCCL actor must specify cuda_stream" expected_rank = self.get_rank(ray.get_runtime_context().current_actor) assert ( rank == expected_rank ), f"NCCL actor's rank {rank} does not match expected rank {expected_rank}" from ray.util.collective.collective_group import nccl_util self.nccl_util = nccl_util self._comm = self.nccl_util.NcclCommunicator(world_size, comm_id, rank) else: # Driver does not have a rank. self._comm = None self._cuda_stream: Optional["torch.cuda.Stream"] = None self._send_stream: Optional["torch.cuda.Stream"] = None self._recv_stream: Optional["torch.cuda.Stream"] = None if cuda_stream is not None: assert rank is not None, "NCCL actor has no rank assigned" self._cuda_stream = cuda_stream if use_communication_streams: import torch # TODO(swang): Allow default device to be overridden. device = AcceleratorContext.get().get_accelerator_devices()[0] self._send_stream = torch.cuda.Stream(device=device) self._recv_stream = torch.cuda.Stream(device=device) else: self._send_stream = self._cuda_stream self._recv_stream = self._cuda_stream self._closed = False def initialize(self, rank: int) -> None: # No additional initialization is needed. pass def get_actor_handles(self) -> List["ray.actor.ActorHandle"]: return self._actor_handles def get_rank(self, actor: ray.actor.ActorHandle) -> int: """ Return the given actor's rank in the NCCL communicator. Args: actor: The actor handle to look up. """ actor_ids = [a._ray_actor_id for a in self._actor_handles] try: rank = actor_ids.index(actor._ray_actor_id) except ValueError: raise ValueError("Actor is not in the NCCL group.") return rank def get_self_rank(self) -> Optional[int]: """ Return this actor's rank. """ return self._rank def get_world_size(self) -> int: """ Return the number of ranks in the NCCL communicator. """ return self._world_size def send(self, buf: "torch.Tensor", peer_rank: int) -> None: """ Send a torch.Tensor to a peer. This returns when the send kernel has been queued, but the kernel may not have completed. Therefore, the caller should ensure that there are no concurrent writes to the sent `buf` until the send has finished. That is, either all writes should be submitted on the current stream (self._cuda_stream) or, if on a different stream, that stream should synchronize with the current stream. Args: buf: The torch.Tensor to send. It should already be on this actor's default device. peer_rank: The rank of the actor to send to. """ if self._closed: raise RayChannelError("NCCL group has been destroyed.") if self._use_communication_streams: # We observed that if all recv/compute/send operations run on GPU, # since there is no synchronization, the CPU execution loop may be # far ahead of the GPU operations and lead to runtime failures. # To avoid that, we synchronize on the send stream. # TODO(rui): find a better approach self._send_stream.synchronize() # TODO(swang): Handle send/recv async NCCL errors such as network # failures. self._comm.send( self.nccl_util.get_tensor_ptr(buf), buf.numel(), self.nccl_util.get_nccl_tensor_dtype(buf), peer_rank, self._send_stream.cuda_stream, ) def recv( self, shape: Tuple[int], dtype: "torch.dtype", peer_rank: int, allocator=Optional[TorchTensorAllocator], ) -> "torch.Tensor": """ Receive a torch.Tensor from a peer and synchronize the current stream. After this call returns, the receive buffer is safe to read from from any stream. An RayChannelError will be raised if an error occurred (e.g., remote actor died), and the buffer is not safe to read. Args: buf: The torch.Tensor to receive into. This buffer is safe to read peer_rank: The rank of the actor to receive from. """ if self._closed: raise RayChannelError("NCCL group has been destroyed.") assert allocator is not None, "NCCL group requires a tensor allocator" buf = allocator(shape, dtype) if self._use_communication_streams: # We observed that if all recv/compute/send operations run on GPU, # since there is no synchronization, the CPU execution loop may be # far ahead of the GPU operations and lead to runtime failures. # To avoid that, we synchronize on the recv stream. # TODO(rui): find a better approach self._recv_stream.synchronize() self._comm.recv( self.nccl_util.get_tensor_ptr(buf), buf.numel(), self.nccl_util.get_nccl_tensor_dtype(buf), peer_rank, self._recv_stream.cuda_stream, ) else: self._comm.recv( self.nccl_util.get_tensor_ptr(buf), buf.numel(), self.nccl_util.get_nccl_tensor_dtype(buf), peer_rank, self._recv_stream.cuda_stream, ) # Buffer values are undefined if NCCL ops are aborted. Therefore, we # need to synchronize here and check that the channel is still open to # ensure that the receive buffer is valid. # TODO(swang): Avoid CUDA synchronization. self._cuda_stream.synchronize() if self._closed: raise RayChannelError("NCCL group has been destroyed.") return buf def _exec_collective( self, send_buf: "torch.Tensor", recv_buf: "torch.Tensor", operation: "Callable[..., None]", *operation_args, ): if self._closed: raise RayChannelError("NCCL group has been destroyed.") assert send_buf.dtype == recv_buf.dtype, ( "Ray Compiled Graph derived the dtype of recv_buf from send_buf, " "so send_buf and recv_buf must have the same dtype. " "If you see this error, please file an issue at Ray repository." ) operation(*operation_args) # Buffer values are undefined if NCCL ops are aborted. Therefore, we # need to synchronize here and check that the channel is still open to # ensure that the receive buffer is valid. # TODO(swang): Avoid CUDA synchronization. # TODO(wxdeng): This synchronize will be optional after merging the unify PR. self._cuda_stream.synchronize() if self._closed: raise RayChannelError( "NCCL group has been destroyed during allreduce operation. " "There may be a dtype mismatch between input tensors from " "different ranks." ) def allgather( self, send_buf: "torch.Tensor", recv_buf: "torch.Tensor", ): operation_args = [ self.nccl_util.get_tensor_ptr(send_buf), self.nccl_util.get_tensor_ptr(recv_buf), send_buf.numel(), self.nccl_util.get_nccl_tensor_dtype(send_buf), self._cuda_stream.cuda_stream, ] self._exec_collective( send_buf, recv_buf, self._comm.allGather, *operation_args, ) def allreduce( self, send_buf: "torch.Tensor", recv_buf: "torch.Tensor", op: ReduceOp = ReduceOp.SUM, ): operation_args = [ self.nccl_util.get_tensor_ptr(send_buf), self.nccl_util.get_tensor_ptr(recv_buf), send_buf.numel(), self.nccl_util.get_nccl_tensor_dtype(send_buf), op.value, self._cuda_stream.cuda_stream, ] self._exec_collective( send_buf, recv_buf, self._comm.allReduce, *operation_args, ) def reducescatter( self, send_buf: "torch.Tensor", recv_buf: "torch.Tensor", op: ReduceOp = ReduceOp.SUM, ): operation_args = [ self.nccl_util.get_tensor_ptr(send_buf), self.nccl_util.get_tensor_ptr(recv_buf), recv_buf.numel(), self.nccl_util.get_nccl_tensor_dtype(send_buf), op.value, self._cuda_stream.cuda_stream, ] self._exec_collective( send_buf, recv_buf, self._comm.reduceScatter, *operation_args, ) @property def recv_stream(self): import torch return torch.cuda.StreamContext(self._recv_stream) @property def send_stream(self): import torch return torch.cuda.StreamContext(self._send_stream) def destroy(self) -> None: """ Destroy the NCCL group. """ if self._closed: return self._closed = True if self._comm is not None: logger.info( "Destructing NCCL group on actor: " f"{ray.get_runtime_context().current_actor}" ) # Abort *after* setting the _closed flag. This ensures that NCCL # ops that were blocked on a remote peer will see that the _closed # flag is True when they exit from the abort. self._comm.abort() self._comm.destroy() def get_transport_name(self) -> str: return "accelerator" @classmethod def generate_communicator_id(cls) -> str: from cupy.cuda import nccl return nccl.get_unique_id()
_NcclGroup
python
scrapy__scrapy
tests/test_scheduler.py
{ "start": 1496, "end": 1559 }
class ____(NamedTuple): downloader: MockDownloader
MockEngine
python
django__django
tests/postgres_tests/models.py
{ "start": 3788, "end": 4367 }
class ____(PostgreSQLModel): ints = IntegerRangeField(blank=True, null=True, db_default=(5, 10)) bigints = BigIntegerRangeField(blank=True, null=True) decimals = DecimalRangeField(blank=True, null=True) timestamps = DateTimeRangeField(blank=True, null=True) timestamps_inner = DateTimeRangeField(blank=True, null=True) timestamps_closed_bounds = DateTimeRangeField( blank=True, null=True, default_bounds="[]", ) dates = DateRangeField(blank=True, null=True) dates_inner = DateRangeField(blank=True, null=True)
RangesModel
python
aio-libs__aiohttp
aiohttp/web_exceptions.py
{ "start": 7096, "end": 7161 }
class ____(HTTPClientError): status_code = 401
HTTPUnauthorized
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/recursiveTypeAlias9.py
{ "start": 244, "end": 497 }
class ____(Generic[A]): val: A a: JSON = {"a": "b"} b: JSON = "a" c: Example[JSON] = Example(a) d: Example[JSON] = Example("a") e: Example[JSON] = Example({}) f: Example[JSON] = Example({"a": "b"}) g: Example[JSON] = Example({"a": {"a": "b"}})
Example
python
numba__numba
numba/core/types/misc.py
{ "start": 4427, "end": 4655 }
class ____(CPointer): """ Type class for pointers which aren't guaranteed to last long - e.g. stack-allocated slots. The data model serializes such pointers by copying the data pointed to. """
EphemeralPointer
python
pytorch__pytorch
torch/autograd/grad_mode.py
{ "start": 11134, "end": 12471 }
class ____(_DecoratorContextManager): r"""Context-manager that sets whether or not to always enable view-replay in autograd. ``set_view_replay_enabled`` will enable or disable view-replay based on its argument :attr:`mode`. It can be used as a context-manager or as a function. This context manager is thread local; it will not affect computation in other threads. When a tensor view is mutated, the autograd engine needs to decide whether or not to regenerate the "updated view" by either replaying the chain of views from the updated base, or with a single call to as_strided. If set_view_replay_enabled is set to True, then autograd will always use view replay. Otherwise, it will fall back to its existing logic. Args: mode (bool): Flag whether to enable view-replay (``True``), or disable (``False``). """ def __init__(self, mode: bool) -> None: self.prev = torch._C._is_view_replay_enabled() torch._C._set_view_replay_enabled(mode) self.mode = mode def __enter__(self) -> None: pass def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None: torch._C._set_view_replay_enabled(self.prev) def clone(self): return self.__class__(self.mode)
_force_original_view_tracking
python
fsspec__filesystem_spec
fsspec/implementations/tests/memory/memory_test.py
{ "start": 426, "end": 501 }
class ____(abstract.AbstractOpenTests, MemoryFixtures): pass
TestMemoryOpen
python
huggingface__transformers
src/transformers/models/timesfm/modeling_timesfm.py
{ "start": 12147, "end": 22120 }
class ____(TimesFmPreTrainedModel): def __init__(self, config: TimesFmConfig): super().__init__(config) self.config = config self.input_ff_layer = TimesFmResidualBlock( input_dims=2 * config.patch_length, output_dims=config.hidden_size, hidden_dims=config.intermediate_size, ) self.freq_emb = nn.Embedding(num_embeddings=config.freq_size, embedding_dim=config.hidden_size) self.layers = nn.ModuleList( [TimesFmDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) if self.config.use_positional_embedding: self.position_emb = TimesFmPositionalEmbedding(config=config) # Initialize weights and apply final processing self.post_init() def _forward_transform( self, inputs: torch.Tensor, patched_pads: torch.Tensor ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor]]: """Input is of shape [B, N, P].""" mu, sigma = self._timesfm_masked_mean_std(inputs, patched_pads) sigma = torch.clamp(sigma, min=self.config.tolerance) # Normalize each patch outputs = (inputs - mu[:, None, None]) / sigma[:, None, None] outputs = torch.where( torch.abs(inputs - self.config.pad_val) < self.config.tolerance, torch.tensor(self.config.pad_val, dtype=outputs.dtype, device=outputs.device), outputs, ) return outputs, (mu, sigma) @can_return_tuple @auto_docstring def forward( self, past_values: torch.Tensor, past_values_padding: torch.LongTensor, freq: torch.Tensor, output_attentions: bool = False, output_hidden_states: bool = False, ) -> TimesFmOutput: r""" past_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`): Past values of the time series that serves as input to the model. past_values_padding (`torch.LongTensor` of shape `(batch_size, sequence_length)`): The padding indicator of the time series. freq (`torch.LongTensor` of shape `(batch_size,)`): Frequency indices for the time series data. """ # Reshape into patches (using view for efficiency) bsize = past_values.shape[0] patched_inputs = past_values.view(bsize, -1, self.config.patch_length) patched_pads = past_values_padding.view(bsize, -1, self.config.patch_length) patched_inputs = torch.where( torch.abs(patched_pads - 1.0) < self.config.tolerance, torch.tensor(0.0, dtype=patched_inputs.dtype, device=patched_inputs.device), patched_inputs, ) patched_pads = torch.where( torch.abs(patched_inputs - self.config.pad_val) < self.config.tolerance, torch.tensor(1.0, dtype=patched_pads.dtype, device=patched_pads.device), patched_pads, ) patched_inputs, stats = self._forward_transform(patched_inputs, patched_pads) # B x N x D patched_inputs = patched_inputs * (1.0 - patched_pads) concat_inputs = torch.cat([patched_inputs, patched_pads], dim=-1) model_input = self.input_ff_layer(concat_inputs) # A patch should not be padded even if there is at least one zero. patched_padding = torch.min(patched_pads, dim=-1)[0] # Get the values from the min result if self.config.use_positional_embedding: pos_emb = self.position_emb(model_input.shape[1]) pos_emb = torch.concat([pos_emb] * model_input.shape[0], dim=0) pos_emb = self._timesfm_shift_padded_seq(patched_padding, pos_emb) model_input += pos_emb f_emb = self.freq_emb(freq) # B x 1 x D model_input += f_emb # Convert paddings to attention mask and combine with causal mask hidden_states = model_input attention_mask = self._prepare_4d_attention_mask( attention_mask=patched_padding, sequence_length=hidden_states.shape[1], dtype=hidden_states.dtype, device=hidden_states.device, is_causal=True, ) all_attentions = [] all_hidden_states = [] for layer in self.layers[: self.config.num_hidden_layers]: scores, hidden_states = layer( hidden_states=hidden_states, attention_mask=attention_mask, paddings=patched_padding, output_attentions=output_attentions, ) if output_attentions: all_attentions.append(scores) if output_hidden_states: all_hidden_states.append(hidden_states) if output_hidden_states: all_hidden_states = [model_input] + all_hidden_states else: all_hidden_states = None return TimesFmOutput( last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions if output_attentions else None, loc=stats[0], scale=stats[1], ) @staticmethod def _prepare_4d_attention_mask( attention_mask: Optional[torch.Tensor], sequence_length: int, dtype: torch.dtype, device: torch.device, is_causal: bool = True, ) -> Optional[torch.Tensor]: """ Creates 4D attention mask and combines causal and padding masks if needed. Args: attention_mask: Optional tensor of shape (batch_size, seq_length) containing padding mask sequence_length: Length of the sequence dtype: Data type of the mask device: Device of the mask is_causal: Whether to apply causal masking Returns: 4D attention mask of shape (batch_size, 1, seq_length, seq_length) """ # Get minimum value for the dtype min_value = torch.finfo(dtype).min if dtype.is_floating_point else torch.iinfo(dtype).min # Handle padding mask if attention_mask is not None: # Convert 2D padding mask to 4D attention mask attention_mask = attention_mask.view(attention_mask.shape[0], 1, 1, -1) attention_mask = attention_mask * min_value # Create causal mask if needed if is_causal: causal_mask = torch.triu( torch.ones((sequence_length, sequence_length), dtype=dtype, device=device) * min_value, diagonal=1, ) causal_mask = causal_mask.view(1, 1, sequence_length, sequence_length) # Combine with padding mask if it exists if attention_mask is not None: attention_mask = torch.minimum(attention_mask, causal_mask) else: attention_mask = causal_mask return attention_mask @staticmethod def _timesfm_masked_mean_std(inputs: torch.Tensor, padding: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: """Calculates mean and standard deviation of `inputs` across axis 1. It excludes values where `padding` is 1. Args: inputs: A PyTorch tensor of shape [b, n, p]. padding: A PyTorch tensor of shape [b, n, p] with values 0 or 1. Returns: A tuple containing the mean and standard deviation. We return the statistics of the first patch with more than three non-padded values. """ # Selecting the first patch with more than 3 unpadded values. def _get_patch_index(arr: torch.Tensor): indices = torch.argmax((arr >= 3).to(torch.int32), dim=1) row_sum = (arr >= 3).to(torch.int32).sum(dim=1) return torch.where(row_sum == 0, arr.shape[1] - 1, indices) pad_sum = torch.sum(1 - padding, dim=2) patch_indices = _get_patch_index(pad_sum) bidxs = torch.arange(inputs.shape[0]) arr = inputs[bidxs, patch_indices, :] pad = padding[bidxs, patch_indices, :] # Create a mask where padding is 0 mask = 1 - pad # Calculate the number of valid elements num_valid_elements = torch.sum(mask, dim=1) num_valid_elements = torch.clamp(num_valid_elements, min=1.0) # Calculate the masked sum and mean masked_sum = torch.sum(arr * mask, dim=1) masked_mean = masked_sum / num_valid_elements # [b] # Calculate the masked variance using centered values masked_centered_arr = (arr - masked_mean.unsqueeze(-1)) * mask masked_var = torch.sum(masked_centered_arr**2, dim=1) / num_valid_elements masked_var = torch.clamp(masked_var, min=0.0) masked_std = torch.sqrt(masked_var) return masked_mean, masked_std @staticmethod def _timesfm_shift_padded_seq(mask: torch.Tensor, seq: torch.Tensor) -> torch.Tensor: """Shifts rows of seq based on the first 0 in each row of the mask. Args: mask: mask tensor of shape [B, N] seq: seq tensor of shape [B, N, P] Returns: The shifted sequence. """ batch_size, num_seq, feature_dim = seq.shape new_mask: torch.BoolTensor = mask == 0 # Use argmax to find the first True value in each row indices = new_mask.to(torch.int32).argmax(dim=1) # Handle rows with all zeros indices[~new_mask.any(dim=1)] = -1 # Create index ranges for each sequence in the batch idx_range = torch.arange(num_seq, device=seq.device).view(1, -1, 1).expand(batch_size, -1, feature_dim) # Calculate shifted indices for each element in each sequence shifted_idx = (idx_range - indices[:, None, None]) % num_seq # Gather values from seq using shifted indices shifted_seq = seq.gather(1, shifted_idx) return shifted_seq
TimesFmModel
python
fastapi__sqlmodel
docs_src/tutorial/one/tutorial002.py
{ "start": 100, "end": 1637 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def create_heroes(): hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson") hero_2 = Hero(name="Spider-Boy", secret_name="Pedro Parqueador") hero_3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48) hero_4 = Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32) hero_5 = Hero(name="Black Lion", secret_name="Trevor Challa", age=35) hero_6 = Hero(name="Dr. Weird", secret_name="Steve Weird", age=36) hero_7 = Hero(name="Captain North America", secret_name="Esteban Rogelios", age=93) with Session(engine) as session: session.add(hero_1) session.add(hero_2) session.add(hero_3) session.add(hero_4) session.add(hero_5) session.add(hero_6) session.add(hero_7) session.commit() def select_heroes(): with Session(engine) as session: statement = select(Hero).where(Hero.age < 25) results = session.exec(statement) hero = results.first() print("Hero:", hero) def main(): create_db_and_tables() create_heroes() select_heroes() if __name__ == "__main__": main()
Hero
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/missing_type.py
{ "start": 499, "end": 789 }
class ____: def source(self) -> None: pass unknown = source # revealed type is `unknown` def test_unknown_source_attribute(x: UnknownSourceAttribute) -> None: # TODO(T205677349): We don't find the flow here. y = x.unknown() _test_sink(y)
UnknownSourceAttribute
python
getsentry__sentry
tests/sentry/users/api/endpoints/test_user_ips.py
{ "start": 269, "end": 1525 }
class ____(APITestCase): endpoint = "sentry-api-0-user-ips" def setUp(self) -> None: super().setUp() self.user = self.create_user(id=1) self.login_as(self.user) def test_simple(self) -> None: UserIP.objects.create( user=self.user, ip_address="127.0.0.2", first_seen=datetime(2012, 4, 5, 3, 29, 45, tzinfo=timezone.utc), last_seen=datetime(2012, 4, 5, 3, 29, 45, tzinfo=timezone.utc), ) # this will always be the newest because when we access the site it gets updated UserIP.objects.create( user=self.user, ip_address="127.0.0.1", first_seen=datetime(2012, 4, 3, 3, 29, 45, tzinfo=timezone.utc), last_seen=datetime(2013, 4, 10, 3, 29, 45, tzinfo=timezone.utc), ) response = self.get_success_response("me") assert len(response.data) == 2 assert response.data[0]["ipAddress"] == "127.0.0.1" assert response.data[1]["ipAddress"] == "127.0.0.2" @override_options({"demo-mode.enabled": True, "demo-mode.users": [1]}) def test_demo_user(self) -> None: response = self.get_response("me") assert response.status_code == 403
UserIPsTest
python
tensorflow__tensorflow
tensorflow/python/keras/optimizer_v2/gradient_descent.py
{ "start": 1036, "end": 7006 }
class ____(optimizer_v2.OptimizerV2): r"""Gradient descent (with momentum) optimizer. Update rule for parameter `w` with gradient `g` when `momentum` is 0: ```python w = w - learning_rate * g ``` Update rule when `momentum` is larger than 0: ```python velocity = momentum * velocity - learning_rate * g w = w + velocity ``` When `nesterov=True`, this rule becomes: ```python velocity = momentum * velocity - learning_rate * g w = w + momentum * velocity - learning_rate * g ``` Args: learning_rate: A `Tensor`, floating point value, or a schedule that is a `tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable that takes no arguments and returns the actual value to use. The learning rate. Defaults to 0.01. momentum: float hyperparameter >= 0 that accelerates gradient descent in the relevant direction and dampens oscillations. Defaults to 0, i.e., vanilla gradient descent. nesterov: boolean. Whether to apply Nesterov momentum. Defaults to `False`. name: Optional name prefix for the operations created when applying gradients. Defaults to `"SGD"`. **kwargs: Keyword arguments. Allowed to be one of `"clipnorm"` or `"clipvalue"`. `"clipnorm"` (float) clips gradients by norm; `"clipvalue"` (float) clips gradients by value. Usage: >>> opt = tf.keras.optimizers.SGD(learning_rate=0.1) >>> var = tf.Variable(1.0) >>> loss = lambda: (var ** 2)/2.0 # d(loss)/d(var1) = var1 >>> step_count = opt.minimize(loss, [var]).numpy() >>> # Step is `- learning_rate * grad` >>> var.numpy() 0.9 >>> opt = tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.9) >>> var = tf.Variable(1.0) >>> val0 = var.value() >>> loss = lambda: (var ** 2)/2.0 # d(loss)/d(var1) = var1 >>> # First step is `- learning_rate * grad` >>> step_count = opt.minimize(loss, [var]).numpy() >>> val1 = var.value() >>> (val0 - val1).numpy() 0.1 >>> # On later steps, step-size increases because of momentum >>> step_count = opt.minimize(loss, [var]).numpy() >>> val2 = var.value() >>> (val1 - val2).numpy() 0.18 Reference: - For `nesterov=True`, See [Sutskever et al., 2013]( http://jmlr.org/proceedings/papers/v28/sutskever13.pdf). """ _HAS_AGGREGATE_GRAD = True def __init__(self, learning_rate=0.01, momentum=0.0, nesterov=False, name="SGD", **kwargs): super(SGD, self).__init__(name, **kwargs) self._set_hyper("learning_rate", kwargs.get("lr", learning_rate)) self._set_hyper("decay", self._initial_decay) self._momentum = False if isinstance( momentum, tensor.Tensor) or callable(momentum) or momentum > 0: self._momentum = True if isinstance(momentum, (int, float)) and (momentum < 0 or momentum > 1): raise ValueError("`momentum` must be between [0, 1].") self._set_hyper("momentum", momentum) self.nesterov = nesterov def _create_slots(self, var_list): if self._momentum: for var in var_list: self.add_slot(var, "momentum") def _prepare_local(self, var_device, var_dtype, apply_state): super(SGD, self)._prepare_local(var_device, var_dtype, apply_state) apply_state[(var_device, var_dtype)]["momentum"] = array_ops.identity( self._get_hyper("momentum", var_dtype)) def _resource_apply_dense(self, grad, var, apply_state=None): var_device, var_dtype = var.device, var.dtype.base_dtype coefficients = ((apply_state or {}).get((var_device, var_dtype)) or self._fallback_apply_state(var_device, var_dtype)) if self._momentum: momentum_var = self.get_slot(var, "momentum") return gen_training_ops.ResourceApplyKerasMomentum( var=var.handle, accum=momentum_var.handle, lr=coefficients["lr_t"], grad=grad, momentum=coefficients["momentum"], use_locking=self._use_locking, use_nesterov=self.nesterov) else: return gen_training_ops.ResourceApplyGradientDescent( var=var.handle, alpha=coefficients["lr_t"], delta=grad, use_locking=self._use_locking) def _resource_apply_sparse_duplicate_indices(self, grad, var, indices, **kwargs): if self._momentum: return super(SGD, self)._resource_apply_sparse_duplicate_indices( grad, var, indices, **kwargs) else: var_device, var_dtype = var.device, var.dtype.base_dtype coefficients = (kwargs.get("apply_state", {}).get((var_device, var_dtype)) or self._fallback_apply_state(var_device, var_dtype)) return gen_resource_variable_ops.ResourceScatterAdd( resource=var.handle, indices=indices, updates=-grad * coefficients["lr_t"]) def _resource_apply_sparse(self, grad, var, indices, apply_state=None): # This method is only needed for momentum optimization. var_device, var_dtype = var.device, var.dtype.base_dtype coefficients = ((apply_state or {}).get((var_device, var_dtype)) or self._fallback_apply_state(var_device, var_dtype)) momentum_var = self.get_slot(var, "momentum") return gen_training_ops.ResourceSparseApplyKerasMomentum( var=var.handle, accum=momentum_var.handle, lr=coefficients["lr_t"], grad=grad, indices=indices, momentum=coefficients["momentum"], use_locking=self._use_locking, use_nesterov=self.nesterov) def get_config(self): config = super(SGD, self).get_config() config.update({ "learning_rate": self._serialize_hyperparameter("learning_rate"), "decay": self._initial_decay, "momentum": self._serialize_hyperparameter("momentum"), "nesterov": self.nesterov, }) return config
SGD
python
langchain-ai__langchain
libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_selection.py
{ "start": 2840, "end": 6852 }
class ____: """Test basic tool selection functionality.""" def test_sync_basic_selection(self) -> None: """Test synchronous tool selection.""" # First call: selector picks tools # Second call: agent uses selected tools tool_calls = [ [ { "name": "ToolSelectionResponse", "id": "1", "args": {"tools": ["get_weather", "calculate"]}, } ], [{"name": "get_weather", "id": "2", "args": {"location": "Paris"}}], ] model_requests = [] @wrap_model_call def trace_model_requests(request, handler): """Middleware to select relevant tools based on state/context.""" # Select a small, relevant subset of tools based on state/context model_requests.append(request) return handler(request) tool_selection_model = FakeModel( messages=cycle( [ AIMessage( content="", tool_calls=[ { "name": "ToolSelectionResponse", "id": "1", "args": {"tools": ["get_weather", "calculate"]}, } ], ), ] ) ) model = FakeModel( messages=iter( [ AIMessage( content="", tool_calls=[ {"name": "get_weather", "id": "2", "args": {"location": "Paris"}} ], ), AIMessage(content="The weather in Paris is 72°F and sunny."), ] ) ) tool_selector = LLMToolSelectorMiddleware(max_tools=2, model=tool_selection_model) agent = create_agent( model=model, tools=[get_weather, search_web, calculate, send_email, get_stock_price], middleware=[tool_selector, trace_model_requests], ) response = agent.invoke({"messages": [HumanMessage("What's the weather in Paris?")]}) assert isinstance(response["messages"][-1], AIMessage) for request in model_requests: selected_tool_names = [tool.name for tool in request.tools] if request.tools else [] assert selected_tool_names == ["get_weather", "calculate"] async def test_async_basic_selection(self) -> None: """Test asynchronous tool selection.""" tool_selection_model = FakeModel( messages=cycle( [ AIMessage( content="", tool_calls=[ { "name": "ToolSelectionResponse", "id": "1", "args": {"tools": ["search_web"]}, } ], ), ] ) ) model = FakeModel( messages=iter( [ AIMessage( content="", tool_calls=[{"name": "search_web", "id": "2", "args": {"query": "Python"}}], ), AIMessage(content="Search results found."), ] ) ) tool_selector = LLMToolSelectorMiddleware(max_tools=1, model=tool_selection_model) agent = create_agent( model=model, tools=[get_weather, search_web, calculate], middleware=[tool_selector], ) response = await agent.ainvoke({"messages": [HumanMessage("Search for Python tutorials")]}) assert isinstance(response["messages"][-1], AIMessage)
TestLLMToolSelectorBasic
python
ray-project__ray
rllib/env/multi_agent_env_runner.py
{ "start": 2469, "end": 45194 }
class ____(EnvRunner, Checkpointable): """The genetic environment runner for the multi-agent case.""" @override(EnvRunner) def __init__(self, config: AlgorithmConfig, **kwargs): """Initializes a MultiAgentEnvRunner instance. Args: config: An `AlgorithmConfig` object containing all settings needed to build this `EnvRunner` class. """ super().__init__(config=config, **kwargs) # Raise an Error, if the provided config is not a multi-agent one. if not self.config.is_multi_agent: raise ValueError( f"Cannot use this EnvRunner class ({type(self).__name__}), if your " "setup is not multi-agent! Try adding multi-agent information to your " "AlgorithmConfig via calling the `config.multi_agent(policies=..., " "policy_mapping_fn=...)`." ) self.spaces = kwargs.get("spaces", {}) self._setup_metrics() # Create our callbacks object. self._callbacks = [cls() for cls in force_list(self.config.callbacks_class)] # Set device. self._device = get_device( self.config, 0 if not self.worker_index else self.config.num_gpus_per_env_runner, ) # Create the vectorized gymnasium env. self.env: Optional[VectorMultiAgentEnv] = None self.num_envs: int = 0 if ( self.worker_index is None or self.worker_index > 0 or self.config.create_env_on_local_worker or self.config.num_env_runners == 0 ): self.make_env() # Create the env-to-module connector pipeline. self._env_to_module = self.config.build_env_to_module_connector( env=self.env, spaces=self.spaces, device=self._device ) # Cached env-to-module results taken at the end of a `_sample_timesteps()` # call to make sure the final observation (before an episode cut) gets properly # processed (and maybe postprocessed and re-stored into the episode). # For example, if we had a connector that normalizes observations and directly # re-inserts these new obs back into the episode, the last observation in each # sample call would NOT be processed, which could be very harmful in cases, # in which value function bootstrapping of those (truncation) observations is # required in the learning step. self._cached_to_module = None # Construct the MultiRLModule. self.module: Optional[MultiRLModule] = None self.make_module() # Create the module-to-env connector pipeline. self._module_to_env = self.config.build_module_to_env_connector( env=self.env.unwrapped if self.env else None, spaces=self.spaces ) self._needs_initial_reset: bool = True self._episode: Optional[MultiAgentEpisode] = None self._shared_data = None self._weights_seq_no: int = 0 # Measures the time passed between returning from `sample()` # and receiving the next `sample()` request from the user. self._time_after_sampling = None @override(EnvRunner) def sample( self, *, num_timesteps: int = None, num_episodes: int = None, explore: bool = None, random_actions: bool = False, force_reset: bool = False, ) -> List[MultiAgentEpisode]: """Runs and returns a sample (n timesteps or m episodes) on the env(s). Args: num_timesteps: The number of timesteps to sample during this call. Note that only one of `num_timesteps` or `num_episodes` may be provided. num_episodes: The number of episodes to sample during this call. Note that only one of `num_timesteps` or `num_episodes` may be provided. explore: If True, will use the RLModule's `forward_exploration()` method to compute actions. If False, will use the RLModule's `forward_inference()` method. If None (default), will use the `explore` boolean setting from `self.config` passed into this EnvRunner's constructor. You can change this setting in your config via `config.env_runners(explore=True|False)`. random_actions: If True, actions will be sampled randomly (from the action space of the environment). If False (default), actions or action distribution parameters are computed by the RLModule. force_reset: Whether to force-reset all (vector) environments before sampling. Useful if you would like to collect a clean slate of new episodes via this call. Note that when sampling n episodes (`num_episodes != None`), this is fixed to True. Returns: A list of `MultiAgentEpisode` instances, carrying the sampled data. """ if self.env is None: raise ValueError( f"{self} doesn't have an env! Can't call `sample()` on it." ) assert not (num_timesteps is not None and num_episodes is not None), ( "Provide " "either `num_timesteps` or `num_episodes`. Both provided here:" f"{num_timesteps=}, {num_episodes=}" ) # Log time between `sample()` requests. if self._time_after_sampling is not None: self.metrics.log_value( key=TIME_BETWEEN_SAMPLING, value=time.perf_counter() - self._time_after_sampling, ) # Log current weight seq no. self.metrics.log_value( key=WEIGHTS_SEQ_NO, value=self._weights_seq_no, window=1, ) with self.metrics.log_time(SAMPLE_TIMER): # If no execution details are provided, use the config to try to infer the # desired timesteps/episodes to sample and exploration behavior. if explore is None: explore = self.config.explore if ( num_timesteps is None and num_episodes is None and self.config.batch_mode == "truncate_episodes" ): num_timesteps = ( self.config.get_rollout_fragment_length(self.worker_index) * self.num_envs ) # Sample "num_timesteps" timesteps. if num_timesteps is not None: samples = self._sample( num_timesteps=num_timesteps, explore=explore, random_actions=random_actions, force_reset=force_reset, ) # Sample "num_episodes" episodes. elif num_episodes is not None: samples = self._sample( num_episodes=num_episodes, explore=explore, random_actions=random_actions, ) # For batch_mode="complete_episodes" (env_runners configuration), continue sampling as long as the number of timesteps done is smaller than the `train_batch_size`. else: samples = self._sample( num_episodes=self.num_envs, explore=explore, random_actions=random_actions, ) # Make the `on_sample_end` callback. make_callback( "on_sample_end", callbacks_objects=self._callbacks, callbacks_functions=self.config.callbacks_on_sample_end, kwargs=dict( env_runner=self, metrics_logger=self.metrics, samples=samples, ), ) self._time_after_sampling = time.perf_counter() return samples def _sample( self, *, num_timesteps: Optional[int] = None, num_episodes: Optional[int] = None, explore: bool, random_actions: bool = False, force_reset: bool = False, ) -> List[MultiAgentEpisode]: done_episodes_to_return: List[MultiAgentEpisode] = [] # Have to reset the env (on all vector sub_envs). if force_reset or num_episodes is not None or self._needs_initial_reset: episodes = self._episodes = [None for _ in range(self.num_envs)] shared_data = self._shared_data = {} self._reset_envs(episodes, shared_data, explore) # We just reset the env. Don't have to force this again in the next # call to `self._sample_timesteps()`. self._needs_initial_reset = False else: episodes = self._episodes shared_data = self._shared_data if num_episodes is not None: self._needs_initial_reset = True # Loop through `num_timesteps` timesteps or `num_episodes` episodes. env_ts = 0 agent_ts = 0 eps = 0 while ( (eps < num_episodes) if num_timesteps is None else ( env_ts < num_timesteps if self.config.count_steps_by == "env_steps" else agent_ts < num_timesteps ) ): # Act randomly. if random_actions: to_env = { Columns.ACTIONS: [ { # Only act (randomly) for those agents that had an # observation. aid: self.env.envs[i] .unwrapped.get_action_space(aid) .sample() for aid in episodes[i].get_agents_to_act() } for i in range(self.num_envs) ] } # Compute an action using the RLModule. else: # Env-to-module connector (already cached). to_module = self._cached_to_module assert to_module is not None self._cached_to_module = None if to_module: # MultiRLModule forward pass: Explore or not. if explore: # Global env steps sampled are (roughly) this EnvRunner's lifetime # count times the number of env runners in the algo. global_env_steps_lifetime = ( self.metrics.peek(NUM_ENV_STEPS_SAMPLED_LIFETIME, default=0) + env_ts ) * (self.config.num_env_runners or 1) with self.metrics.log_time(RLMODULE_INFERENCE_TIMER): to_env = self.module.forward_exploration( to_module, t=global_env_steps_lifetime ) else: with self.metrics.log_time(RLMODULE_INFERENCE_TIMER): to_env = self.module.forward_inference(to_module) # Module-to-env connector. to_env = self._module_to_env( rl_module=self.module, batch=to_env, episodes=episodes, explore=explore, shared_data=shared_data, metrics=self.metrics, metrics_prefix_key=(MODULE_TO_ENV_CONNECTOR,), ) # In case all environments had been terminated `to_module` will be # empty and no actions are needed b/c we reset all environments. else: to_env = {} shared_data["vector_env_episodes_map"] = {} # Extract the (vectorized) actions (to be sent to the env) from the # module/connector output. Note that these actions are fully ready (e.g. # already unsquashed/clipped) to be sent to the environment and might not # be identical to the actions produced by the RLModule/distribution, which # are the ones stored permanently in the episode objects. actions = to_env.pop(Columns.ACTIONS, [{} for _ in episodes]) actions_for_env = to_env.pop(Columns.ACTIONS_FOR_ENV, actions) # Try stepping the environment. results = self._try_env_step(actions_for_env) if results == ENV_STEP_FAILURE: return self._sample( num_timesteps=num_timesteps, num_episodes=num_episodes, explore=explore, random_actions=random_actions, force_reset=True, ) observations, rewards, terminateds, truncateds, infos = results call_on_episode_start = set() # Store the data from the last environment step into the # episodes for all sub-environments. for env_index in range(self.num_envs): extra_model_outputs = defaultdict(dict) # `to_env` returns a dictionary with column keys and # (AgentID, value) tuple values. for col, ma_dict_list in to_env.items(): ma_dict = ma_dict_list[env_index] for agent_id, val in ma_dict.items(): extra_model_outputs[agent_id][col] = val extra_model_outputs[agent_id][ WEIGHTS_SEQ_NO ] = self._weights_seq_no extra_model_outputs = dict(extra_model_outputs) # Episode has no data in it yet -> Was just reset and needs to be called # with its `add_env_reset()` method. if not self._episodes[env_index].is_reset: # Add the reset step data to the episode. episodes[env_index].add_env_reset( observations=observations[env_index], infos=infos[env_index], ) # Call the callback on episode start so users can hook in. call_on_episode_start.add(env_index) # Call `add_env_step()` method on episode. else: episodes[env_index].add_env_step( observations=observations[env_index], actions=actions[env_index], rewards=rewards[env_index], infos=infos[env_index], terminateds=terminateds[env_index], truncateds=truncateds[env_index], extra_model_outputs=extra_model_outputs, ) # Ray metrics self._log_env_steps( metric=self._metrics_num_env_steps_sampled, num_steps=1 ) # Only increase ts when we actually stepped (not reset'd as a reset # does not count as a timestep). env_ts += self._increase_sampled_metrics( 1, observations[env_index], episodes[env_index] ) agent_ts += len(observations[env_index]) done_episodes_to_run_env_to_module = [] for env_index in range(self.num_envs): # Call `on_episode_start()` callback (always after reset). if env_index in call_on_episode_start: self._make_on_episode_callback( "on_episode_start", env_index, episodes ) # Make the `on_episode_step` callbacks. else: self._make_on_episode_callback( "on_episode_step", env_index, episodes ) # Episode is done. if episodes[env_index].is_done: eps += 1 # Make the `on_episode_end` callbacks (before finalizing the episode # object). self._make_on_episode_callback( "on_episode_end", env_index, episodes ) # TODO (simon): Check, if needed. I guess not b/c the complete episode is done. # This needs to be executed here to remove the `SingleAgentEpisode`s # that are done. self._prune_zero_len_sa_episodes(episodes[env_index]) done_episodes_to_return.append(episodes[env_index]) # Run a last time the `env_to_module` pipeline for these episodes # to postprocess artifacts (e.g. observations to one-hot). done_episodes_to_run_env_to_module.append(episodes[env_index]) old_episode_id = episodes[env_index].id_ # Create a new episode object with no data in it. # Note: If we're about to break (reached target num_episodes), skip # the `on_episode_created` callback since this episode will never be # used (it gets discarded on the next sample() call). self._new_episode( env_index, episodes, call_on_episode_created=(eps != num_episodes), ) # Register the mapping of new episode ID to old episode ID. shared_data["vector_env_episodes_map"].update( {old_episode_id: episodes[env_index].id_} ) # Also early-out if we reach the number of episodes within this # for-loop. if eps == num_episodes: break # Env-to-module connector pass (cache results as we will do the RLModule # forward pass only in the next `while`-iteration). # Note, running the pipeline here ensures that we are not executing a # pipeline run for agents that have died. This increases performance in # case of environments in which 1000's of agents exist. Because the # `VectorMultiAgentEnv` calls `reset()` for any terminated/truncated sub- # environment `observations` and `infos` will always be returned for the # `MultiAgentEpisode.add_reset_step`. if self.module is not None: if done_episodes_to_run_env_to_module: # Run the env-to-module connector pipeline for all done episodes. # Note, this is needed to postprocess last-step data, e.g. if the # user uses a connector that one-hot encodes observations. # Note, this pipeline run is not timed as the number of episodes # can differ from `num_envs_per_env_runner` and would bias time # measurements. self._env_to_module( batch={}, episodes=done_episodes_to_run_env_to_module, explore=explore, rl_module=self.module, shared_data=shared_data, metrics=None, ) self._cached_to_module = self._env_to_module( batch={}, episodes=episodes, explore=explore, rl_module=self.module, shared_data=shared_data, metrics=self.metrics, metrics_prefix_key=(ENV_TO_MODULE_CONNECTOR,), ) # Numpy'ize the done episodes after running the connector pipeline. Note, # that we need simple `list` objects in the # `AddObservationsFromEpisodesToBatch` connector. Furthermore, we spare # multiple `if` calls. if self.config.episodes_to_numpy: for episode in done_episodes_to_return: # Any possibly compress observations. episode.to_numpy() # Return done episodes ... self._done_episodes_for_metrics.extend(done_episodes_to_return) # ... and all ongoing episode chunks. # Also, make sure we start new episode chunks (continuing the ongoing episodes # from the to-be-returned chunks). ongoing_episodes_to_return = [] # Only if we are doing individual timesteps: We have to maybe cut an ongoing # episode and continue building it on the next call to `sample()`. if num_timesteps is not None: ongoing_episodes_continuations = [ eps.cut(len_lookback_buffer=self.config.episode_lookback_horizon) for eps in self._episodes ] for eps in self._episodes: # Just started Episodes do not have to be returned. There is no data # in them anyway. if eps.env_t == 0: continue eps.validate() self._ongoing_episodes_for_metrics[eps.id_].append(eps) self._prune_zero_len_sa_episodes(eps) # Numpy'ize the episode. if self.config.episodes_to_numpy: # Any possibly compress observations. ongoing_episodes_to_return.append(eps.to_numpy()) # Leave episode as lists of individual (obs, action, etc..) items. else: ongoing_episodes_to_return.append(eps) # Continue collecting into the cut Episode chunks. self._episodes = ongoing_episodes_continuations # Return collected episode data. return done_episodes_to_return + ongoing_episodes_to_return def _reset_envs(self, episodes, shared_data, explore): for env_index in range(self.num_envs): self._new_episode(env_index, episodes) # Erase all cached ongoing episodes. This EnvRunner never completes or returns # these from `get_metrics`, causing a memory leak. self._ongoing_episodes_for_metrics.clear() # Try resetting the environment. observations, infos = self._try_env_reset( # Only seed (if seed provided) upon initial reset. seed=self._seed if self._needs_initial_reset else None, # TODO (sven): Support options? options=None, ) # Set the initial obs and infos in the episodes. for env_index in range(self.num_envs): episodes[env_index].add_env_reset( observations=observations[env_index], infos=infos[env_index], ) # Run the env-to-module connector to make sure the reset-obs/infos have # properly been processed (if applicable). self._cached_to_module = None if self.module: self._cached_to_module = self._env_to_module( rl_module=self.module, episodes=episodes, explore=explore, shared_data=shared_data, metrics=self.metrics, metrics_key_prefix=(ENV_TO_MODULE_CONNECTOR,), ) # Call `on_episode_start()` callbacks (always after reset). for env_index in range(self.num_envs): self._make_on_episode_callback("on_episode_start", env_index, episodes) @override(EnvRunner) def get_spaces(self): if self.env is None: return self.spaces # Return the already agent-to-module translated spaces from our connector # pipeline. return { INPUT_ENV_SPACES: (self.env.observation_space, self.env.action_space), INPUT_ENV_SINGLE_SPACES: ( self.env.single_observation_space, self.env.single_action_space, ), **{ mid: (o, self._env_to_module.action_space[mid]) for mid, o in self._env_to_module.observation_space.spaces.items() }, } @override(EnvRunner) def get_metrics(self) -> ResultDict: # Compute per-episode metrics (only on already completed episodes). for eps in self._done_episodes_for_metrics: assert eps.is_done episode_length = len(eps) agent_steps = defaultdict( int, {str(aid): len(sa_eps) for aid, sa_eps in eps.agent_episodes.items()}, ) episode_return = eps.get_return() episode_duration_s = eps.get_duration_s() agent_episode_returns = defaultdict( float, { str(sa_eps.agent_id): sa_eps.get_return() for sa_eps in eps.agent_episodes.values() }, ) module_episode_returns = defaultdict( float, { sa_eps.module_id: sa_eps.get_return() for sa_eps in eps.agent_episodes.values() }, ) # Don't forget about the already returned chunks of this episode. if eps.id_ in self._ongoing_episodes_for_metrics: for eps2 in self._ongoing_episodes_for_metrics[eps.id_]: return_eps2 = eps2.get_return() episode_length += len(eps2) episode_return += return_eps2 episode_duration_s += eps2.get_duration_s() for sa_eps in eps2.agent_episodes.values(): return_sa = sa_eps.get_return() agent_steps[str(sa_eps.agent_id)] += len(sa_eps) agent_episode_returns[str(sa_eps.agent_id)] += return_sa module_episode_returns[sa_eps.module_id] += return_sa del self._ongoing_episodes_for_metrics[eps.id_] self._log_episode_metrics( episode_length, episode_return, episode_duration_s, agent_episode_returns, module_episode_returns, dict(agent_steps), ) # Now that we have logged everything, clear cache of done episodes. self._done_episodes_for_metrics.clear() # Return reduced metrics. return self.metrics.reduce() @override(Checkpointable) def get_state( self, components: Optional[Union[str, Collection[str]]] = None, *, not_components: Optional[Union[str, Collection[str]]] = None, **kwargs, ) -> StateDict: # Basic state dict. state = { NUM_ENV_STEPS_SAMPLED_LIFETIME: ( self.metrics.peek(NUM_ENV_STEPS_SAMPLED_LIFETIME, default=0) ), } # RLModule (MultiRLModule) component. if self._check_component(COMPONENT_RL_MODULE, components, not_components): state[COMPONENT_RL_MODULE] = self.module.get_state( components=self._get_subcomponents(COMPONENT_RL_MODULE, components), not_components=self._get_subcomponents( COMPONENT_RL_MODULE, not_components ), **kwargs, ) state[WEIGHTS_SEQ_NO] = self._weights_seq_no # Env-to-module connector. if self._check_component( COMPONENT_ENV_TO_MODULE_CONNECTOR, components, not_components ): state[COMPONENT_ENV_TO_MODULE_CONNECTOR] = self._env_to_module.get_state() # Module-to-env connector. if self._check_component( COMPONENT_MODULE_TO_ENV_CONNECTOR, components, not_components ): state[COMPONENT_MODULE_TO_ENV_CONNECTOR] = self._module_to_env.get_state() return state @override(Checkpointable) def set_state(self, state: StateDict) -> None: if COMPONENT_ENV_TO_MODULE_CONNECTOR in state: self._env_to_module.set_state(state[COMPONENT_ENV_TO_MODULE_CONNECTOR]) if COMPONENT_MODULE_TO_ENV_CONNECTOR in state: self._module_to_env.set_state(state[COMPONENT_MODULE_TO_ENV_CONNECTOR]) # Update RLModule state. if COMPONENT_RL_MODULE in state: # A missing value for WEIGHTS_SEQ_NO or a value of 0 means: Force the # update. weights_seq_no = state.get(WEIGHTS_SEQ_NO, 0) # Only update the weights, if this is the first synchronization or # if the weights of this `EnvRunner` lacks behind the actual ones. if weights_seq_no == 0 or self._weights_seq_no < weights_seq_no: rl_module_state = state[COMPONENT_RL_MODULE] if isinstance(rl_module_state, ray.ObjectRef): rl_module_state = ray.get(rl_module_state) self.module.set_state(rl_module_state) # Update weights_seq_no, if the new one is > 0. if weights_seq_no > 0: self._weights_seq_no = weights_seq_no # Update lifetime counters. if NUM_ENV_STEPS_SAMPLED_LIFETIME in state: self.metrics.set_value( key=NUM_ENV_STEPS_SAMPLED_LIFETIME, value=state[NUM_ENV_STEPS_SAMPLED_LIFETIME], reduce="sum", with_throughput=True, ) @override(Checkpointable) def get_ctor_args_and_kwargs(self): return ( (), # *args {"config": self.config}, # **kwargs ) @override(Checkpointable) def get_metadata(self): metadata = Checkpointable.get_metadata(self) metadata.update( { # TODO (sven): Maybe add serialized (JSON-writable) config here? } ) return metadata @override(Checkpointable) def get_checkpointable_components(self): return [ (COMPONENT_RL_MODULE, self.module), (COMPONENT_ENV_TO_MODULE_CONNECTOR, self._env_to_module), (COMPONENT_MODULE_TO_ENV_CONNECTOR, self._module_to_env), ] @override(EnvRunner) def assert_healthy(self): """Checks that self.__init__() has been completed properly. Ensures that the instances has a `MultiRLModule` and an environment defined. Raises: AssertionError: If the EnvRunner Actor has NOT been properly initialized. """ # Make sure, we have built our gym.vector.Env and RLModule properly. assert self.env and self.module @override(EnvRunner) def make_env(self): # If an env already exists, try closing it first (to allow it to properly # cleanup). if self.env is not None: try: self.env.close() except Exception as e: logger.warning( "Tried closing the existing env (multi-agent), but failed with " f"error: {e.args[0]}" ) del self.env env_ctx = self.config.env_config if not isinstance(env_ctx, EnvContext): env_ctx = EnvContext( env_ctx, worker_index=self.worker_index, num_workers=self.config.num_env_runners, remote=self.config.remote_worker_envs, ) # No env provided -> Error. if not self.config.env: raise ValueError( "`config.env` is not provided! You should provide a valid environment " "to your config through `config.environment([env descriptor e.g. " "'CartPole-v1'])`." ) # Register env for the local context. # Note, `gym.register` has to be called on each worker. elif isinstance(self.config.env, str) and _global_registry.contains( ENV_CREATOR, self.config.env ): entry_point = partial( _global_registry.get(ENV_CREATOR, self.config.env), env_ctx, ) else: entry_point = partial( _gym_env_creator, env_descriptor=self.config.env, env_context=env_ctx, ) gym.register( "rllib-multi-agent-env-v0", entry_point=entry_point, disable_env_checker=True, ) vectorize_mode = self.config.gym_env_vectorize_mode # Perform actual gym.make call. self.env = make_vec( "rllib-multi-agent-env-v0", num_envs=self.config.num_envs_per_env_runner, vectorization_mode=( vectorize_mode if isinstance(vectorize_mode, gym.envs.registration.VectorizeMode) else gym.envs.registration.VectorizeMode(vectorize_mode.lower()) ), ) self.num_envs: int = self.env.num_envs assert self.num_envs == self.config.num_envs_per_env_runner # self.env: MultiAgentEnv = gym.make("rllib-multi-agent-env-v0") # self.num_envs = 1 # If required, check the created MultiAgentEnv instances. if not self.config.disable_env_checking: try: for env in self.env.envs: check_multiagent_environments(env.unwrapped) except Exception as e: logger.exception(e.args[0]) # If not required, still check the type (must be `VectorMultiAgentEnv``). else: try: assert isinstance(self.env, VectorMultiAgentEnv) assert isinstance(self.env.envs[0].unwrapped, MultiAgentEnv) except AssertionError: logger.exception( "When using the `MultiAgentEnvRunner`, the environment must " f"inherit from `ray.rllib.env.vector.vector_multi_agent_env." f"VectorMultiAgentEnv` (but yours is {self.env}) and the individual" " envs must inherit from `MultiAgentEnv` (but yours is " f"{self.env.envs[0].unwrapped})!" ) except TypeError: logger.exception( "When using the `MultiAgentEnvRunner`, the env must " "have a subscriptable `self.envs` attribute!" ) # Set the flag to reset all envs upon the next `sample()` call. self._needs_initial_reset = True # Call the `on_environment_created` callback. make_callback( "on_environment_created", callbacks_objects=self._callbacks, callbacks_functions=self.config.callbacks_on_environment_created, kwargs=dict( env_runner=self, metrics_logger=self.metrics, env=self.env.unwrapped, env_context=env_ctx, ), ) @override(EnvRunner) def make_module(self): env = self.env.unwrapped if self.env is not None else None try: module_spec: MultiRLModuleSpec = self.config.get_multi_rl_module_spec( env=env, spaces=self.get_spaces(), inference_only=True ) # Build the module from its spec. self.module = module_spec.build() # Move the RLModule to our device. # TODO (sven): In order to make this framework-agnostic, we should maybe # make the MultiRLModule.build() method accept a device OR create an # additional `(Multi)RLModule.to()` override. if torch: self.module.foreach_module( lambda mid, mod: ( mod.to(self._device) if isinstance(mod, torch.nn.Module) else mod ) ) # If `AlgorithmConfig.get_rl_module_spec()` is not implemented, this env runner # will not have an RLModule, but might still be usable with random actions. except NotImplementedError: self.module = None @override(EnvRunner) def stop(self): # Note, `MultiAgentEnv` inherits `close()`-method from `gym.Env`. if self.env is not None: self.env.close() def _setup_metrics(self): self._done_episodes_for_metrics: List[MultiAgentEpisode] = [] self._ongoing_episodes_for_metrics: DefaultDict[ EpisodeID, List[MultiAgentEpisode] ] = defaultdict(list) def _new_episode(self, env_index, episodes=None, call_on_episode_created=True): episodes = episodes if episodes is not None else self._episodes episodes[env_index] = MultiAgentEpisode( observation_space={ aid: self.env.envs[env_index].unwrapped.get_observation_space(aid) for aid in self.env.envs[env_index].unwrapped.possible_agents }, action_space={ aid: self.env.envs[env_index].unwrapped.get_action_space(aid) for aid in self.env.envs[env_index].unwrapped.possible_agents }, agent_to_module_mapping_fn=self.config.policy_mapping_fn, ) if call_on_episode_created: self._make_on_episode_callback("on_episode_created", env_index, episodes) def _make_on_episode_callback( self, which: str, idx: int, episodes: List[MultiAgentEpisode] ): kwargs = dict( episode=episodes[idx], env_runner=self, metrics_logger=self.metrics, env=self.env.unwrapped, rl_module=self.module, env_index=idx, ) if which == "on_episode_end": kwargs["prev_episode_chunks"] = self._ongoing_episodes_for_metrics[ episodes[idx].id_ ] make_callback( which, callbacks_objects=self._callbacks, callbacks_functions=getattr(self.config, f"callbacks_{which}"), kwargs=kwargs, ) def _increase_sampled_metrics(self, num_steps, next_obs, episode): # Env steps. self.metrics.log_value( NUM_ENV_STEPS_SAMPLED, num_steps, reduce="sum", clear_on_reduce=True ) self.metrics.log_value( NUM_ENV_STEPS_SAMPLED_LIFETIME, num_steps, reduce="sum", with_throughput=True, ) # Completed episodes. if episode.is_done: self.metrics.log_value(NUM_EPISODES, 1, reduce="sum", clear_on_reduce=True) self.metrics.log_value(NUM_EPISODES_LIFETIME, 1, reduce="sum") # Record agent and module metrics. for aid in next_obs: self.metrics.log_value( (NUM_AGENT_STEPS_SAMPLED, str(aid)), 1, reduce="sum", clear_on_reduce=True, ) self.metrics.log_value( (NUM_AGENT_STEPS_SAMPLED_LIFETIME, str(aid)), 1, reduce="sum", ) self.metrics.log_value( (NUM_MODULE_STEPS_SAMPLED, episode.module_for(aid)), 1, reduce="sum", clear_on_reduce=True, ) self.metrics.log_value( (NUM_MODULE_STEPS_SAMPLED_LIFETIME, episode.module_for(aid)), 1, reduce="sum", ) return num_steps def _log_episode_metrics( self, length, ret, sec, agents=None, modules=None, agent_steps=None, ): # Log general episode metrics. # Use the configured window, but factor in the parallelism of the EnvRunners. # As a result, we only log the last `window / num_env_runners` steps here, # b/c everything gets parallel-merged in the Algorithm process. win = max( 1, int( math.ceil( self.config.metrics_num_episodes_for_smoothing / (self.config.num_env_runners or 1) ) ), ) self.metrics.log_dict( { EPISODE_LEN_MEAN: length, EPISODE_RETURN_MEAN: ret, EPISODE_DURATION_SEC_MEAN: sec, **( { # Per-agent returns. "agent_episode_returns_mean": agents, # Per-RLModule returns. "module_episode_returns_mean": modules, "agent_steps": agent_steps, } if agents is not None else {} ), }, window=win, ) # For some metrics, log min/max as well. self.metrics.log_dict( { EPISODE_LEN_MIN: length, EPISODE_RETURN_MIN: ret, }, reduce="min", window=win, ) self.metrics.log_dict( { EPISODE_LEN_MAX: length, EPISODE_RETURN_MAX: ret, }, reduce="max", window=win, ) @staticmethod def _prune_zero_len_sa_episodes(episode: MultiAgentEpisode): for agent_id, agent_eps in episode.agent_episodes.copy().items(): if not agent_eps: del episode.agent_episodes[agent_id] @Deprecated( new="MultiAgentEnvRunner.get_state(components='rl_module')", error=False, ) def get_weights(self, modules=None): rl_module_state = self.get_state(components=COMPONENT_RL_MODULE)[ COMPONENT_RL_MODULE ] return rl_module_state @Deprecated(new="MultiAgentEnvRunner.set_state()", error=False) def set_weights( self, weights: ModelWeights, global_vars: Optional[Dict] = None, weights_seq_no: int = 0, ) -> None: assert global_vars is None return self.set_state( { COMPONENT_RL_MODULE: weights, WEIGHTS_SEQ_NO: weights_seq_no, } )
MultiAgentEnvRunner
python
Textualize__textual
src/textual/worker.py
{ "start": 1663, "end": 2310 }
class ____(enum.Enum): """A description of the worker's current state.""" PENDING = 1 """Worker is initialized, but not running.""" RUNNING = 2 """Worker is running.""" CANCELLED = 3 """Worker is not running, and was cancelled.""" ERROR = 4 """Worker is not running, and exited with an error.""" SUCCESS = 5 """Worker is not running, and completed successfully.""" ResultType = TypeVar("ResultType") WorkType: TypeAlias = Union[ Callable[[], Coroutine[None, None, ResultType]], Callable[[], ResultType], Awaitable[ResultType], ] """Type used for [workers](/guide/workers/)."""
WorkerState
python
apache__airflow
airflow-core/src/airflow/dag_processing/bundles/manager.py
{ "start": 1580, "end": 1783 }
class ____(BaseModel): """Schema defining the user-specified configuration for a DAG bundle.""" name: str classpath: str kwargs: dict team_name: str | None = None
_ExternalBundleConfig
python
pytorch__pytorch
tools/test/heuristics/test_heuristics.py
{ "start": 1818, "end": 3231 }
class ____(TestTD): @mock.patch( HEURISTIC_CLASS + "_get_historical_test_class_correlations", return_value=gen_historical_class_failures(), ) @mock.patch( HEURISTIC_CLASS + "query_changed_files", return_value=["file1"], ) def test_get_prediction_confidence( self, historical_class_failures: dict[str, dict[str, float]], changed_files: list[str], ) -> None: tests_to_prioritize = ALL_TESTS heuristic = HistoricalClassFailurCorrelation() test_prioritizations = heuristic.get_prediction_confidence(tests_to_prioritize) expected = TestPrioritizations( tests_to_prioritize, { TestRun("test1::classA"): 0.25, TestRun("test2::classA"): 0.1, TestRun("test5::classB"): 0.05, TestRun("test1", excluded=["classA"]): 0.0, TestRun("test2", excluded=["classA"]): 0.0, TestRun("test3"): 0.0, TestRun("test4"): 0.0, TestRun("test5", excluded=["classB"]): 0.0, TestRun("test6"): 0.0, TestRun("test7"): 0.0, TestRun("test8"): 0.0, }, ) self.assert_test_scores_almost_equal( test_prioritizations._test_scores, expected._test_scores )
TestHistoricalClassFailureCorrelation
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/inconsistentConstructor1.py
{ "start": 372, "end": 512 }
class ____(Parent2): # This should generate an error if reportInconsistentConstructor is enabled. def __new__(cls, b: str): ...
Child2
python
sphinx-doc__sphinx
sphinx/ext/autosummary/__init__.py
{ "start": 3433, "end": 3814 }
class ____(nodes.comment): pass def autosummary_toc_visit_html(self: nodes.NodeVisitor, node: autosummary_toc) -> None: """Hide autosummary toctree list in HTML output.""" raise nodes.SkipNode def autosummary_noop(self: nodes.NodeVisitor, node: Node) -> None: pass # -- autosummary_table node ----------------------------------------------------
autosummary_toc
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_warning.py
{ "start": 2405, "end": 5107 }
class ____: @pytest.mark.parametrize( ("query_params", "expected_total_entries", "expected_messages"), [ ({}, 3, [DAG1_MESSAGE, DAG2_MESSAGE, DAG3_MESSAGE]), ({"dag_id": DAG1_ID}, 1, [DAG1_MESSAGE]), ({"warning_type": DAG_WARNING_TYPE}, 3, [DAG1_MESSAGE, DAG2_MESSAGE, DAG3_MESSAGE]), ({"limit": 1, "order_by": "message"}, 3, [DAG1_MESSAGE]), ({"limit": 1, "offset": 1, "order_by": "message"}, 3, [DAG2_MESSAGE]), ({"limit": 1, "offset": 2, "order_by": "dag_id"}, 3, [DAG3_MESSAGE]), ({"limit": 1, "offset": 2, "order_by": "-dag_id"}, 3, [DAG1_MESSAGE]), ({"limit": 1, "order_by": "timestamp"}, 3, [DAG1_MESSAGE]), ({"limit": 1, "order_by": "-timestamp"}, 3, [DAG3_MESSAGE]), ({"order_by": "timestamp"}, 3, [DAG1_MESSAGE, DAG2_MESSAGE, DAG3_MESSAGE]), ({"order_by": "-timestamp"}, 3, [DAG3_MESSAGE, DAG2_MESSAGE, DAG1_MESSAGE]), ({"order_by": "dag_id"}, 3, [DAG1_MESSAGE, DAG2_MESSAGE, DAG3_MESSAGE]), ({"order_by": "-dag_id"}, 3, [DAG3_MESSAGE, DAG2_MESSAGE, DAG1_MESSAGE]), ], ) def test_get_dag_warnings(self, test_client, query_params, expected_total_entries, expected_messages): with assert_queries_count(3): response = test_client.get("/dagWarnings", params=query_params) assert response.status_code == 200 response_json = response.json() assert response_json["total_entries"] == expected_total_entries assert len(response_json["dag_warnings"]) == len(expected_messages) assert [dag_warning["message"] for dag_warning in response_json["dag_warnings"]] == expected_messages for dag_warning in response_json["dag_warnings"]: assert "dag_display_name" in dag_warning dag_id = dag_warning["dag_id"] assert dag_warning["dag_display_name"] == expected_display_names[dag_id] def test_should_respond_401(self, unauthenticated_test_client): response = unauthenticated_test_client.get("/dagWarnings", params={}) assert response.status_code == 401 def test_should_respond_403(self, unauthorized_test_client): response = unauthorized_test_client.get("/dagWarnings", params={}) assert response.status_code == 403 def test_get_dag_warnings_bad_request(self, test_client): response = test_client.get("/dagWarnings", params={"warning_type": "invalid"}) response_json = response.json() assert response.status_code == 422 assert response_json["detail"][0]["msg"] == "Input should be 'asset conflict' or 'non-existent pool'"
TestGetDagWarnings
python
pennersr__django-allauth
allauth/socialaccount/providers/microsoft/provider.py
{ "start": 242, "end": 372 }
class ____(ProviderAccount): def get_avatar_url(self): return self.account.extra_data.get("photo")
MicrosoftGraphAccount
python
sympy__sympy
sympy/physics/quantum/dagger.py
{ "start": 154, "end": 2484 }
class ____(adjoint): """General Hermitian conjugate operation. Explanation =========== Take the Hermetian conjugate of an argument [1]_. For matrices this operation is equivalent to transpose and complex conjugate [2]_. Parameters ========== arg : Expr The SymPy expression that we want to take the dagger of. evaluate : bool Whether the resulting expression should be directly evaluated. Examples ======== Daggering various quantum objects: >>> from sympy.physics.quantum.dagger import Dagger >>> from sympy.physics.quantum.state import Ket, Bra >>> from sympy.physics.quantum.operator import Operator >>> Dagger(Ket('psi')) <psi| >>> Dagger(Bra('phi')) |phi> >>> Dagger(Operator('A')) Dagger(A) Inner and outer products:: >>> from sympy.physics.quantum import InnerProduct, OuterProduct >>> Dagger(InnerProduct(Bra('a'), Ket('b'))) <b|a> >>> Dagger(OuterProduct(Ket('a'), Bra('b'))) |b><a| Powers, sums and products:: >>> A = Operator('A') >>> B = Operator('B') >>> Dagger(A*B) Dagger(B)*Dagger(A) >>> Dagger(A+B) Dagger(A) + Dagger(B) >>> Dagger(A**2) Dagger(A)**2 Dagger also seamlessly handles complex numbers and matrices:: >>> from sympy import Matrix, I >>> m = Matrix([[1,I],[2,I]]) >>> m Matrix([ [1, I], [2, I]]) >>> Dagger(m) Matrix([ [ 1, 2], [-I, -I]]) References ========== .. [1] https://en.wikipedia.org/wiki/Hermitian_adjoint .. [2] https://en.wikipedia.org/wiki/Hermitian_transpose """ @property def kind(self): """Find the kind of a dagger of something (just the kind of the something).""" return self.args[0].kind def __new__(cls, arg, evaluate=True): if hasattr(arg, 'adjoint') and evaluate: return arg.adjoint() elif hasattr(arg, 'conjugate') and hasattr(arg, 'transpose') and evaluate: return arg.conjugate().transpose() return Expr.__new__(cls, sympify(arg)) adjoint.__name__ = "Dagger" adjoint._sympyrepr = lambda a, b: "Dagger(%s)" % b._print(a.args[0])
Dagger
python
doocs__leetcode
solution/1100-1199/1110.Delete Nodes And Return Forest/Solution.py
{ "start": 192, "end": 833 }
class ____: def delNodes( self, root: Optional[TreeNode], to_delete: List[int] ) -> List[TreeNode]: def dfs(root: Optional[TreeNode]) -> Optional[TreeNode]: if root is None: return None root.left, root.right = dfs(root.left), dfs(root.right) if root.val not in s: return root if root.left: ans.append(root.left) if root.right: ans.append(root.right) return None s = set(to_delete) ans = [] if dfs(root): ans.append(root) return ans
Solution
python
PyCQA__pylint
tests/pyreverse/functional/class_diagrams/property_decorator/property_decorator.py
{ "start": 461, "end": 895 }
class ____: """Test class for property decorators without annotated return type""" def __init__(self): self._x = 0 @property def x(self): """This is a getter for x""" return self._x @x.setter def x(self, value): """This is a setter for x""" self._x = value @x.deleter def x(self): """This is a deleter for x""" del self._x
NonAnnotatedPropertyTest
python
python-openxml__python-docx
src/docx/oxml/shape.py
{ "start": 7055, "end": 8070 }
class ____(BaseOxmlElement): """``<pic:spPr>`` element, specifies size and shape of picture container.""" xfrm = ZeroOrOne( "a:xfrm", successors=( "a:custGeom", "a:prstGeom", "a:ln", "a:effectLst", "a:effectDag", "a:scene3d", "a:sp3d", "a:extLst", ), ) @property def cx(self): """Shape width as an instance of Emu, or None if not present.""" xfrm = self.xfrm if xfrm is None: return None return xfrm.cx @cx.setter def cx(self, value): xfrm = self.get_or_add_xfrm() xfrm.cx = value @property def cy(self): """Shape height as an instance of Emu, or None if not present.""" xfrm = self.xfrm if xfrm is None: return None return xfrm.cy @cy.setter def cy(self, value): xfrm = self.get_or_add_xfrm() xfrm.cy = value
CT_ShapeProperties
python
bokeh__bokeh
src/bokeh/document/json.py
{ "start": 2796, "end": 3033 }
class ____(TypedDict): version: NotRequired[str] title: NotRequired[str] defs: NotRequired[list[ModelDef]] config: NotRequired[ModelDef] roots: list[ModelRep] callbacks: NotRequired[dict[str, list[ModelRep]]]
DocJson
python
realpython__materials
python-use-global-variable-in-function/account_class.py
{ "start": 0, "end": 1221 }
class ____: def __init__(self, balance=0): self.balance = balance def deposit(self, amount): self.balance += amount print(f"Successful deposit: +${amount:,.2f}") def withdraw(self, amount): if self.balance - amount > 0: self.balance -= amount print(f"Successful withdrawal: -${amount:,.2f}") else: print("Not enough funds for this transaction") def main(): account = Account() while True: operation = input( "What would you like to do?\n" " d) deposit " " w) withdraw " " b) balance " " q) quit\n" "> " ) if operation in "dD": amount = float(input("Enter the deposit amount: ")) account.deposit(amount) elif operation in "wW": amount = float(input("Enter the withdrawal amount: ")) account.withdraw(amount) elif operation in "bB": print(f"Current balance: ${account.balance:,.2f}") elif operation in "qQ": print("Goodbye!") break else: print("Invalid operation. Please try again.") main()
Account
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 93520, "end": 95654 }
class ____(Operation): def compute_output_spec(self, abs_, angle): return KerasTensor(shape=abs_.shape) def call(self, abs_, angle): return _polar(abs_, angle) @keras_export(["keras.ops.polar", "keras.ops.nn.polar"]) def polar(abs_, angle): """Constructs a complex tensor whose elements are Cartesian coordinates corresponding to the polar coordinates with absolute value `abs` and angle `angle`. The operation is numerically equivalent to `torch.polar()`. It is not equivalent to `scipy.lingalg.polar()` which performs Singular Value Decomposition. Given the magnitude (`abs_`) and angle (`angle`), this function computes the corresponding complex number in the form of `real + imaginary * 1j`, where: - `real = abs_ * cos(angle)` - `imaginary = abs_ * sin(angle)` Args: abs_: The magnitude (absolute value) of the complex number. angle: The angle (in radians) of the complex number. Returns: A complex number (or array of complex numbers) with the same shape as `abs_` and `angle`. Example: >>> abs_ = keras.random.normal((1, 2)) >>> angle = keras.random.normal((1, 2)) >>> keras.ops.nn.polar(abs_, angle).shape (1, 2) >>> keras.ops.nn.polar(abs_, angle) Array([[0.63185346-0.59370506j, 0.48960376-0.31677645j]], dtype=complex64) """ if any_symbolic_tensors((abs_, angle)): return Polar().symbolic_call(abs_, angle) return _polar(abs_, angle) def _polar(abs_, angle): """Internal implementation of the polar function. Args: abs_: The magnitude (absolute value) of the complex number. angle: The angle (in radians) of the complex number. Returns: A complex number (or array of complex numbers) with the same shape as `abs_` and `angle`. """ abs_ = backend.convert_to_tensor(abs_) angle = backend.convert_to_tensor(angle) real = abs_ * backend.numpy.cos(angle) imaginary = abs_ * backend.numpy.sin(angle) result = backend.math._get_complex_tensor_from_tuple((real, imaginary)) return result
Polar
python
getsentry__sentry
src/sentry/users/api/serializers/user.py
{ "start": 1656, "end": 1718 }
class ____(TypedDict): slug: str name: str
_Organization
python
Textualize__textual
tests/test_binding_inheritance.py
{ "start": 18096, "end": 18315 }
class ____( Static, can_focus=True, inherit_bindings=False ): """A widget that can receive focus but has empty bindings and doesn't inherit bindings.""" BINDINGS = []
FocusableWidgetWithEmptyBindingsNoInherit
python
realpython__materials
tic-tac-toe-ai-python/source_code_step_3/tic-tac-toe/frontends/console/args.py
{ "start": 279, "end": 1124 }
class ____(NamedTuple): player1: Player player2: Player starting_mark: Mark def parse_args() -> Args: parser = argparse.ArgumentParser() parser.add_argument( "-X", dest="player_x", choices=PLAYER_CLASSES.keys(), default="human", ) parser.add_argument( "-O", dest="player_o", choices=PLAYER_CLASSES.keys(), default="random", ) parser.add_argument( "--starting", dest="starting_mark", choices=Mark, type=Mark, default="X", ) args = parser.parse_args() player1 = PLAYER_CLASSES[args.player_x](Mark("X")) player2 = PLAYER_CLASSES[args.player_o](Mark("O")) if args.starting_mark == "O": player1, player2 = player2, player1 return Args(player1, player2, args.starting_mark)
Args
python
getsentry__sentry
src/sentry/api/serializers/models/project.py
{ "start": 25664, "end": 25740 }
class ____(TypedDict): version: str dateFinished: datetime
_DeployDict
python
tensorflow__tensorflow
tensorflow/python/data/util/sparse_test.py
{ "start": 11777, "end": 15567 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times(test_base.default_test_combinations(), _test_any_sparse_combinations())) def testAnySparse(self, classes_fn, expected): classes = classes_fn() self.assertEqual(sparse.any_sparse(classes), expected) def assertShapesEqual(self, a, b): for a, b in zip(nest.flatten(a), nest.flatten(b)): self.assertEqual(a.ndims, b.ndims) if a.ndims is None: continue for c, d in zip(a.as_list(), b.as_list()): self.assertEqual(c, d) @combinations.generate( combinations.times(test_base.default_test_combinations(), _test_as_dense_shapes_combinations())) def testAsDenseShapes(self, types_fn, classes_fn, expected_fn): types = types_fn() classes = classes_fn() expected = expected_fn() self.assertShapesEqual(sparse.as_dense_shapes(types, classes), expected) @combinations.generate( combinations.times(test_base.default_test_combinations(), _test_as_dense_types_combinations())) def testAsDenseTypes(self, types_fn, classes_fn, expected_fn): types = types_fn() classes = classes_fn() expected = expected_fn() self.assertEqual(sparse.as_dense_types(types, classes), expected) @combinations.generate( combinations.times(test_base.default_test_combinations(), _test_get_classes_combinations())) def testGetClasses(self, classes_fn, expected_fn): classes = classes_fn() expected = expected_fn() self.assertEqual(sparse.get_classes(classes), expected) def assertSparseValuesEqual(self, a, b): if not isinstance(a, sparse_tensor.SparseTensor): self.assertFalse(isinstance(b, sparse_tensor.SparseTensor)) self.assertEqual(a, b) return self.assertTrue(isinstance(b, sparse_tensor.SparseTensor)) with self.cached_session(): self.assertAllEqual(a.eval().indices, self.evaluate(b).indices) self.assertAllEqual(a.eval().values, self.evaluate(b).values) self.assertAllEqual(a.eval().dense_shape, self.evaluate(b).dense_shape) @combinations.generate( combinations.times(test_base.graph_only_combinations(), _test_serialize_deserialize_combinations())) def testSerializeDeserialize(self, input_fn): test_case = input_fn() classes = sparse.get_classes(test_case) shapes = nest.map_structure(lambda _: tensor_shape.TensorShape(None), classes) types = nest.map_structure(lambda _: dtypes.int32, classes) actual = sparse.deserialize_sparse_tensors( sparse.serialize_sparse_tensors(test_case), types, shapes, sparse.get_classes(test_case)) nest.assert_same_structure(test_case, actual) for a, e in zip(nest.flatten(actual), nest.flatten(test_case)): self.assertSparseValuesEqual(a, e) @combinations.generate( combinations.times(test_base.graph_only_combinations(), _test_serialize_many_deserialize_combinations())) def testSerializeManyDeserialize(self, input_fn): test_case = input_fn() classes = sparse.get_classes(test_case) shapes = nest.map_structure(lambda _: tensor_shape.TensorShape(None), classes) types = nest.map_structure(lambda _: dtypes.int32, classes) actual = sparse.deserialize_sparse_tensors( sparse.serialize_many_sparse_tensors(test_case), types, shapes, sparse.get_classes(test_case)) nest.assert_same_structure(test_case, actual) for a, e in zip(nest.flatten(actual), nest.flatten(test_case)): self.assertSparseValuesEqual(a, e) if __name__ == "__main__": test.main()
SparseTest
python
PrefectHQ__prefect
src/prefect/concurrency/_asyncio.py
{ "start": 1079, "end": 8424 }
class ____(TimeoutError): """Raised when acquiring a concurrency slot times out.""" logger: logging.Logger = get_logger("concurrency") async def aacquire_concurrency_slots( names: list[str], slots: int, mode: Literal["concurrency", "rate_limit"] = "concurrency", timeout_seconds: Optional[float] = None, max_retries: Optional[int] = None, strict: bool = False, ) -> list[MinimalConcurrencyLimitResponse]: service = ConcurrencySlotAcquisitionService.instance(frozenset(names)) future = service.send((slots, mode, timeout_seconds, max_retries)) try: response = await asyncio.wrap_future(future) except TimeoutError as timeout: raise AcquireConcurrencySlotTimeoutError( f"Attempt to acquire concurrency slots timed out after {timeout_seconds} second(s)" ) from timeout except Exception as exc: raise ConcurrencySlotAcquisitionError( f"Unable to acquire concurrency slots on {names!r}" ) from exc retval = _response_to_minimal_concurrency_limit_response(response) if not retval: if strict: raise ConcurrencySlotAcquisitionError( f"Concurrency limits {names!r} must be created before acquiring slots" ) try: logger = get_run_logger() except Exception: pass else: logger.warning( f"Concurrency limits {names!r} do not exist - skipping acquisition." ) return retval async def aacquire_concurrency_slots_with_lease( names: list[str], slots: int, mode: Literal["concurrency", "rate_limit"] = "concurrency", timeout_seconds: Optional[float] = None, max_retries: Optional[int] = None, lease_duration: float = 300, strict: bool = False, holder: "Optional[ConcurrencyLeaseHolder]" = None, suppress_warnings: bool = False, ) -> ConcurrencyLimitWithLeaseResponse: service = ConcurrencySlotAcquisitionWithLeaseService.instance(frozenset(names)) future = service.send( (slots, mode, timeout_seconds, max_retries, lease_duration, strict, holder) ) try: response = await asyncio.wrap_future(future) except TimeoutError as timeout: raise AcquireConcurrencySlotTimeoutError( f"Attempt to acquire concurrency slots timed out after {timeout_seconds} second(s)" ) from timeout except Exception as exc: raise ConcurrencySlotAcquisitionError( f"Unable to acquire concurrency slots on {names!r}" ) from exc retval = ConcurrencyLimitWithLeaseResponse.model_validate(response.json()) if not retval.limits: if strict: raise ConcurrencySlotAcquisitionError( f"Concurrency limits {names!r} must be created before acquiring slots" ) else: try: # Use a run logger if available task_logger = get_run_logger() except Exception: task_logger = get_logger("concurrency") log_level = logging.DEBUG if suppress_warnings else logging.WARNING task_logger.log( log_level, f"Concurrency limits {names!r} do not exist - skipping acquisition.", ) return retval async def arelease_concurrency_slots( names: list[str], slots: int, occupancy_seconds: float ) -> list[MinimalConcurrencyLimitResponse]: async with get_client() as client: response = await client.release_concurrency_slots( names=names, slots=slots, occupancy_seconds=occupancy_seconds ) return _response_to_minimal_concurrency_limit_response(response) async def arelease_concurrency_slots_with_lease( lease_id: UUID, ) -> None: async with get_client() as client: await client.release_concurrency_slots_with_lease(lease_id=lease_id) def _response_to_minimal_concurrency_limit_response( response: httpx.Response, ) -> list[MinimalConcurrencyLimitResponse]: return [ MinimalConcurrencyLimitResponse.model_validate(obj_) for obj_ in response.json() ] @asynccontextmanager async def concurrency( names: str | list[str], occupy: int = 1, timeout_seconds: Optional[float] = None, max_retries: Optional[int] = None, lease_duration: float = 300, strict: bool = False, holder: "Optional[ConcurrencyLeaseHolder]" = None, suppress_warnings: bool = False, ) -> AsyncGenerator[None, None]: """ Internal version of the `concurrency` context manager. The public version is located in `prefect.concurrency.asyncio`. Args: names: The names of the concurrency limits to acquire slots from. occupy: The number of slots to acquire and hold from each limit. timeout_seconds: The number of seconds to wait for the slots to be acquired before raising a `TimeoutError`. A timeout of `None` will wait indefinitely. max_retries: The maximum number of retries to acquire the concurrency slots. lease_duration: The duration of the lease for the acquired slots in seconds. strict: A boolean specifying whether to raise an error if the concurrency limit does not exist. Defaults to `False`. holder: A dictionary containing information about the holder of the concurrency slots. Typically includes 'type' and 'id' keys. Raises: TimeoutError: If the slots are not acquired within the given timeout. ConcurrencySlotAcquisitionError: If the concurrency limit does not exist and `strict` is `True`. Example: A simple example of using the async `concurrency` context manager: ```python from prefect.concurrency.asyncio import concurrency async def resource_heavy(): async with concurrency("test", occupy=1): print("Resource heavy task") async def main(): await resource_heavy() ``` """ if not names: yield return names = names if isinstance(names, list) else [names] response = await aacquire_concurrency_slots_with_lease( names=names, slots=occupy, timeout_seconds=timeout_seconds, max_retries=max_retries, lease_duration=lease_duration, strict=strict, holder=holder, suppress_warnings=suppress_warnings, ) emitted_events = emit_concurrency_acquisition_events(response.limits, occupy) try: async with amaintain_concurrency_lease( response.lease_id, lease_duration, raise_on_lease_renewal_failure=strict, suppress_warnings=suppress_warnings, ): yield finally: try: await arelease_concurrency_slots_with_lease( lease_id=response.lease_id, ) except anyio.get_cancelled_exc_class(): # The task was cancelled before it could release the lease. Add the # lease ID to the cleanup list so it can be released when the # concurrency context is exited. if ctx := ConcurrencyContext.get(): ctx.cleanup_lease_ids.append(response.lease_id) emit_concurrency_release_events(response.limits, occupy, emitted_events)
AcquireConcurrencySlotTimeoutError
python
ray-project__ray
python/ray/_private/test_utils.py
{ "start": 36152, "end": 36955 }
class ____(Queue): def __init__(self, maxsize: int = 0, actor_options: Optional[Dict] = None) -> None: actor_options = actor_options or {} self.maxsize = maxsize self.actor = ( ray.remote(_BatchQueueActor).options(**actor_options).remote(self.maxsize) ) def get_batch( self, batch_size: int = None, total_timeout: Optional[float] = None, first_timeout: Optional[float] = None, ) -> List[Any]: """Gets batch of items from the queue and returns them in a list in order. Raises: Empty: if the queue does not contain the desired number of items """ return ray.get( self.actor.get_batch.remote(batch_size, total_timeout, first_timeout) )
BatchQueue
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/assertsql.py
{ "start": 861, "end": 1843 }
class ____(SQLMatchRule): def __init__(self, statement, params=None, consume_statement=True): self.statement = statement self.params = params self.consume_statement = consume_statement def process_statement(self, execute_observed): stmt = execute_observed.statements[0] if self.statement != stmt.statement or ( self.params is not None and self.params != stmt.parameters ): self.consume_statement = True self.errormessage = ( "Testing for exact SQL %s parameters %s received %s %s" % ( self.statement, self.params, stmt.statement, stmt.parameters, ) ) else: execute_observed.statements.pop(0) self.is_consumed = True if not execute_observed.statements: self.consume_statement = True
CursorSQL
python
spack__spack
lib/spack/spack/vendor/ruamel/yaml/comments.py
{ "start": 15906, "end": 20585 }
class ____(MutableSliceableSequence, list, CommentedBase): # type: ignore __slots__ = (Comment.attrib, '_lst') def __init__(self, *args, **kw): # type: (Any, Any) -> None list.__init__(self, *args, **kw) def __getsingleitem__(self, idx): # type: (Any) -> Any return list.__getitem__(self, idx) def __setsingleitem__(self, idx, value): # type: (Any, Any) -> None # try to preserve the scalarstring type if setting an existing key to a new value if idx < len(self): if ( isinstance(value, str) and not isinstance(value, ScalarString) and isinstance(self[idx], ScalarString) ): value = type(self[idx])(value) list.__setitem__(self, idx, value) def __delsingleitem__(self, idx=None): # type: (Any) -> Any list.__delitem__(self, idx) self.ca.items.pop(idx, None) # might not be there -> default value for list_index in sorted(self.ca.items): if list_index < idx: continue self.ca.items[list_index - 1] = self.ca.items.pop(list_index) def __len__(self): # type: () -> int return list.__len__(self) def insert(self, idx, val): # type: (Any, Any) -> None """the comments after the insertion have to move forward""" list.insert(self, idx, val) for list_index in sorted(self.ca.items, reverse=True): if list_index < idx: break self.ca.items[list_index + 1] = self.ca.items.pop(list_index) def extend(self, val): # type: (Any) -> None list.extend(self, val) def __eq__(self, other): # type: (Any) -> bool return list.__eq__(self, other) def _yaml_add_comment(self, comment, key=NoComment): # type: (Any, Optional[Any]) -> None if key is not NoComment: self.yaml_key_comment_extend(key, comment) else: self.ca.comment = comment def _yaml_add_eol_comment(self, comment, key): # type: (Any, Any) -> None self._yaml_add_comment(comment, key=key) def _yaml_get_columnX(self, key): # type: (Any) -> Any return self.ca.items[key][0].start_mark.column def _yaml_get_column(self, key): # type: (Any) -> Any column = None sel_idx = None pre, post = key - 1, key + 1 if pre in self.ca.items: sel_idx = pre elif post in self.ca.items: sel_idx = post else: # self.ca.items is not ordered for row_idx, _k1 in enumerate(self): if row_idx >= key: break if row_idx not in self.ca.items: continue sel_idx = row_idx if sel_idx is not None: column = self._yaml_get_columnX(sel_idx) return column def _yaml_get_pre_comment(self): # type: () -> Any pre_comments = [] # type: List[Any] if self.ca.comment is None: self.ca.comment = [None, pre_comments] else: pre_comments = self.ca.comment[1] return pre_comments def _yaml_clear_pre_comment(self): # type: () -> Any pre_comments = [] # type: List[Any] if self.ca.comment is None: self.ca.comment = [None, pre_comments] else: self.ca.comment[1] = pre_comments return pre_comments def __deepcopy__(self, memo): # type: (Any) -> Any res = self.__class__() memo[id(self)] = res for k in self: res.append(copy.deepcopy(k, memo)) self.copy_attributes(res, memo=memo) return res def __add__(self, other): # type: (Any) -> Any return list.__add__(self, other) def sort(self, key=None, reverse=False): # type: (Any, bool) -> None if key is None: tmp_lst = sorted(zip(self, range(len(self))), reverse=reverse) list.__init__(self, [x[0] for x in tmp_lst]) else: tmp_lst = sorted( zip(map(key, list.__iter__(self)), range(len(self))), reverse=reverse ) list.__init__(self, [list.__getitem__(self, x[1]) for x in tmp_lst]) itm = self.ca.items self.ca._items = {} for idx, x in enumerate(tmp_lst): old_index = x[1] if old_index in itm: self.ca.items[idx] = itm[old_index] def __repr__(self): # type: () -> Any return list.__repr__(self)
CommentedSeq
python
joke2k__faker
faker/providers/job/zh_TW/__init__.py
{ "start": 156, "end": 8742 }
class ____(BaseProvider): jobs = [ "BIOS工程師", "CAD/CAM工程師", "CNC機台操作人員", "CNC電腦程式編排人員", "EMC/電子安規工程師", "FAE工程師", "IC佈局工程師", "IC封裝/測試工程師", "ISO/品保人員", "Internet程式設計師", "LCD製程工程師", "LCD設備工程師", "MES工程師", "MIS程式設計師", "MIS/網管主管", "OP/旅行社人員", "PCB佈線工程師", "PCB技術人員", "RF通訊工程師", "SMT工程師", "一般動物飼育工作者", "不動產產權審核/估價師", "不動產經紀人", "不動產/商場開發人員", "中等學校教師", "中醫師", "中餐廚師", "主持人", "主管特別助理", "主辦會計", "人力資源主管", "人力資源人員", "人力資源助理", "人力/外勞仲介", "代書/地政士", "估算人員", "作曲家", "作業員/包裝員", "保全人員/警衛", "保全技術人員", "保安服務工作", "保稅人員", "保險業務/經紀人", "倉儲物流人員", "倉管", "催收人員", "傳播媒體企劃人員", "傳銷人員", "儲備幹部", "光學工程師", "光電工程師", "光電工程研發主管", "內業工程師", "公共衛生人員", "公共衛生醫師", "公家機關人員", "券商後線人員", "副教授", "加油員", "助教", "助理工程師", "助理教授", "勞工安全衛生管理人員", "勞工安全衛生管理師", "包裝設計", "化學工程研發人員", "化學研究員", "化工化學工程師", "升學補習班老師", "半導體工程師", "半導體製程工程師", "半導體設備工程師", "印前製作/印刷技術人員", "可靠度工程師", "吊車/起重機設備操作員", "呼吸治療師", "品牌宣傳及媒體公關", "品管/品保主管", "品管/品保工程師", "品管/檢驗人員", "哲學/歷史/政治研究人員", "售票/收銀人員", "商業設計", "商標/專利人員", "噴漆人員", "國內業務主管", "國內業務人員", "國外業務主管", "國外業務人員", "國小學校教師", "國貿人員", "圖書資料管理人員", "土地開發人員", "土木技師/土木工程師", "地勤人員", "地質與地球科學研究員", "塑膠射出技術人員", "塑膠模具技術人員", "塗裝技術人員", "壓鑄模具技術人員", "外務/快遞/送貨", "多媒體動畫設計師", "多媒體開發主管", "大樓管理員", "大貨車司機", "天文研究員", "太陽能技術工程師", "娛樂事業人員", "媒體公關/宣傳採買", "安全/衛生檢驗人員", "安心服務員", "安親班老師", "客戶服務主管", "客戶服務人員", "室內設計/裝潢人員", "家事服務人員", "家庭代工", "實驗化驗人員", "寵物美容專業人員", "專案業務主管", "專案管理主管", "專案管理師", "專科護理師", "導播", "導演", "導遊", "小客車司機", "小貨車司機", "居家服務督導員", "展場/櫥窗佈置人員", "工務人員/助理", "工商登記服務人員", "工地監工/主任", "工廠主管", "工業工程師/生產線規劃", "工業設計", "工程助理", "工程研發主管", "工程配管繪圖", "工讀生", "市場調查/市場分析", "平面設計/美編人員", "幼教班老師", "店長/賣場管理人員", "廠務", "廠務助理", "廣告AE業務人員", "廣告企劃主管", "廣告文案/企劃", "廣告設計", "建築師", "建築物清潔工", "建築物電力系統維修工", "建築設計/繪圖人員", "影片製作技術人員", "律師", "復建技術師", "微機電工程師", "心理學研究人員", "志工人員", "志願役軍官/士官/士兵", "應用科學研究員", "成本會計", "手工包裝工", "才藝類老師", "打版人員", "技術文件/說明書編譯", "按摩/推拿師", "排版人員", "採購主管", "採購人員", "採購助理", "推土機設備操作員", "播音/配音人員", "攝影助理", "攝影師", "放射性設備使用技術員", "救生員", "教保員", "教授", "教育訓練人員", "整體造型師", "數位IC設計工程師", "數學研究員", "數理補習班老師", "文件管理師", "文編/校對/文字工作者", "旅遊休閒類主管", "日式廚師", "日文翻譯/口譯人員", "星象占卜人員", "景觀設計師", "會計師", "服裝/皮包/鞋類設計", "木工", "材料研發人員", "板金技術員", "林木伐運工作者", "染整技術人員", "查帳/審計人員", "核保/保險內勤人員", "業務助理", "業務支援工程師", "樂器製造員", "模特兒", "機械加工技術人員", "機械工程師", "機械操作員", "機械裝配員", "機械設計/繪圖人員", "機構工程師", "機電技師/工程師", "櫃檯接待人員", "氣象研究員", "水保工程師", "水保技師", "水利工程師", "水產養殖工作者", "水電工", "水電工程師", "水電工程繪圖人員", "汽車美容人員", "汽車銷售人員", "汽車/機車引擎技術人員", "汽車/機車技術維修人員", "沖壓模具技術人員", "油漆工", "治療師", "法務人員", "法務助理", "法務/智財主管", "法律專業人員", "泥水小工", "泥水工", "洗碗人員", "活動企劃人員", "派報生/傳單派送", "消防員", "消防專業人員", "混凝土工", "清潔工", "測試人員", "演員", "演奏家", "演算法開發工程師", "焊接及切割技術員", "照顧指導員", "照顧服務員", "熱傳工程師", "燈光/音響師", "營建主管", "營建構造工", "營造工程師", "營運管理師", "營養師", "牙醫助理", "牙醫師", "物理治療師", "物理研究員", "物管/資材", "特殊工程師", "特殊教育教師", "特用化學工程師", "獸醫師", "珠寶及貴金屬技術員", "珠心算老師", "理賠人員", "環境工程師", "生命禮儀師", "生物學專業與研究", "生物科技研發人員", "生產技術/製程工程師", "生產管理主管", "生產設備工程師", "生管", "生管助理", "生鮮人員", "產品事業處主管", "產品企劃主管", "產品企劃開發人員", "產品售後技術服務", "產品管理師", "產品維修人員", "產品行銷人員", "病理藥理研究人員", "發包人員", "發行企劃/出版人員", "砌磚工", "研究人員", "研究助理", "硬體工程研發主管", "硬體測試工程師", "硬體研發工程師", "社工人員", "社會/人類學研究人員", "秘書", "稅務人員", "稽核人員", "空服員", "空調冷凍技術人員", "節目助理", "節目製作人員", "粉末冶金模具技術人員", "精密儀器製造工", "精密拋光技術人員", "系統整合/ERP專案師", "系統維護/操作人員", "紡織化學工程師", "紡織工務", "結構技師", "統計學研究員", "統計精算人員", "經營管理主管", "網站行銷企劃", "網路安全分析師", "網路管理工程師", "網頁設計師", "線切割技術員", "總務主管", "總務人員", "總幹事", "總機人員", "織品設計", "美姿美儀人員", "美容工作者", "美容類助理", "美甲彩繪師", "美療/芳療師", "美術老師", "美術設計", "美髮工作者", "美髮類助理", "翻譯/口譯人員", "聲學/噪音工程師", "聲樂家", "職能治療師", "股務人員", "自動控制工程師", "舞蹈指導與舞蹈家", "船務/押匯/報關人員", "船長/大副/船員", "花藝/園藝人員", "英文翻譯/口譯人員", "藝術品/珠寶鑑價/拍賣顧問", "藝術指導/總監", "藥學助理", "藥師", "融資/信用業務人員", "行政主管", "行政人員", "行政助理", "行銷企劃主管", "行銷企劃人員", "行銷企劃助理", "補習班導師/管理人員", "補習班老師", "製鞋類人員", "西餐廚師", "西點/蛋糕師", "視聽工程類人員", "計程車司機", "記帳/出納/一般會計", "記者/採編", "設計助理", "診所助理", "語文補習班老師", "語言治療師", "調酒師/吧台人員", "調音技術員", "講師", "護理師", "財務分析人員", "財務或會計主管", "財務會計助理", "資料庫管理人員", "資料輸入人員", "資材主管", "資源回收人員", "資訊助理人員", "資訊專業人員", "資訊設備管制人員", "車床人員", "車縫/裁縫類人員", "軟韌體測試工程師", "軟體專案主管", "軟體專案管理師", "軟體設計工程師", "農工業用機器裝修工", "農林業設備操作員", "農藝作物栽培工作者", "農藝/畜產研究人員", "通信測試維修人員", "通訊工程研發主管", "通訊軟體工程師", "通路開發人員", "連鎖店管理人員", "遊戲企劃人員", "運動教練", "運輸交通專業人員", "運輸物流類主管", "都市/交通規劃人員", "醫事放射師", "醫事檢驗師", "醫師", "醫療人員", "醫療器材研發工程師", "醫療從業人員", "醫療設備控制人員", "醫藥業務代表", "醫藥研發人員", "醫院行政管理人員", "量測/儀校人員", "金屬建材架構人員", "金融交易員", "金融專業主管", "金融承銷員", "金融營業員", "金融理財專員", "金融研究員", "銀行辦事員", "銑床人員", "鍋爐操作技術人員", "鐵路車輛駕駛員", "鑄造/鍛造模具技術人員", "門市/店員/專櫃人員", "防水施工人員", "防火及建築檢驗人員", "零件工程師", "雷射操作技術員", "電信及電力線路架設工", "電信/通訊系統工程師", "電台工作人員", "電子商務技術主管", "電子工程師", "電子產品系統工程師", "電子設備裝修工", "電機工程技術員", "電機技師/工程師", "電機裝修工", "電機設備裝配員", "電源工程師", "電玩程式設計師", "電腦系統分析師", "電腦組裝/測試", "電腦繪圖人員", "電腦補習班老師", "電話及電報機裝修工", "電話客服類人員", "電話行銷人員", "電鍍/表面處理技術人員", "韌體設計工程師", "音樂家", "音樂老師", "領班", "領隊", "類廚師", "類比IC設計工程師", "類講師", "顧問人員", "飛安人員", "飛機裝修工", "飛行機師", "食品研發人員", "食品衛生管理師", "飯店工作人員", "飯店餐廳主管", "餐廚助手", "餐飲服務生", "駐校代表", "驗光師", "麵包師", "麻醉醫師", ]
Provider
python
lepture__authlib
authlib/jose/rfc7518/jws_algs.py
{ "start": 3013, "end": 4592 }
class ____(JWSAlgorithm): """ECDSA using SHA algorithms for JWS. Available algorithms: - ES256: ECDSA using P-256 and SHA-256 - ES384: ECDSA using P-384 and SHA-384 - ES512: ECDSA using P-521 and SHA-512 """ SHA256 = hashes.SHA256 SHA384 = hashes.SHA384 SHA512 = hashes.SHA512 def __init__(self, name, curve, sha_type): self.name = name self.curve = curve self.description = f"ECDSA using {self.curve} and SHA-{sha_type}" self.hash_alg = getattr(self, f"SHA{sha_type}") def prepare_key(self, raw_data): key = ECKey.import_key(raw_data) if key["crv"] != self.curve: raise ValueError( f'Key for "{self.name}" not supported, only "{self.curve}" allowed' ) return key def sign(self, msg, key): op_key = key.get_op_key("sign") der_sig = op_key.sign(msg, ECDSA(self.hash_alg())) r, s = decode_dss_signature(der_sig) size = key.curve_key_size return encode_int(r, size) + encode_int(s, size) def verify(self, msg, sig, key): key_size = key.curve_key_size length = (key_size + 7) // 8 if len(sig) != 2 * length: return False r = decode_int(sig[:length]) s = decode_int(sig[length:]) der_sig = encode_dss_signature(r, s) try: op_key = key.get_op_key("verify") op_key.verify(der_sig, msg, ECDSA(self.hash_alg())) return True except InvalidSignature: return False
ECAlgorithm
python
joke2k__faker
faker/providers/ssn/es_MX/__init__.py
{ "start": 2493, "end": 6705 }
class ____(BaseProvider): """ A Faker provider for the Mexican SSN, RFC and CURP """ ssn_formats = ("###########",) def ssn(self) -> str: """ Mexican Social Security Number, as given by IMSS. :return: a random Mexican SSN """ office = self.random_int(min=1, max=99) birth_year = self.random_int(min=0, max=99) start_year = self.random_int(min=0, max=99) serial = self.random_int(min=1, max=9999) num = f"{office:02d}{start_year:02d}{birth_year:02d}{serial:04d}" check = ssn_checksum(map(int, num)) num += str(check) return num def curp(self) -> str: """ See https://es.wikipedia.org/wiki/Clave_%C3%9Anica_de_Registro_de_Poblaci%C3%B3n. :return: a random Mexican CURP (Unique Population Registry Code) """ birthday = self.generator.date_of_birth() first_surname = random.choice(ALPHABET) + random.choice(VOWELS) second_surname = random.choice(ALPHABET) given_name = random.choice(ALPHABET) name_initials = first_surname + second_surname + given_name birth_date = birthday.strftime("%y%m%d") gender = random.choice("HM") state = random.choice(STATES_RENAPO) first_surname_inside = random.choice(CONSONANTS) second_surname_inside = random.choice(CONSONANTS) given_name_inside = random.choice(ALPHABET) # This character is assigned to avoid duplicity # It's normally '0' for those born < 2000 # and 'A' for those born >= 2000 assigned_character = "0" if birthday.year < 2000 else "A" name_initials = FORBIDDEN_WORDS.get(name_initials, name_initials) random_curp = ( name_initials + birth_date + gender + state + first_surname_inside + second_surname_inside + given_name_inside + assigned_character ) random_curp += str(curp_checksum(random_curp)) return random_curp def rfc(self, natural: bool = True) -> str: """ See https://es.wikipedia.org/wiki/Registro_Federal_de_Contribuyentes :param natural: Whether to return the RFC of a natural person. Otherwise return the RFC of a legal person. :type natural: bool :return: a random Mexican RFC """ birthday = self.generator.date_of_birth() if natural: first_surname = random.choice(ALPHABET) + random.choice(VOWELS) second_surname = random.choice(ALPHABET) given_name = random.choice(ALPHABET) name_initials = first_surname + second_surname + given_name name_initials = FORBIDDEN_WORDS.get(name_initials, name_initials) else: name_initials = ( self.random_uppercase_letter() + self.random_uppercase_letter() + self.random_uppercase_letter() ) birth_date = birthday.strftime("%y%m%d") disambiguation_code = random.choice(ALPHANUMERIC) + random.choice(ALPHANUMERIC) + random.choice(ALPHANUMERIC) random_rfc = name_initials + birth_date + disambiguation_code return random_rfc def elector_code(self, gender: Optional[Literal["H", "M"]] = None) -> str: """ Unique elector code issued by INE (Instituto Nacional Electoral) in Mexico. :param gender: Gender for which to generate the code. Will be randomly selected if not provided. :type gender: str :return: a random INE elector code :sample: :sample: gender='M' """ if gender and gender not in ("H", "M"): raise ValueError("Gender must be 'H' or 'M'") gender = gender or random.choice(["H", "M"]) consonants = "".join(random.choices(CONSONANTS, k=6)) birthday = self.generator.date_of_birth() birth_date = birthday.strftime("%y%m%d") entity = random.randint(1, 33) disambiguation_code = "".join(random.choices(string.digits, k=3)) return f"{consonants}{birth_date}{entity:02d}{gender}{disambiguation_code}"
Provider
python
ansible__ansible
lib/ansible/_internal/_errors/_error_factory.py
{ "start": 116, "end": 3548 }
class ____(_errors.EventFactory): """Factory for creating `Event` instances from `BaseException` instances on the controller.""" def _get_msg(self, exception: BaseException) -> str | None: from ansible.errors import AnsibleError if not isinstance(exception, AnsibleError): return super()._get_msg(exception) return exception._original_message.strip() def _get_formatted_source_context(self, exception: BaseException) -> str | None: from ansible.errors import AnsibleError if not isinstance(exception, AnsibleError): return super()._get_formatted_source_context(exception) return exception._formatted_source_context def _get_help_text(self, exception: BaseException) -> str | None: from ansible.errors import AnsibleError if not isinstance(exception, AnsibleError): return super()._get_help_text(exception) return exception._help_text def _get_chain(self, exception: BaseException) -> _messages.EventChain | None: from ansible._internal._errors import _captured # avoid circular import due to AnsibleError import if isinstance(exception, _captured.AnsibleCapturedError): # a captured error provides its own cause event, it never has a normal __cause__ return _messages.EventChain( msg_reason=_errors.MSG_REASON_DIRECT_CAUSE, traceback_reason=f'The above {exception.context} exception was the direct cause of the following controller exception:', event=exception._event, ) return super()._get_chain(exception) def _follow_cause(self, exception: BaseException) -> bool: from ansible.errors import AnsibleError return not isinstance(exception, AnsibleError) or exception._include_cause_message def _get_cause(self, exception: BaseException) -> BaseException | None: # deprecated: description='remove support for orig_exc (deprecated in 2.23)' core_version='2.27' cause = super()._get_cause(exception) from ansible.errors import AnsibleError if not isinstance(exception, AnsibleError): return cause try: from ansible.utils.display import _display except Exception: # pylint: disable=broad-except # if config is broken, this can raise things other than ImportError _display = None if cause: if exception.orig_exc and exception.orig_exc is not cause and _display: _display.warning( msg=f"The `orig_exc` argument to `{type(exception).__name__}` was given, but differed from the cause given by `raise ... from`.", ) return cause if exception.orig_exc: if _display: # encourage the use of `raise ... from` before deprecating `orig_exc` _display.warning( msg=f"The `orig_exc` argument to `{type(exception).__name__}` was given without using `raise ... from orig_exc`.", ) return exception.orig_exc return None def _get_events(self, exception: BaseException) -> tuple[_messages.Event, ...] | None: if isinstance(exception, BaseExceptionGroup): return tuple(self._convert_exception(ex) for ex in exception.exceptions) return None
ControllerEventFactory
python
ansible__ansible
test/lib/ansible_test/_internal/cli/parsers/__init__.py
{ "start": 1741, "end": 2792 }
class ____(ControllerNamespaceParser, TypeParser): """Composite argument parser for the controller when delegation is supported.""" def get_stateless_parsers(self) -> dict[str, Parser]: """Return a dictionary of type names and type parsers.""" parsers: dict[str, Parser] = dict( origin=OriginParser(), docker=DockerParser(controller=True), ) if get_ci_provider().supports_core_ci_auth(): parsers.update( remote=PosixRemoteParser(controller=True), ) return parsers def document(self, state: DocumentationState) -> t.Optional[str]: """Generate and return documentation for this parser.""" section = '--controller options:' state.sections[section] = '' # place this section before the sections created by the parsers below state.sections[section] = '\n'.join([f' {name}:{parser.document(state)}' for name, parser in self.get_stateless_parsers().items()]) return None
DelegatedControllerParser
python
PrefectHQ__prefect
tests/input/test_actions.py
{ "start": 4377, "end": 4975 }
class ____: async def test_implicit_flow_run(self, flow_run_context): await create_flow_run_input(key="key", value="value") assert await read_flow_run_input(key="key") == "value" async def test_explicit_flow_run(self, flow_run): await create_flow_run_input(key="key", value="value", flow_run_id=flow_run.id) assert await read_flow_run_input(key="key", flow_run_id=flow_run.id) == "value" async def test_missing_key_returns_none(self, flow_run): assert await read_flow_run_input(key="missing", flow_run_id=flow_run.id) is None
TestReadFlowRunInput
python
pytorch__pytorch
torch/_dynamo/debug_utils.py
{ "start": 18852, "end": 22794 }
class ____: def __init__(self, save_dir: Optional[str] = None, *, pbar: Optional[tqdm] = None): # If None, we will generate random data instead. It's important # to natively support this use case as it will allow people to # share repros without including the real data, if the problem # reproduces even on random data. if save_dir is None: log.warning("no save_dir specified, will generate random data") self.store = ContentStoreReader(save_dir) if save_dir is not None else None self.args: list[Any] = [] self.pbar = pbar def storage( self, storage_hash: Optional[str], nbytes: int, *, device: Optional[torch._prims_common.DeviceLikeType] = None, dtype_hint: Optional[torch.dtype] = None, ) -> UntypedStorage: if self.pbar is not None: self.pbar.update(1) device = _device_or_default(device) # type: ignore[arg-type] dtype_hint = _dtype_or_default(dtype_hint) if self.store is not None and storage_hash is not None: try: storage = self.store.read_storage(storage_hash) except FileNotFoundError: pass else: if device != storage.device: log.warning("device mismatch: %s != %s", device, storage.device) # TODO: transfer it to the right device? But failing this # way would be very mysterious! Would have been better # not to store device in the serialized format... return storage warn_once(f"could not load {storage_hash}, generating random data instead") shape = (nbytes // dtype_hint.itemsize,) stride = _stride_or_default(None, shape=shape) return rand_strided(shape, stride, dtype_hint, device).untyped_storage() def tensor( self, storage: UntypedStorage, shape: torch._prims_common.ShapeType, stride: Optional[torch._prims_common.StrideType] = None, *, storage_offset: Optional[int] = None, dtype: Optional[torch.dtype] = None, requires_grad: Optional[bool] = None, is_leaf: Optional[bool] = None, **metadata: Any, ) -> torch.Tensor: stride = _stride_or_default(stride, shape=shape) storage_offset = _storage_offset_or_default(storage_offset) dtype = _dtype_or_default(dtype) is_leaf = _is_leaf_or_default(is_leaf) requires_grad = _requires_grad_or_default(requires_grad) t = torch.tensor( [], dtype=dtype, device=storage.device, requires_grad=requires_grad ) with torch.no_grad(): t.set_(storage, storage_offset, shape, stride) if not is_leaf: # Fake up some autograd history in a very naughty way with torch.enable_grad(): t = t.clone(memory_format=torch.preserve_format) with torch.no_grad(): t.set_(storage, storage_offset, shape, stride) assert torch._subclasses.meta_utils.safe_is_leaf(t) == is_leaf torch._utils.set_tensor_metadata(t, metadata) self.args.append(t) return t # for BC def symint(self, val: Any) -> Any: self.args.append(val) return val # for BC # Here is our writer strategy: # 1. We will stream all of the inputs to disk # 2. You can now deterministically randomize the inputs, or reload # the inputs from disk # 3. You can YOLO run the script without the inputs, in which case # we'll fill the inputs with random data and pray. This is the # legacy behavior, but it's also useful if you want to find out # if we're so broken even random inputs trigger it # 4. We could offer an in process "check if the randomized thing # works too" but this is delicate so we don't do it
InputReader
python
davidhalter__jedi
jedi/inference/gradual/base.py
{ "start": 9150, "end": 11251 }
class ____: def __init__(self, class_value, lazy_base_class, generics_manager): self._class_value = class_value self._lazy_base_class = lazy_base_class self._generics_manager = generics_manager @iterator_to_value_set def infer(self): for base in self._lazy_base_class.infer(): if isinstance(base, GenericClass): # Here we have to recalculate the given types. yield GenericClass.create_cached( base.inference_state, base._wrapped_value, TupleGenericManager(tuple(self._remap_type_vars(base))), ) else: if base.is_class_mixin(): # This case basically allows classes like `class Foo(List)` # to be used like `Foo[int]`. The generics are not # necessary and can be used later. yield GenericClass.create_cached( base.inference_state, base, self._generics_manager, ) else: yield base def _remap_type_vars(self, base): from jedi.inference.gradual.type_var import TypeVar filter = self._class_value.get_type_var_filter() for type_var_set in base.get_generics(): new = NO_VALUES for type_var in type_var_set: if isinstance(type_var, TypeVar): names = filter.get(type_var.py__name__()) new |= ValueSet.from_sets( name.infer() for name in names ) else: # Mostly will be type vars, except if in some cases # a concrete type will already be there. In that # case just add it to the value set. new |= ValueSet([type_var]) yield new def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self._lazy_base_class)
_LazyGenericBaseClass
python
huggingface__transformers
tests/models/pvt_v2/test_modeling_pvt_v2.py
{ "start": 1740, "end": 4960 }
class ____(ModelTesterMixin): def __init__( self, parent, batch_size=13, image_size=None, num_channels=3, num_encoder_blocks=4, depths=[2, 2, 2, 2], sr_ratios=[8, 4, 2, 1], hidden_sizes=[16, 32, 64, 128], downsampling_rates=[1, 4, 8, 16], num_attention_heads=[1, 2, 4, 8], out_indices=[0, 1, 2, 3], is_training=True, use_labels=True, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, initializer_range=0.02, num_labels=3, scope=None, ): self.parent = parent self.batch_size = batch_size self.image_size = 64 if image_size is None else image_size self.num_channels = num_channels self.num_encoder_blocks = num_encoder_blocks self.sr_ratios = sr_ratios self.depths = depths self.hidden_sizes = hidden_sizes self.downsampling_rates = downsampling_rates self.num_attention_heads = num_attention_heads self.is_training = is_training self.use_labels = use_labels self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.initializer_range = initializer_range self.out_indices = out_indices self.num_labels = num_labels self.scope = scope def prepare_config_and_inputs(self): pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) labels = None if self.use_labels: labels = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels) config = self.get_config() return config, pixel_values, labels def get_config(self): return PvtV2Config( image_size=self.image_size, num_channels=self.num_channels, num_encoder_blocks=self.num_encoder_blocks, depths=self.depths, sr_ratios=self.sr_ratios, hidden_sizes=self.hidden_sizes, num_attention_heads=self.num_attention_heads, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, initializer_range=self.initializer_range, out_indices=self.out_indices, ) def create_and_check_model(self, config, pixel_values, labels): model = PvtV2Model(config=config) model.to(torch_device) model.eval() result = model(pixel_values) self.parent.assertIsNotNone(result.last_hidden_state) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values, labels = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_torch
PvtV2ModelTester
python
protocolbuffers__protobuf
python/google/protobuf/descriptor.py
{ "start": 8073, "end": 10261 }
class ____(DescriptorBase): """Common class for descriptors that can be nested.""" def __init__( self, options, options_class_name, name, full_name, file, containing_type, serialized_start=None, serialized_end=None, serialized_options=None, ): """Constructor. Args: options: Protocol message options or None to use default message options. options_class_name (str): The class name of the above options. name (str): Name of this protocol message type. full_name (str): Fully-qualified name of this protocol message type, which will include protocol "package" name and the name of any enclosing types. containing_type: if provided, this is a nested descriptor, with this descriptor as parent, otherwise None. serialized_start: The start index (inclusive) in block in the file.serialized_pb that describes this descriptor. serialized_end: The end index (exclusive) in block in the file.serialized_pb that describes this descriptor. serialized_options: Protocol message serialized options or None. """ super(_NestedDescriptorBase, self).__init__( file, options, serialized_options, options_class_name ) self.name = name # TODO: Add function to calculate full_name instead of having it in # memory? self.full_name = full_name self.containing_type = containing_type self._serialized_start = serialized_start self._serialized_end = serialized_end def CopyToProto(self, proto): """Copies this to the matching proto in descriptor_pb2. Args: proto: An empty proto instance from descriptor_pb2. Raises: Error: If self couldn't be serialized, due to to few constructor arguments. """ if ( self.file is not None and self._serialized_start is not None and self._serialized_end is not None ): proto.ParseFromString( self.file.serialized_pb[self._serialized_start : self._serialized_end] ) else: raise Error('Descriptor does not contain serialization.')
_NestedDescriptorBase
python
dagster-io__dagster
python_modules/dagster/dagster/_grpc/types.py
{ "start": 7878, "end": 10952 }
class ____( NamedTuple( "_ExecuteStepArgs", [ # Deprecated, only needed for back-compat since it can be pulled from the DagsterRun ("job_origin", JobPythonOrigin), ("run_id", str), ("step_keys_to_execute", Optional[Sequence[str]]), ("instance_ref", Optional[InstanceRef]), ("retry_mode", Optional[RetryMode]), ("known_state", Optional[KnownExecutionState]), ("should_verify_step", Optional[bool]), ("print_serialized_events", bool), ], ) ): def __new__( cls, job_origin: JobPythonOrigin, run_id: str, step_keys_to_execute: Optional[Sequence[str]], instance_ref: Optional[InstanceRef] = None, retry_mode: Optional[RetryMode] = None, known_state: Optional[KnownExecutionState] = None, should_verify_step: Optional[bool] = None, print_serialized_events: Optional[bool] = None, ): return super().__new__( cls, job_origin=check.inst_param(job_origin, "job_origin", JobPythonOrigin), run_id=check.str_param(run_id, "run_id"), step_keys_to_execute=check.opt_nullable_sequence_param( step_keys_to_execute, "step_keys_to_execute", of_type=str ), instance_ref=check.opt_inst_param(instance_ref, "instance_ref", InstanceRef), retry_mode=check.opt_inst_param(retry_mode, "retry_mode", RetryMode), known_state=check.opt_inst_param(known_state, "known_state", KnownExecutionState), should_verify_step=check.opt_bool_param( should_verify_step, "should_verify_step", False ), print_serialized_events=check.opt_bool_param( print_serialized_events, "print_serialized_events", False ), ) def _get_compressed_args(self) -> str: # Compress, then base64 encode so we can pass it around as a str return base64.b64encode(zlib.compress(serialize_value(self).encode())).decode() def get_command_args(self, skip_serialized_namedtuple: bool = False) -> Sequence[str]: """Get the command args to run this step. If skip_serialized_namedtuple is True, then get_command_env should be used to pass the args to Click using an env var. """ return [ *_get_entry_point(self.job_origin), "api", "execute_step", *( ["--compressed-input-json", self._get_compressed_args()] if not skip_serialized_namedtuple else [] ), ] def get_command_env(self) -> Sequence[Mapping[str, str]]: """Get the env vars for overriding the Click args of this step. Used in conjuction with get_command_args(skip_serialized_namedtuple=True). """ return [ {"name": "DAGSTER_COMPRESSED_EXECUTE_STEP_ARGS", "value": self._get_compressed_args()}, ] @whitelist_for_serdes
ExecuteStepArgs
python
getsentry__sentry
src/sentry/analytics/events/groupowner_assignment.py
{ "start": 78, "end": 341 }
class ____(analytics.Event): organization_id: int project_id: int group_id: int new_assignment: bool user_id: int | None = None group_owner_type: int method: str | None = None analytics.register(GroupOwnerAssignment)
GroupOwnerAssignment
python
wandb__wandb
wandb/util.py
{ "start": 4723, "end": 24752 }
class ____(types.ModuleType): def __getattribute__(self, name: str) -> Any: state = object.__getattribute__(self, "__lazy_module_state__") state.load() return object.__getattribute__(self, name) def __setattr__(self, name: str, value: Any) -> None: state = object.__getattribute__(self, "__lazy_module_state__") state.load() object.__setattr__(self, name, value) def __delattr__(self, name: str) -> None: state = object.__getattribute__(self, "__lazy_module_state__") state.load() object.__delattr__(self, name) def import_module_lazy(name: str) -> types.ModuleType: """Import a module lazily, only when it is used. Inspired by importlib.util.LazyLoader, but improved so that the module loading is thread-safe. Circular dependency between modules can lead to a deadlock if the two modules are loaded from different threads. :param (str) name: Dot-separated module path. E.g., 'scipy.stats'. """ try: return sys.modules[name] except KeyError: spec = importlib.util.find_spec(name) if spec is None: raise ModuleNotFoundError module = importlib.util.module_from_spec(spec) module.__lazy_module_state__ = LazyModuleState(module) # type: ignore module.__class__ = LazyModule sys.modules[name] = module return module def get_module( name: str, required: str | None = None, lazy: bool = True, ) -> Any: """Return module or None. Absolute import is required. :param (str) name: Dot-separated module path. E.g., 'scipy.stats'. :param (str) required: A string to raise a ValueError if missing :param (bool) lazy: If True, return a lazy loader for the module. :return: (module|None) If import succeeds, the module will be returned. """ if name not in _not_importable: try: if not lazy: return import_module(name) else: return import_module_lazy(name) except Exception: _not_importable.add(name) msg = f"Error importing optional module {name}" if required: logger.exception(msg) if required and name in _not_importable: raise wandb.Error(required) def get_optional_module(name) -> importlib.ModuleInterface | None: # type: ignore return get_module(name) np = get_module("numpy") pd_available = False pandas_spec = importlib.util.find_spec("pandas") if pandas_spec is not None: pd_available = True # TODO: Revisit these limits VALUE_BYTES_LIMIT = 100000 def app_url(api_url: str) -> str: """Return the frontend app url without a trailing slash.""" # TODO: move me to settings app_url = wandb.env.get_app_url() if app_url is not None: return str(app_url.strip("/")) if "://api.wandb.test" in api_url: # dev mode return api_url.replace("://api.", "://app.").strip("/") elif "://api.wandb." in api_url: # cloud return api_url.replace("://api.", "://").strip("/") elif "://api." in api_url: # onprem cloud return api_url.replace("://api.", "://app.").strip("/") # wandb/local return api_url def get_full_typename(o: Any) -> Any: """Determine types based on type names. Avoids needing to to import (and therefore depend on) PyTorch, TensorFlow, etc. """ instance_name = o.__class__.__module__ + "." + o.__class__.__name__ if instance_name in ["builtins.module", "__builtin__.module"]: return o.__name__ else: return instance_name def get_h5_typename(o: Any) -> Any: typename = get_full_typename(o) if is_tf_tensor_typename(typename): return "tensorflow.Tensor" elif is_pytorch_tensor_typename(typename): return "torch.Tensor" else: return o.__class__.__module__.split(".")[0] + "." + o.__class__.__name__ def is_uri(string: str) -> bool: parsed_uri = urllib.parse.urlparse(string) return len(parsed_uri.scheme) > 0 def local_file_uri_to_path(uri: str) -> str: """Convert URI to local filesystem path. No-op if the uri does not have the expected scheme. """ path = urllib.parse.urlparse(uri).path if uri.startswith("file:") else uri return urllib.request.url2pathname(path) def get_local_path_or_none(path_or_uri: str) -> str | None: """Return path if local, None otherwise. Return None if the argument is a local path (not a scheme or file:///). Otherwise return `path_or_uri`. """ parsed_uri = urllib.parse.urlparse(path_or_uri) if ( len(parsed_uri.scheme) == 0 or parsed_uri.scheme == "file" and len(parsed_uri.netloc) == 0 ): return local_file_uri_to_path(path_or_uri) else: return None def check_windows_valid_filename(path: int | str) -> bool: r"""Verify that the given path does not contain any invalid characters for a Windows filename. Windows filenames cannot contain the following characters: < > : " \ / | ? * For more details, refer to the official documentation: https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file#naming-conventions Args: path: The file path to check, which can be either an integer or a string. Returns: bool: True if the path does not contain any invalid characters, False otherwise. """ return not bool(re.search(r'[<>:"\\?*]', path)) # type: ignore def make_file_path_upload_safe(path: str) -> str: r"""Makes the provide path safe for file upload. The filename is made safe by: 1. Removing any leading slashes to prevent writing to absolute paths 2. Replacing '.' and '..' with underscores to prevent directory traversal attacks Raises: ValueError: If running on Windows and the key contains invalid filename characters (\, :, *, ?, ", <, >, |) """ sys_platform = platform.system() if sys_platform == "Windows" and not check_windows_valid_filename(path): raise ValueError( f"Path {path} is invalid. Please remove invalid filename characters" r' (\, :, *, ?, ", <, >, |)' ) # On Windows, convert forward slashes to backslashes. # This ensures that the key is a valid filename on Windows. if sys_platform == "Windows": path = str(path).replace("/", os.sep) # Avoid writing to absolute paths by striping any leading slashes. # The key has already been validated for windows operating systems in util.check_windows_valid_filename # This ensures the key does not contain invalid characters for windows, such as '\' or ':'. # So we can check only for '/' in the key. path = path.lstrip(os.sep) # Avoid directory traversal by replacing dots with underscores. paths = path.split(os.sep) safe_paths = [ p.replace(".", "_") if p in (os.curdir, os.pardir) else p for p in paths ] # Recombine the key into a relative path. return os.sep.join(safe_paths) def make_tarfile( output_filename: str, source_dir: str, archive_name: str, custom_filter: Callable | None = None, ) -> None: # Helper for filtering out modification timestamps def _filter_timestamps(tar_info: tarfile.TarInfo) -> tarfile.TarInfo | None: tar_info.mtime = 0 return tar_info if custom_filter is None else custom_filter(tar_info) descriptor, unzipped_filename = tempfile.mkstemp() try: with tarfile.open(unzipped_filename, "w") as tar: tar.add(source_dir, arcname=archive_name, filter=_filter_timestamps) # When gzipping the tar, don't include the tar's filename or modification time in the # zipped archive (see https://docs.python.org/3/library/gzip.html#gzip.GzipFile) with gzip.GzipFile( filename="", fileobj=open(output_filename, "wb"), mode="wb", mtime=0 ) as gzipped_tar, open(unzipped_filename, "rb") as tar_file: gzipped_tar.write(tar_file.read()) finally: os.close(descriptor) os.remove(unzipped_filename) def is_tf_tensor(obj: Any) -> bool: import tensorflow # type: ignore return isinstance(obj, tensorflow.Tensor) def is_tf_tensor_typename(typename: str) -> bool: return typename.startswith("tensorflow.") and ( "Tensor" in typename or "Variable" in typename ) def is_tf_eager_tensor_typename(typename: str) -> bool: return typename.startswith("tensorflow.") and ("EagerTensor" in typename) def is_pytorch_tensor(obj: Any) -> bool: import torch # type: ignore return isinstance(obj, torch.Tensor) def is_pytorch_tensor_typename(typename: str) -> bool: return typename.startswith("torch.") and ( "Tensor" in typename or "Variable" in typename ) def is_jax_tensor_typename(typename: str) -> bool: return typename.startswith("jaxlib.") and "Array" in typename def get_jax_tensor(obj: Any) -> Any: import jax # type: ignore return jax.device_get(obj) def is_fastai_tensor_typename(typename: str) -> bool: return typename.startswith("fastai.") and ("Tensor" in typename) def is_pandas_data_frame_typename(typename: str) -> bool: return typename.startswith("pandas.") and "DataFrame" in typename def is_matplotlib_typename(typename: str) -> bool: return typename.startswith("matplotlib.") def is_plotly_typename(typename: str) -> bool: return typename.startswith("plotly.") def is_plotly_figure_typename(typename: str) -> bool: return typename.startswith("plotly.") and typename.endswith(".Figure") def is_numpy_array(obj: Any) -> bool: return np and isinstance(obj, np.ndarray) def is_pandas_data_frame(obj: Any) -> bool: if pd_available: import pandas as pd return isinstance(obj, pd.DataFrame) else: return is_pandas_data_frame_typename(get_full_typename(obj)) def ensure_matplotlib_figure(obj: Any) -> Any: """Extract the current figure from a matplotlib object. Return the object itself if it's a figure. Raises ValueError if the object can't be converted. """ import matplotlib # type: ignore from matplotlib.figure import Figure # type: ignore # there are combinations of plotly and matplotlib versions that don't work well together, # this patches matplotlib to add a removed method that plotly assumes exists from matplotlib.spines import Spine # type: ignore def is_frame_like(self: Any) -> bool: """Return True if directly on axes frame. This is useful for determining if a spine is the edge of an old style MPL plot. If so, this function will return True. """ position = self._position or ("outward", 0.0) if isinstance(position, str): if position == "center": position = ("axes", 0.5) elif position == "zero": position = ("data", 0) if len(position) != 2: raise ValueError("position should be 2-tuple") position_type, amount = position # type: ignore if position_type == "outward" and amount == 0: return True else: return False Spine.is_frame_like = is_frame_like if obj == matplotlib.pyplot: obj = obj.gcf() elif not isinstance(obj, Figure): if hasattr(obj, "figure"): obj = obj.figure # Some matplotlib objects have a figure function if not isinstance(obj, Figure): raise ValueError( "Only matplotlib.pyplot or matplotlib.pyplot.Figure objects are accepted." ) return obj def matplotlib_to_plotly(obj: Any) -> Any: obj = ensure_matplotlib_figure(obj) tools = get_module( "plotly.tools", required=( "plotly is required to log interactive plots, install with: " "`pip install plotly` or convert the plot to an image with `wandb.Image(plt)`" ), ) return tools.mpl_to_plotly(obj) def matplotlib_contains_images(obj: Any) -> bool: obj = ensure_matplotlib_figure(obj) return any(len(ax.images) > 0 for ax in obj.axes) def _numpy_generic_convert(obj: Any) -> Any: obj = obj.item() if isinstance(obj, float) and math.isnan(obj): obj = None elif isinstance(obj, np.generic) and ( obj.dtype.kind == "f" or obj.dtype == "bfloat16" ): # obj is a numpy float with precision greater than that of native python float # (i.e., float96 or float128) or it is of custom type such as bfloat16. # in these cases, obj.item() does not return a native # python float (in the first case - to avoid loss of precision, # so we need to explicitly cast this down to a 64bit float) obj = float(obj) return obj def _sanitize_numpy_keys( d: dict, visited: dict[int, dict] | None = None, ) -> tuple[dict, bool]: """Returns a dictionary where all NumPy keys are converted. Args: d: The dictionary to sanitize. Returns: A sanitized dictionary, and a boolean indicating whether anything was changed. """ out: dict[Any, Any] = dict() converted = False # Work with recursive dictionaries: if a dictionary has already been # converted, reuse its converted value to retain the recursive structure # of the input. if visited is None: visited = {id(d): out} elif id(d) in visited: return visited[id(d)], False visited[id(d)] = out for key, value in d.items(): if isinstance(value, dict): value, converted_value = _sanitize_numpy_keys(value, visited) converted |= converted_value if isinstance(key, np.generic): key = _numpy_generic_convert(key) converted = True out[key] = value return out, converted def json_friendly( # noqa: C901 obj: Any, ) -> tuple[Any, bool] | tuple[None | str | float, bool]: """Convert an object into something that's more becoming of JSON.""" converted = True typename = get_full_typename(obj) if is_tf_eager_tensor_typename(typename): obj = obj.numpy() elif is_tf_tensor_typename(typename): try: obj = obj.eval() except RuntimeError: obj = obj.numpy() elif is_pytorch_tensor_typename(typename) or is_fastai_tensor_typename(typename): try: if obj.requires_grad: obj = obj.detach() except AttributeError: pass # before 0.4 is only present on variables try: obj = obj.data except RuntimeError: pass # happens for Tensors before 0.4 if obj.size(): obj = obj.cpu().detach().numpy() else: return obj.item(), True elif is_jax_tensor_typename(typename): obj = get_jax_tensor(obj) if is_numpy_array(obj): if obj.size == 1: obj = obj.flatten()[0] elif obj.size <= 32: obj = obj.tolist() elif np and isinstance(obj, np.generic): obj = _numpy_generic_convert(obj) elif isinstance(obj, bytes): obj = obj.decode("utf-8") elif isinstance(obj, (datetime, date)): obj = obj.isoformat() elif callable(obj): obj = ( f"{obj.__module__}.{obj.__qualname__}" if hasattr(obj, "__qualname__") and hasattr(obj, "__module__") else str(obj) ) elif isinstance(obj, float) and math.isnan(obj): obj = None elif isinstance(obj, dict) and np: obj, converted = _sanitize_numpy_keys(obj) elif isinstance(obj, set): # set is not json serializable, so we convert it to tuple obj = tuple(obj) elif isinstance(obj, enum.Enum): obj = obj.name else: converted = False if getsizeof(obj) > VALUE_BYTES_LIMIT: wandb.termwarn( f"Serializing object of type {type(obj).__name__} that is {getsizeof(obj)} bytes" ) return obj, converted def json_friendly_val(val: Any) -> Any: """Make any value (including dict, slice, sequence, dataclass) JSON friendly.""" converted: dict | list if isinstance(val, dict): converted = {} for key, value in val.items(): converted[key] = json_friendly_val(value) return converted if isinstance(val, slice): converted = dict( slice_start=val.start, slice_step=val.step, slice_stop=val.stop ) return converted val, _ = json_friendly(val) if isinstance(val, Sequence) and not isinstance(val, str): converted = [] for value in val: converted.append(json_friendly_val(value)) return converted if is_dataclass(val) and not isinstance(val, type): converted = asdict(val) return json_friendly_val(converted) else: if val.__class__.__module__ not in ("builtins", "__builtin__"): val = str(val) return val def alias_is_version_index(alias: str) -> bool: return len(alias) >= 2 and alias[0] == "v" and alias[1:].isnumeric() def convert_plots(obj: Any) -> Any: if is_matplotlib_typename(get_full_typename(obj)): tools = get_module( "plotly.tools", required=( "plotly is required to log interactive plots, install with: " "`pip install plotly` or convert the plot to an image with `wandb.Image(plt)`" ), ) obj = tools.mpl_to_plotly(obj) if is_plotly_typename(get_full_typename(obj)): return {"_type": "plotly", "plot": obj.to_plotly_json()} else: return obj def maybe_compress_history(obj: Any) -> tuple[Any, bool]: if np and isinstance(obj, np.ndarray) and obj.size > 32: return wandb.Histogram(obj, num_bins=32).to_json(), True else: return obj, False def maybe_compress_summary(obj: Any, h5_typename: str) -> tuple[Any, bool]: if np and isinstance(obj, np.ndarray) and obj.size > 32: return ( { "_type": h5_typename, # may not be ndarray "var": np.var(obj).item(), "mean": np.mean(obj).item(), "min": np.amin(obj).item(), "max": np.amax(obj).item(), "10%": np.percentile(obj, 10), "25%": np.percentile(obj, 25), "75%": np.percentile(obj, 75), "90%": np.percentile(obj, 90), "size": obj.size, }, True, ) else: return obj, False def launch_browser(attempt_launch_browser: bool = True) -> bool: """Decide if we should launch a browser.""" _display_variables = ["DISPLAY", "WAYLAND_DISPLAY", "MIR_SOCKET"] _webbrowser_names_blocklist = ["www-browser", "lynx", "links", "elinks", "w3m"] import webbrowser launch_browser = attempt_launch_browser if launch_browser: if "linux" in sys.platform and not any( os.getenv(var) for var in _display_variables ): launch_browser = False try: browser = webbrowser.get() if hasattr(browser, "name") and browser.name in _webbrowser_names_blocklist: launch_browser = False except webbrowser.Error: launch_browser = False return launch_browser def generate_id(length: int = 8) -> str: # Do not use this; use wandb.sdk.lib.runid.generate_id instead. # This is kept only for legacy code. return runid.generate_id(length) def parse_tfjob_config() -> Any: """Attempt to parse TFJob config, returning False if it can't find it.""" if os.getenv("TF_CONFIG"): try: return json.loads(os.environ["TF_CONFIG"]) except ValueError: return False else: return False
LazyModule
python
fastai__fastai
fastai/text/core.py
{ "start": 5262, "end": 11501 }
class ____: "A wrapper around `tok` which applies `rules`, then tokenizes, then applies `post_rules`" def __init__(self, tok, rules=None, post_rules=None): self.rules = L(ifnone(rules, defaults.text_proc_rules)) self.post_f = compose(*L(ifnone(post_rules, defaults.text_postproc_rules))) self.tok = tok def __call__(self, batch): return (L(o).map(self.post_f) for o in self.tok(maps(*self.rules, batch))) # %% ../../nbs/30_text.core.ipynb 46 @delegates(TokenizeWithRules) def tokenize1(text, tok, **kwargs): "Call `TokenizeWithRules` with a single text" return first(TokenizeWithRules(tok=tok, **kwargs)([text])) # %% ../../nbs/30_text.core.ipynb 48 def parallel_tokenize(items, tok=None, rules=None, n_workers=defaults.cpus, **kwargs): "Calls optional `setup` on `tok` before launching `TokenizeWithRules` using `parallel_gen" if tok is None: tok = WordTokenizer() if hasattr(tok, 'setup'): tok.setup(items, rules) return parallel_gen(TokenizeWithRules, items, tok=tok, rules=rules, n_workers=n_workers, **kwargs) # %% ../../nbs/30_text.core.ipynb 54 fn_counter_pkl = 'counter.pkl' fn_lengths_pkl = 'lengths.pkl' # %% ../../nbs/30_text.core.ipynb 55 def _tokenize_files(func, files, path, output_dir=None, output_names=None, n_workers=defaults.cpus, rules=None, tok=None, encoding='utf8', skip_if_exists=False): "Tokenize text `files` in parallel using `n_workers`" if tok is None: tok = WordTokenizer() output_dir = Path(ifnone(output_dir, path.parent/f'{path.name}_tok')) if skip_if_exists and output_dir.exists(): return output_dir output_dir.mkdir(exist_ok=True) if output_names is None: output_names = L(output_dir/f.relative_to(path) for f in files) rules = partial(Path.read_text, encoding=encoding) + L(ifnone(rules, defaults.text_proc_rules.copy())) lengths,counter = {},Counter() for i,tok in parallel_tokenize(files, tok, rules, n_workers=n_workers): out = func(i,output_dir) out.mk_write(' '.join(tok), encoding=encoding) lengths[str(files[i].relative_to(path))] = len(tok) counter.update(tok) save_pickle(output_dir/fn_lengths_pkl, lengths) save_pickle(output_dir/fn_counter_pkl, counter) return output_dir # %% ../../nbs/30_text.core.ipynb 56 @delegates(_tokenize_files) def tokenize_folder(path, extensions=None, folders=None, output_dir=None, skip_if_exists=True, **kwargs): "Tokenize text files in `path` in parallel using `n_workers`" path,extensions = Path(path),ifnone(extensions, ['.txt']) files = get_files(path, extensions=extensions, recurse=True, folders=folders) def _f(i,output_dir): return output_dir/files[i].relative_to(path) return _tokenize_files(_f, files, path, skip_if_exists=skip_if_exists, **kwargs) # %% ../../nbs/30_text.core.ipynb 58 @delegates(_tokenize_files) def tokenize_files(files, path, output_dir, output_names=None, **kwargs): "Tokenize text `files` in parallel using `n_workers`" if output_names is None: output_names = L(output_dir/f.relative_to(path) for f in files) def _f(i,output_dir): return output_dir/output_names[i] return _tokenize_files(_f, files, path, output_dir=output_dir, **kwargs) # %% ../../nbs/30_text.core.ipynb 60 def _join_texts(df, mark_fields=False): "Join texts in row `idx` of `df`, marking each field with `FLD` if `mark_fields=True`" text_col = (f'{FLD} {1} ' if mark_fields else '' ) + df.iloc[:,0].astype(str) for i in range(1,len(df.columns)): text_col += (f' {FLD} {i+1} ' if mark_fields else ' ') + df.iloc[:,i].astype(str) return text_col.values # %% ../../nbs/30_text.core.ipynb 62 def tokenize_texts(texts, n_workers=defaults.cpus, rules=None, tok=None): "Tokenize `texts` in parallel using `n_workers`" rules = L(ifnone(rules, defaults.text_proc_rules.copy())) outputs = L(parallel_tokenize(texts, tok=tok, rules=rules, n_workers=n_workers) ).sorted().itemgot(1) return outputs # %% ../../nbs/30_text.core.ipynb 63 def tokenize_df(df, text_cols, n_workers=defaults.cpus, rules=None, mark_fields=None, tok=None, tok_text_col="text"): "Tokenize texts in `df[text_cols]` in parallel using `n_workers` and stores them in `df[tok_text_col]`" text_cols = [df.columns[c] if isinstance(c, int) else c for c in L(text_cols)] #mark_fields defaults to False if there is one column of texts, True if there are multiple if mark_fields is None: mark_fields = len(text_cols)>1 rules = L(ifnone(rules, defaults.text_proc_rules.copy())) texts = _join_texts(df[text_cols], mark_fields=mark_fields) outputs = L(parallel_tokenize(texts, tok, rules, n_workers=n_workers) ).sorted().itemgot(1) other_cols = df.columns[~df.columns.isin(text_cols)] res = df[other_cols].copy() res[tok_text_col] = outputs res[f'{tok_text_col}_length'] = [len(o) for o in outputs] return res,Counter(outputs.concat()) # %% ../../nbs/30_text.core.ipynb 65 def tokenize_csv(fname, text_cols, outname=None, n_workers=4, rules=None, mark_fields=None, tok=None, header='infer', chunksize=50000): "Tokenize texts in the `text_cols` of the csv `fname` in parallel using `n_workers`" df = pd.read_csv(fname, header=header, chunksize=chunksize) outname = Path(ifnone(outname, fname.parent/f'{fname.stem}_tok.csv')) cnt = Counter() for i,dfp in enumerate(df): out,c = tokenize_df(dfp, text_cols, n_workers=n_workers, rules=rules, mark_fields=mark_fields, tok=tok) out.text = out.text.str.join(' ') out.to_csv(outname, header=(None,header)[i==0], index=False, mode=('a','w')[i==0]) cnt.update(c) save_pickle(outname.with_suffix('.pkl'), cnt) # %% ../../nbs/30_text.core.ipynb 66 def load_tokenized_csv(fname): "Utility function to quickly load a tokenized csv ans the corresponding counter" fname = Path(fname) out = pd.read_csv(fname) for txt_col in out.columns[1:-1]: out[txt_col] = tuple(out[txt_col].str.split(' ')) return out,load_pickle(fname.with_suffix('.pkl')) # %% ../../nbs/30_text.core.ipynb 71
TokenizeWithRules
python
allegroai__clearml
clearml/backend_api/services/v2_20/tasks.py
{ "start": 73947, "end": 79188 }
class ____(Request): """ Update existing artifacts (search by key/mode) and add new ones :param task: Task ID :type task: str :param artifacts: Artifacts to add or update :type artifacts: Sequence[Artifact] :param force: If set to True then both new and running task artifacts can be edited. Otherwise only the new task ones. Default is False :type force: bool """ _service = "tasks" _action = "add_or_update_artifacts" _version = "2.20" _schema = { "definitions": { "artifact": { "properties": { "content_size": { "description": "Raw data length in bytes", "type": "integer", }, "display_data": { "description": "User-defined list of key/value pairs, sorted", "items": {"items": {"type": "string"}, "type": "array"}, "type": "array", }, "hash": { "description": "Hash of entire raw data", "type": "string", }, "key": {"description": "Entry key", "type": "string"}, "mode": { "$ref": "#/definitions/artifact_mode_enum", "description": "System defined input/output indication", }, "timestamp": { "description": "Epoch time when artifact was created", "type": "integer", }, "type": {"description": "System defined type", "type": "string"}, "type_data": { "$ref": "#/definitions/artifact_type_data", "description": "Additional fields defined by the system", }, "uri": {"description": "Raw data location", "type": "string"}, }, "required": ["key", "type"], "type": "object", }, "artifact_mode_enum": { "default": "output", "enum": ["input", "output"], "type": "string", }, "artifact_type_data": { "properties": { "content_type": { "description": "System defined raw data content type", "type": ["string", "null"], }, "data_hash": { "description": "Hash of raw data, without any headers or descriptive parts", "type": ["string", "null"], }, "preview": { "description": "Description or textual data", "type": ["string", "null"], }, }, "type": "object", }, }, "properties": { "artifacts": { "description": "Artifacts to add or update", "items": {"$ref": "#/definitions/artifact"}, "type": "array", }, "force": { "description": "If set to True then both new and running task artifacts can be edited. Otherwise only the new task ones. Default is False", "type": "boolean", }, "task": {"description": "Task ID", "type": "string"}, }, "required": ["task", "artifacts"], "type": "object", } def __init__(self, task: str, artifacts: List[Any], force: Optional[bool] = None, **kwargs: Any) -> None: super(AddOrUpdateArtifactsRequest, self).__init__(**kwargs) self.task = task self.artifacts = artifacts self.force = force @schema_property("task") def task(self) -> str: return self._property_task @task.setter def task(self, value: str) -> None: if value is None: self._property_task = None return self.assert_isinstance(value, "task", six.string_types) self._property_task = value @schema_property("artifacts") def artifacts(self) -> List[Any]: return self._property_artifacts @artifacts.setter def artifacts(self, value: List[Any]) -> None: if value is None: self._property_artifacts = None return self.assert_isinstance(value, "artifacts", (list, tuple)) if any((isinstance(v, dict) for v in value)): value = [Artifact.from_dict(v) if isinstance(v, dict) else v for v in value] else: self.assert_isinstance(value, "artifacts", Artifact, is_array=True) self._property_artifacts = value @schema_property("force") def force(self) -> Optional[bool]: return self._property_force @force.setter def force(self, value: Optional[bool]) -> None: if value is None: self._property_force = None return self.assert_isinstance(value, "force", (bool,)) self._property_force = value
AddOrUpdateArtifactsRequest
python
langchain-ai__langchain
libs/partners/qdrant/tests/integration_tests/common.py
{ "start": 1164, "end": 2188 }
class ____(Embeddings): """Fake embeddings which remember all the texts seen so far to return consistent vectors for the same texts. """ def __init__(self, dimensionality: int = 10) -> None: self.known_texts: list[str] = [] self.dimensionality = dimensionality def embed_documents(self, texts: list[str]) -> list[list[float]]: """Return consistent embeddings for each text seen so far.""" out_vectors = [] for text in texts: if text not in self.known_texts: self.known_texts.append(text) vector = [1.0] * (self.dimensionality - 1) + [ float(self.known_texts.index(text)) ] out_vectors.append(vector) return out_vectors def embed_query(self, text: str) -> list[float]: """Return consistent embeddings for the text, if seen before, or a constant one if the text is unknown. """ return self.embed_documents([text])[0]
ConsistentFakeEmbeddings
python
pypa__warehouse
tests/unit/accounts/test_views.py
{ "start": 207594, "end": 218775 }
class ____: def test_already_logged_in(self, pyramid_request): pyramid_request.user = UserFactory.create() pyramid_request.route_path = pretend.call_recorder(lambda route: f"/{route}") result = views.confirm_login(pyramid_request) assert isinstance(result, HTTPSeeOther) assert result.location == "/index" assert pyramid_request.route_path.calls == [pretend.call("index")] def test_no_token(self, pyramid_request): pyramid_request.user = None pyramid_request.params = {} result = views.confirm_login(pyramid_request) assert result == {} @pytest.mark.parametrize( ("exception", "message"), [ (TokenInvalid, "Invalid token: please try to login again"), (TokenExpired, "Expired token: please try to login again"), (TokenMissing, "Invalid token: no token supplied"), ], ) def test_token_error(self, pyramid_request, exception, message): pyramid_request.user = None pyramid_request.params = {"token": "foo"} token_service = pretend.stub(loads=pretend.raiser(exception)) user_service = pretend.stub() pyramid_request.find_service = lambda interface, name=None, **kwargs: { ITokenService: {"confirm_login": token_service}, IUserService: {None: user_service}, }[interface][name] pyramid_request.session.flash = pretend.call_recorder(lambda *a, **kw: None) pyramid_request.route_path = pretend.call_recorder(lambda r: f"/{r}") result = views.confirm_login(pyramid_request) assert isinstance(result, HTTPSeeOther) assert result.location == "/accounts.login" assert pyramid_request.session.flash.calls == [ pretend.call(message, queue="error") ] def test_invalid_action(self, pyramid_request): pyramid_request.user = None pyramid_request.params = {"token": "foo"} token_data = {"action": "wrong-action"} token_service = pretend.stub(loads=pretend.call_recorder(lambda t: token_data)) user_service = pretend.stub() pyramid_request.find_service = lambda interface, name=None, **kwargs: { ITokenService: {"confirm_login": token_service}, IUserService: {None: user_service}, }[interface][name] pyramid_request.session.flash = pretend.call_recorder(lambda *a, **kw: None) pyramid_request.route_path = pretend.call_recorder(lambda r: f"/{r}") result = views.confirm_login(pyramid_request) assert isinstance(result, HTTPSeeOther) assert result.location == "/accounts.login" assert pyramid_request.session.flash.calls == [ pretend.call("Invalid token: not a login confirmation token", queue="error") ] def test_user_not_found(self, pyramid_request): pyramid_request.user = None pyramid_request.params = {"token": "foo"} token_data = { "action": "login-confirmation", "user.id": str(uuid.uuid4()), } token_service = pretend.stub(loads=pretend.call_recorder(lambda t: token_data)) user_service = pretend.stub(get_user=pretend.call_recorder(lambda uid: None)) pyramid_request.find_service = lambda interface, name=None, **kwargs: { ITokenService: {"confirm_login": token_service}, IUserService: {None: user_service}, }[interface][name] pyramid_request.session.flash = pretend.call_recorder(lambda *a, **kw: None) pyramid_request.route_path = pretend.call_recorder(lambda r: f"/{r}") result = views.confirm_login(pyramid_request) assert isinstance(result, HTTPSeeOther) assert result.location == "/accounts.login" assert pyramid_request.session.flash.calls == [ pretend.call("Invalid token: user not found", queue="error") ] def test_user_logged_in_since_naive_datetime(self, db_request): user = UserFactory.create(last_login=datetime.datetime.now(datetime.UTC)) db_request.user = None db_request.params = {"token": "foo"} token_data = { "action": "login-confirmation", "user.id": str(user.id), "user.last_login": (user.last_login - datetime.timedelta(seconds=1)) .replace(tzinfo=None) .isoformat(), } token_service = pretend.stub(loads=pretend.call_recorder(lambda t: token_data)) user_service = pretend.stub(get_user=pretend.call_recorder(lambda uid: user)) db_request.find_service = lambda interface, name=None, **kwargs: { ITokenService: {"confirm_login": token_service}, IUserService: {None: user_service}, }[interface][name] db_request.session.flash = pretend.call_recorder(lambda *a, **kw: None) db_request.route_path = pretend.call_recorder(lambda r: f"/{r}") result = views.confirm_login(db_request) assert isinstance(result, HTTPSeeOther) assert result.location == "/accounts.login" assert db_request.session.flash.calls == [ pretend.call( "Invalid token: user has logged in since this token was requested", queue="error", ) ] def test_user_logged_in_since(self, db_request): user = UserFactory.create(last_login=datetime.datetime.now(datetime.UTC)) db_request.user = None db_request.params = {"token": "foo"} token_data = { "action": "login-confirmation", "user.id": str(user.id), "user.last_login": ( user.last_login - datetime.timedelta(seconds=1) ).isoformat(), } token_service = pretend.stub(loads=pretend.call_recorder(lambda t: token_data)) user_service = pretend.stub(get_user=pretend.call_recorder(lambda uid: user)) db_request.find_service = lambda interface, name=None, **kwargs: { ITokenService: {"confirm_login": token_service}, IUserService: {None: user_service}, }[interface][name] db_request.session.flash = pretend.call_recorder(lambda *a, **kw: None) db_request.route_path = pretend.call_recorder(lambda r: f"/{r}") result = views.confirm_login(db_request) assert isinstance(result, HTTPSeeOther) assert result.location == "/accounts.login" assert db_request.session.flash.calls == [ pretend.call( "Invalid token: user has logged in since this token was requested", queue="error", ) ] def test_unique_login_not_found(self, db_request): user = UserFactory.create(last_login=datetime.datetime.now(datetime.UTC)) db_request.user = None db_request.params = {"token": "foo"} token_data = { "action": "login-confirmation", "user.id": str(user.id), "user.last_login": user.last_login.isoformat(), "unique_login_id": str(uuid.uuid4()), } token_service = pretend.stub(loads=pretend.call_recorder(lambda t: token_data)) user_service = pretend.stub(get_user=pretend.call_recorder(lambda uid: user)) db_request.find_service = lambda interface, name=None, **kwargs: { ITokenService: {"confirm_login": token_service}, IUserService: {None: user_service}, }[interface][name] db_request.session.flash = pretend.call_recorder(lambda *a, **kw: None) db_request.route_path = pretend.call_recorder(lambda r: f"/{r}") result = views.confirm_login(db_request) assert isinstance(result, HTTPSeeOther) assert result.location == "/accounts.login" assert db_request.session.flash.calls == [ pretend.call("Invalid login attempt.", queue="error") ] def test_ip_address_mismatch(self, db_request): user = UserFactory.create(last_login=datetime.datetime.now(datetime.UTC)) unique_login = UserUniqueLoginFactory.create(user=user, ip_address="1.1.1.1") db_request.user = None db_request.params = {"token": "foo"} token_data = { "action": "login-confirmation", "user.id": str(user.id), "user.last_login": user.last_login.isoformat(), "unique_login_id": unique_login.id, } token_service = pretend.stub(loads=pretend.call_recorder(lambda t: token_data)) user_service = pretend.stub(get_user=pretend.call_recorder(lambda uid: user)) db_request.find_service = lambda interface, name=None, **kwargs: { ITokenService: {"confirm_login": token_service}, IUserService: {None: user_service}, }[interface][name] db_request.session.flash = pretend.call_recorder(lambda *a, **kw: None) db_request.route_path = pretend.call_recorder(lambda r: f"/{r}") result = views.confirm_login(db_request) assert isinstance(result, HTTPSeeOther) assert result.location == "/accounts.login" assert db_request.session.flash.calls == [ pretend.call( "Device details didn't match, please try again from the device you " "originally used to log in.", queue="error", ) ] def test_success(self, monkeypatch, db_request): user = UserFactory.create(last_login=datetime.datetime.now(datetime.UTC)) unique_login = UserUniqueLoginFactory.create( user=user, ip_address=db_request.remote_addr ) db_request.user = None db_request.params = {"token": "foo"} token_data = { "action": "login-confirmation", "user.id": str(user.id), "user.last_login": user.last_login.isoformat(), "unique_login_id": str(unique_login.id), } token_service = pretend.stub(loads=pretend.call_recorder(lambda t: token_data)) user_service = pretend.stub(get_user=pretend.call_recorder(lambda uid: user)) db_request.find_service = lambda interface, name=None, **kwargs: { ITokenService: {"confirm_login": token_service}, IUserService: {None: user_service}, }[interface][name] _login_user = pretend.call_recorder(lambda request, userid: [("foo", "bar")]) monkeypatch.setattr(views, "_login_user", _login_user) _set_userid_insecure_cookie = pretend.call_recorder(lambda resp, userid: None) monkeypatch.setattr( views, "_set_userid_insecure_cookie", _set_userid_insecure_cookie ) db_request.route_path = pretend.call_recorder(lambda r: f"/{r}") result = views.confirm_login(db_request) assert isinstance(result, HTTPSeeOther) assert result.location == "/manage.projects" assert unique_login.status == UniqueLoginStatus.CONFIRMED assert _login_user.calls == [pretend.call(db_request, user.id)] assert _set_userid_insecure_cookie.calls == [pretend.call(result, user.id)]
TestConfirmLogin
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI036.py
{ "start": 9119, "end": 9513 }
class ____: @overload def __exit__(self, exc_typ: type[BaseException] | None, exc: None, tb: None) -> None: ... # PYI036 @overload def __exit__(self, exc_typ: object, exc: Exception, tb: builtins.TracebackType) -> None: ... # PYI036 def __exit__(self, exc_typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ...
UnacceptableOverload2
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 1048748, "end": 1049016 }
class ____(sgqlc.types.Type, HovercardContext): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("viewer",) viewer = sgqlc.types.Field(sgqlc.types.non_null(User), graphql_name="viewer")
ViewerHovercardContext
python
django__django
tests/model_fields/models.py
{ "start": 3416, "end": 3506 }
class ____(models.Model): value = models.SmallAutoField(primary_key=True)
SmallAutoModel
python
pypa__hatch
tests/project/test_frontend.py
{ "start": 10792, "end": 12056 }
class ____: def test_default(self, temp_dir, temp_dir_data, platform, global_application): project_dir = temp_dir / "project" project_dir.mkdir() (project_dir / "pyproject.toml").write_text( """\ [build-system] requires = ["hatchling"] build-backend = "hatchling.build" [project] name = "foo" version = "9000.42" """ ) package_dir = project_dir / "foo" package_dir.mkdir() (package_dir / "__init__.py").touch() project = Project(project_dir) project.build_env = MockEnvironment( temp_dir, project.metadata, "default", project.config.envs["default"], {}, temp_dir_data, temp_dir_data, platform, 0, global_application, ) output_dir = temp_dir / "output" output_dir.mkdir() script = project.build_frontend.hatch.scripts.get_build_deps( output_dir=str(output_dir), project_root=str(project_dir), targets=["sdist", "wheel"] ) platform.check_command([sys.executable, "-c", script]) output = json.loads((output_dir / "output.json").read_text()) assert output == []
TestHatchGetBuildDeps
python
django__django
django/template/defaulttags.py
{ "start": 13060, "end": 13517 }
class ____(Node): def __init__(self, format_string, asvar=None): self.format_string = format_string self.asvar = asvar def render(self, context): tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None formatted = date(datetime.now(tz=tzinfo), self.format_string) if self.asvar: context[self.asvar] = formatted return "" else: return formatted
NowNode
python
getsentry__sentry
src/sentry/sentry_apps/external_requests/select_requester.py
{ "start": 973, "end": 1191 }
class ____(TypedDict, total=False): # Each contained Sequence of strings is of length 2 i.e ["label", "value"] choices: Sequence[Annotated[Sequence[str], 2]] defaultValue: str @dataclass
SelectRequesterResult
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/methodOverride4.py
{ "start": 746, "end": 931 }
class ____(BaseA[_TSource]): def method1( self, mapper: Callable[[_TSource, _T3], _TResult], other: BaseA[_T3] ) -> BaseA[_TResult]: return SubclassA2()
SubclassA2
python
huggingface__transformers
src/transformers/models/audioflamingo3/modular_audioflamingo3.py
{ "start": 4970, "end": 12741 }
class ____(VoxtralForConditionalGeneration): _tp_plan = None _pp_plan = None _keep_in_fp32_modules_strict = None def __init__(self, config): super().__init__(config) def get_audio_features( self, input_features: torch.FloatTensor, input_features_mask: torch.Tensor ) -> torch.FloatTensor: """ This method is used to get the audio embeddings from input features (a log mel spectrogram), meaning inferring the audio encoder and the multi-modal projector. Args: input_features (`torch.FloatTensor`): Float values of mel features extracted from the raw speech waveform. Raw speech waveform can be obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]` or a `numpy.ndarray`, *e.g.* via the soundfile library (`pip install soundfile`). To prepare the array into `input_features`, the [`AutoFeatureExtractor`] should be used for extracting the mel features, padding and conversion into a tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`] input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`): Mask to avoid performing attention on padded feature indices. Returns: `torch.FloatTensor`: The audio embeddings. """ # Encode audio encoder_output = self.audio_tower(input_features, input_features_mask=input_features_mask) audio_embeds = self.multi_modal_projector(encoder_output.last_hidden_state) # Mask according to avg pooling (which is after attention blocks) post_lengths = (input_features_mask.sum(-1) - 2) // 2 + 1 valid_mask = torch.arange(audio_embeds.shape[1], device=post_lengths.device)[None, :] < post_lengths[:, None] audio_embeds = audio_embeds[valid_mask.to(audio_embeds.device)] return audio_embeds def get_audio_embeds(self): raise NotImplementedError("This method is not supported for AudioFlamingo3ForConditionalGeneration.") @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, input_features: Optional[torch.FloatTensor] = None, input_features_mask: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> CausalLMOutputWithPast: r""" input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`): Mask to avoid performing attention on padding feature indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Example: ```python >>> from transformers import AudioFlamingo3ForConditionalGeneration, AutoProcessor >>> model_id = "nvidia/audio-flamingo-3-hf" >>> processor = AutoProcessor.from_pretrained(model_id) >>> model = AudioFlamingo3ForConditionalGeneration.from_pretrained(model_id, device_map="auto") >>> conversations = [ >>> [ >>> { >>> "role": "user", >>> "content": [ >>> {"type": "text", "text": "Transcribe the input speech."}, >>> { >>> "type": "audio", >>> "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/t_837b89f2-26aa-4ee2-bdf6-f73f0dd59b26.wav", >>> }, >>> ], >>> } >>> ], >>> [ >>> { >>> "role": "user", >>> "content": [ >>> { >>> "type": "text", >>> "text": "This track feels really peaceful and introspective. What elements make it feel so calming and meditative?", >>> }, >>> {"type": "audio", "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/FPSbCAANfbJLVSwD.mp3"}, >>> ], >>> } >>> ], >>> ] >>> inputs = processor.apply_chat_template( >>> conversations, >>> tokenize=True, >>> add_generation_prompt=True, >>> return_dict=True, >>> ).to(model.device) >>> outputs = model.generate(**inputs, max_new_tokens=500) >>> decoded_outputs = processor.batch_decode( >>> outputs[:, inputs["input_ids"].shape[1]:], skip_special_tokens=True >>> ) >>> print(decoded_outputs) ["The spoken content of the audio is...", "The track's calming and meditative feel can be attributed to..."] ```""" if inputs_embeds is None: inputs_embeds = self.get_input_embeddings()(input_ids) if input_features is not None and input_ids is not None: audio_embeds = self.get_audio_features(input_features, input_features_mask) # replace text-audio token placeholders with audio embeddings audio_token_mask = (input_ids == self.config.audio_token_id).unsqueeze(-1) inputs_embeds = inputs_embeds.masked_scatter( audio_token_mask.to(inputs_embeds.device), audio_embeds.to(inputs_embeds.device) ) outputs: CausalLMOutputWithPast = self.language_model( inputs_embeds=inputs_embeds, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, labels=labels, use_cache=use_cache, cache_position=cache_position, logits_to_keep=logits_to_keep, **kwargs, ) return outputs def prepare_inputs_for_generation(self, *args, **kwargs): # Overwritten -- we should not pass input_features when we are in cached decoding stage input_features = kwargs.pop("input_features", None) input_features_mask = kwargs.pop("input_features_mask", None) cache_position = kwargs.get("cache_position") model_inputs = super().prepare_inputs_for_generation(*args, **kwargs) if cache_position is not None and cache_position[0] == 0: # input_features should only be passed when we are not in cached decoding stage if input_features is not None: model_inputs["input_features"] = input_features if input_features_mask is not None: model_inputs["input_features_mask"] = input_features_mask return model_inputs __all__ = ["AudioFlamingo3ForConditionalGeneration", "AudioFlamingo3PreTrainedModel", "AudioFlamingo3Encoder"]
AudioFlamingo3ForConditionalGeneration
python
lepture__authlib
authlib/jose/rfc7517/base_key.py
{ "start": 285, "end": 3358 }
class ____: """This is the base class for a JSON Web Key.""" kty = "_" ALLOWED_PARAMS = ["use", "key_ops", "alg", "kid", "x5u", "x5c", "x5t", "x5t#S256"] PRIVATE_KEY_OPS = [ "sign", "decrypt", "unwrapKey", ] PUBLIC_KEY_OPS = [ "verify", "encrypt", "wrapKey", ] REQUIRED_JSON_FIELDS = [] def __init__(self, options=None): self.options = options or {} self._dict_data = {} @property def tokens(self): if not self._dict_data: self.load_dict_key() rv = dict(self._dict_data) rv["kty"] = self.kty for k in self.ALLOWED_PARAMS: if k not in rv and k in self.options: rv[k] = self.options[k] return rv @property def kid(self): return self.tokens.get("kid") def keys(self): return self.tokens.keys() def __getitem__(self, item): return self.tokens[item] @property def public_only(self): raise NotImplementedError() def load_raw_key(self): raise NotImplementedError() def load_dict_key(self): raise NotImplementedError() def check_key_op(self, operation): """Check if the given key_op is supported by this key. :param operation: key operation value, such as "sign", "encrypt". :raise: ValueError """ key_ops = self.tokens.get("key_ops") if key_ops is not None and operation not in key_ops: raise ValueError(f'Unsupported key_op "{operation}"') if operation in self.PRIVATE_KEY_OPS and self.public_only: raise ValueError(f'Invalid key_op "{operation}" for public key') use = self.tokens.get("use") if use: if operation in ["sign", "verify"]: if use != "sig": raise InvalidUseError() elif operation in ["decrypt", "encrypt", "wrapKey", "unwrapKey"]: if use != "enc": raise InvalidUseError() def as_dict(self, is_private=False, **params): raise NotImplementedError() def as_json(self, is_private=False, **params): """Represent this key as a JSON string.""" obj = self.as_dict(is_private, **params) return json_dumps(obj) def thumbprint(self): """Implementation of RFC7638 JSON Web Key (JWK) Thumbprint.""" fields = list(self.REQUIRED_JSON_FIELDS) fields.append("kty") fields.sort() data = OrderedDict() for k in fields: data[k] = self.tokens[k] json_data = json_dumps(data) digest_data = hashlib.sha256(to_bytes(json_data)).digest() return to_unicode(urlsafe_b64encode(digest_data)) @classmethod def check_required_fields(cls, data): for k in cls.REQUIRED_JSON_FIELDS: if k not in data: raise ValueError(f'Missing required field: "{k}"') @classmethod def validate_raw_key(cls, key): raise NotImplementedError()
Key
python
streamlit__streamlit
lib/tests/streamlit/logger_test.py
{ "start": 909, "end": 2959 }
class ____(unittest.TestCase): """Logger Unittest class.""" def test_set_log_level_by_constant(self): """Test streamlit.logger.set_log_level.""" data = [ logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG, ] for k in data: logger.set_log_level(k) assert k == logging.getLogger("streamlit").getEffectiveLevel() def test_set_log_level_error(self): """Test streamlit.logger.set_log_level.""" with pytest.raises(SystemExit) as e: logger.set_log_level(90) assert e.type is SystemExit assert e.value.code == 1 @parameterized.expand( [ ("%(asctime)s.%(msecs)03d %(name)s: %(message)s", None), ("%(asctime)s.%(msecs)03d %(name)s: %(message)s", DUMMY_CONFIG_OPTIONS), (None, None), (None, DUMMY_CONFIG_OPTIONS), ] ) def test_setup_log_formatter(self, messageFormat, config_options): """Test streamlit.logger.setup_log_formatter.""" LOGGER = logger.get_logger("test") config._set_option("logger.messageFormat", messageFormat, "test") config._set_option("logger.level", logging.DEBUG, "test") with patch.object(config, "_config_options", new=config_options): logger.setup_formatter(LOGGER) assert len(LOGGER.handlers) == 1 if config_options: assert LOGGER.handlers[0].formatter._fmt == ( messageFormat or "%(message)s" ) else: assert LOGGER.handlers[0].formatter._fmt == logger.DEFAULT_LOG_MESSAGE def test_init_tornado_logs(self): """Test streamlit.logger.init_tornado_logs.""" logger.init_tornado_logs() loggers = [x for x in logger._loggers if "tornado." in x] truth = ["tornado.access", "tornado.application", "tornado.general"] assert sorted(truth) == sorted(loggers)
LoggerTest
python
django__django
tests/servers/tests.py
{ "start": 6206, "end": 6437 }
class ____(LiveServerThread): def _create_server(self, connections_override=None): return WSGIServer( (self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False )
LiveServerSingleThread
python
scikit-learn__scikit-learn
sklearn/preprocessing/_encoders.py
{ "start": 18882, "end": 51166 }
class ____(_BaseEncoder): """ Encode categorical features as a one-hot numeric array. The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are encoded using a one-hot (aka 'one-of-K' or 'dummy') encoding scheme. This creates a binary column for each category and returns a sparse matrix or dense array (depending on the ``sparse_output`` parameter). By default, the encoder derives the categories based on the unique values in each feature. Alternatively, you can also specify the `categories` manually. This encoding is needed for feeding categorical data to many scikit-learn estimators, notably linear models and SVMs with the standard kernels. Note: a one-hot encoding of y labels should use a LabelBinarizer instead. Read more in the :ref:`User Guide <preprocessing_categorical_features>`. For a comparison of different encoders, refer to: :ref:`sphx_glr_auto_examples_preprocessing_plot_target_encoder.py`. Parameters ---------- categories : 'auto' or a list of array-like, default='auto' Categories (unique values) per feature: - 'auto' : Determine categories automatically from the training data. - list : ``categories[i]`` holds the categories expected in the ith column. The passed categories should not mix strings and numeric values within a single feature, and should be sorted in case of numeric values. The used categories can be found in the ``categories_`` attribute. .. versionadded:: 0.20 drop : {'first', 'if_binary'} or an array-like of shape (n_features,), \ default=None Specifies a methodology to use to drop one of the categories per feature. This is useful in situations where perfectly collinear features cause problems, such as when feeding the resulting data into an unregularized linear regression model. However, dropping one category breaks the symmetry of the original representation and can therefore induce a bias in downstream models, for instance for penalized linear classification or regression models. - None : retain all features (the default). - 'first' : drop the first category in each feature. If only one category is present, the feature will be dropped entirely. - 'if_binary' : drop the first category in each feature with two categories. Features with 1 or more than 2 categories are left intact. - array : ``drop[i]`` is the category in feature ``X[:, i]`` that should be dropped. When `max_categories` or `min_frequency` is configured to group infrequent categories, the dropping behavior is handled after the grouping. .. versionadded:: 0.21 The parameter `drop` was added in 0.21. .. versionchanged:: 0.23 The option `drop='if_binary'` was added in 0.23. .. versionchanged:: 1.1 Support for dropping infrequent categories. sparse_output : bool, default=True When ``True``, it returns a :class:`scipy.sparse.csr_matrix`, i.e. a sparse matrix in "Compressed Sparse Row" (CSR) format. .. versionadded:: 1.2 `sparse` was renamed to `sparse_output` dtype : number type, default=np.float64 Desired dtype of output. handle_unknown : {'error', 'ignore', 'infrequent_if_exist', 'warn'}, \ default='error' Specifies the way unknown categories are handled during :meth:`transform`. - 'error' : Raise an error if an unknown category is present during transform. - 'ignore' : When an unknown category is encountered during transform, the resulting one-hot encoded columns for this feature will be all zeros. In the inverse transform, an unknown category will be denoted as None. - 'infrequent_if_exist' : When an unknown category is encountered during transform, the resulting one-hot encoded columns for this feature will map to the infrequent category if it exists. The infrequent category will be mapped to the last position in the encoding. During inverse transform, an unknown category will be mapped to the category denoted `'infrequent'` if it exists. If the `'infrequent'` category does not exist, then :meth:`transform` and :meth:`inverse_transform` will handle an unknown category as with `handle_unknown='ignore'`. Infrequent categories exist based on `min_frequency` and `max_categories`. Read more in the :ref:`User Guide <encoder_infrequent_categories>`. - 'warn' : When an unknown category is encountered during transform a warning is issued, and the encoding then proceeds as described for `handle_unknown="infrequent_if_exist"`. .. versionchanged:: 1.1 `'infrequent_if_exist'` was added to automatically handle unknown categories and infrequent categories. .. versionadded:: 1.6 The option `"warn"` was added in 1.6. min_frequency : int or float, default=None Specifies the minimum frequency below which a category will be considered infrequent. - If `int`, categories with a smaller cardinality will be considered infrequent. - If `float`, categories with a smaller cardinality than `min_frequency * n_samples` will be considered infrequent. .. versionadded:: 1.1 Read more in the :ref:`User Guide <encoder_infrequent_categories>`. max_categories : int, default=None Specifies an upper limit to the number of output features for each input feature when considering infrequent categories. If there are infrequent categories, `max_categories` includes the category representing the infrequent categories along with the frequent categories. If `None`, there is no limit to the number of output features. .. versionadded:: 1.1 Read more in the :ref:`User Guide <encoder_infrequent_categories>`. feature_name_combiner : "concat" or callable, default="concat" Callable with signature `def callable(input_feature, category)` that returns a string. This is used to create feature names to be returned by :meth:`get_feature_names_out`. `"concat"` concatenates encoded feature name and category with `feature + "_" + str(category)`.E.g. feature X with values 1, 6, 7 create feature names `X_1, X_6, X_7`. .. versionadded:: 1.3 Attributes ---------- categories_ : list of arrays The categories of each feature determined during fitting (in order of the features in X and corresponding with the output of ``transform``). This includes the category specified in ``drop`` (if any). drop_idx_ : array of shape (n_features,) - ``drop_idx_[i]`` is the index in ``categories_[i]`` of the category to be dropped for each feature. - ``drop_idx_[i] = None`` if no category is to be dropped from the feature with index ``i``, e.g. when `drop='if_binary'` and the feature isn't binary. - ``drop_idx_ = None`` if all the transformed features will be retained. If infrequent categories are enabled by setting `min_frequency` or `max_categories` to a non-default value and `drop_idx[i]` corresponds to an infrequent category, then the entire infrequent category is dropped. .. versionchanged:: 0.23 Added the possibility to contain `None` values. infrequent_categories_ : list of ndarray Defined only if infrequent categories are enabled by setting `min_frequency` or `max_categories` to a non-default value. `infrequent_categories_[i]` are the infrequent categories for feature `i`. If the feature `i` has no infrequent categories `infrequent_categories_[i]` is None. .. versionadded:: 1.1 n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 1.0 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Defined only when `X` has feature names that are all strings. .. versionadded:: 1.0 feature_name_combiner : callable or None Callable with signature `def callable(input_feature, category)` that returns a string. This is used to create feature names to be returned by :meth:`get_feature_names_out`. .. versionadded:: 1.3 See Also -------- OrdinalEncoder : Performs an ordinal (integer) encoding of the categorical features. TargetEncoder : Encodes categorical features using the target. sklearn.feature_extraction.DictVectorizer : Performs a one-hot encoding of dictionary items (also handles string-valued features). sklearn.feature_extraction.FeatureHasher : Performs an approximate one-hot encoding of dictionary items or strings. LabelBinarizer : Binarizes labels in a one-vs-all fashion. MultiLabelBinarizer : Transforms between iterable of iterables and a multilabel format, e.g. a (samples x classes) binary matrix indicating the presence of a class label. Examples -------- Given a dataset with two features, we let the encoder find the unique values per feature and transform the data to a binary one-hot encoding. >>> from sklearn.preprocessing import OneHotEncoder One can discard categories not seen during `fit`: >>> enc = OneHotEncoder(handle_unknown='ignore') >>> X = [['Male', 1], ['Female', 3], ['Female', 2]] >>> enc.fit(X) OneHotEncoder(handle_unknown='ignore') >>> enc.categories_ [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)] >>> enc.transform([['Female', 1], ['Male', 4]]).toarray() array([[1., 0., 1., 0., 0.], [0., 1., 0., 0., 0.]]) >>> enc.inverse_transform([[0, 1, 1, 0, 0], [0, 0, 0, 1, 0]]) array([['Male', 1], [None, 2]], dtype=object) >>> enc.get_feature_names_out(['gender', 'group']) array(['gender_Female', 'gender_Male', 'group_1', 'group_2', 'group_3'], ...) One can always drop the first column for each feature: >>> drop_enc = OneHotEncoder(drop='first').fit(X) >>> drop_enc.categories_ [array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)] >>> drop_enc.transform([['Female', 1], ['Male', 2]]).toarray() array([[0., 0., 0.], [1., 1., 0.]]) Or drop a column for feature only having 2 categories: >>> drop_binary_enc = OneHotEncoder(drop='if_binary').fit(X) >>> drop_binary_enc.transform([['Female', 1], ['Male', 2]]).toarray() array([[0., 1., 0., 0.], [1., 0., 1., 0.]]) One can change the way feature names are created. >>> def custom_combiner(feature, category): ... return str(feature) + "_" + type(category).__name__ + "_" + str(category) >>> custom_fnames_enc = OneHotEncoder(feature_name_combiner=custom_combiner).fit(X) >>> custom_fnames_enc.get_feature_names_out() array(['x0_str_Female', 'x0_str_Male', 'x1_int_1', 'x1_int_2', 'x1_int_3'], dtype=object) Infrequent categories are enabled by setting `max_categories` or `min_frequency`. >>> import numpy as np >>> X = np.array([["a"] * 5 + ["b"] * 20 + ["c"] * 10 + ["d"] * 3], dtype=object).T >>> ohe = OneHotEncoder(max_categories=3, sparse_output=False).fit(X) >>> ohe.infrequent_categories_ [array(['a', 'd'], dtype=object)] >>> ohe.transform([["a"], ["b"]]) array([[0., 0., 1.], [1., 0., 0.]]) """ _parameter_constraints: dict = { "categories": [StrOptions({"auto"}), list], "drop": [StrOptions({"first", "if_binary"}), "array-like", None], "dtype": "no_validation", # validation delegated to numpy "handle_unknown": [ StrOptions({"error", "ignore", "infrequent_if_exist", "warn"}) ], "max_categories": [Interval(Integral, 1, None, closed="left"), None], "min_frequency": [ Interval(Integral, 1, None, closed="left"), Interval(RealNotInt, 0, 1, closed="neither"), None, ], "sparse_output": ["boolean"], "feature_name_combiner": [StrOptions({"concat"}), callable], } def __init__( self, *, categories="auto", drop=None, sparse_output=True, dtype=np.float64, handle_unknown="error", min_frequency=None, max_categories=None, feature_name_combiner="concat", ): self.categories = categories self.sparse_output = sparse_output self.dtype = dtype self.handle_unknown = handle_unknown self.drop = drop self.min_frequency = min_frequency self.max_categories = max_categories self.feature_name_combiner = feature_name_combiner def _map_drop_idx_to_infrequent(self, feature_idx, drop_idx): """Convert `drop_idx` into the index for infrequent categories. If there are no infrequent categories, then `drop_idx` is returned. This method is called in `_set_drop_idx` when the `drop` parameter is an array-like. """ if not self._infrequent_enabled: return drop_idx default_to_infrequent = self._default_to_infrequent_mappings[feature_idx] if default_to_infrequent is None: return drop_idx # Raise error when explicitly dropping a category that is infrequent infrequent_indices = self._infrequent_indices[feature_idx] if infrequent_indices is not None and drop_idx in infrequent_indices: categories = self.categories_[feature_idx] raise ValueError( f"Unable to drop category {categories[drop_idx].item()!r} from" f" feature {feature_idx} because it is infrequent" ) return default_to_infrequent[drop_idx] def _set_drop_idx(self): """Compute the drop indices associated with `self.categories_`. If `self.drop` is: - `None`, No categories have been dropped. - `'first'`, All zeros to drop the first category. - `'if_binary'`, All zeros if the category is binary and `None` otherwise. - array-like, The indices of the categories that match the categories in `self.drop`. If the dropped category is an infrequent category, then the index for the infrequent category is used. This means that the entire infrequent category is dropped. This methods defines a public `drop_idx_` and a private `_drop_idx_after_grouping`. - `drop_idx_`: Public facing API that references the drop category in `self.categories_`. - `_drop_idx_after_grouping`: Used internally to drop categories *after* the infrequent categories are grouped together. If there are no infrequent categories or drop is `None`, then `drop_idx_=_drop_idx_after_grouping`. """ if self.drop is None: drop_idx_after_grouping = None elif isinstance(self.drop, str): if self.drop == "first": drop_idx_after_grouping = np.zeros(len(self.categories_), dtype=object) elif self.drop == "if_binary": n_features_out_no_drop = [len(cat) for cat in self.categories_] if self._infrequent_enabled: for i, infreq_idx in enumerate(self._infrequent_indices): if infreq_idx is None: continue n_features_out_no_drop[i] -= infreq_idx.size - 1 drop_idx_after_grouping = np.array( [ 0 if n_features_out == 2 else None for n_features_out in n_features_out_no_drop ], dtype=object, ) else: drop_array = np.asarray(self.drop, dtype=object) droplen = len(drop_array) if droplen != len(self.categories_): msg = ( "`drop` should have length equal to the number " "of features ({}), got {}" ) raise ValueError(msg.format(len(self.categories_), droplen)) missing_drops = [] drop_indices = [] for feature_idx, (drop_val, cat_list) in enumerate( zip(drop_array, self.categories_) ): if not is_scalar_nan(drop_val): drop_idx = np.where(cat_list == drop_val)[0] if drop_idx.size: # found drop idx drop_indices.append( self._map_drop_idx_to_infrequent(feature_idx, drop_idx[0]) ) else: missing_drops.append((feature_idx, drop_val)) continue # drop_val is nan, find nan in categories manually if is_scalar_nan(cat_list[-1]): drop_indices.append( self._map_drop_idx_to_infrequent(feature_idx, cat_list.size - 1) ) else: # nan is missing missing_drops.append((feature_idx, drop_val)) if any(missing_drops): msg = ( "The following categories were supposed to be " "dropped, but were not found in the training " "data.\n{}".format( "\n".join( [ "Category: {}, Feature: {}".format(c, v) for c, v in missing_drops ] ) ) ) raise ValueError(msg) drop_idx_after_grouping = np.array(drop_indices, dtype=object) # `_drop_idx_after_grouping` are the categories to drop *after* the infrequent # categories are grouped together. If needed, we remap `drop_idx` back # to the categories seen in `self.categories_`. self._drop_idx_after_grouping = drop_idx_after_grouping if not self._infrequent_enabled or drop_idx_after_grouping is None: self.drop_idx_ = self._drop_idx_after_grouping else: drop_idx_ = [] for feature_idx, drop_idx in enumerate(drop_idx_after_grouping): default_to_infrequent = self._default_to_infrequent_mappings[ feature_idx ] if drop_idx is None or default_to_infrequent is None: orig_drop_idx = drop_idx else: orig_drop_idx = np.flatnonzero(default_to_infrequent == drop_idx)[0] drop_idx_.append(orig_drop_idx) self.drop_idx_ = np.asarray(drop_idx_, dtype=object) def _compute_transformed_categories(self, i, remove_dropped=True): """Compute the transformed categories used for column `i`. 1. If there are infrequent categories, the category is named 'infrequent_sklearn'. 2. Dropped columns are removed when remove_dropped=True. """ cats = self.categories_[i] if self._infrequent_enabled: infreq_map = self._default_to_infrequent_mappings[i] if infreq_map is not None: frequent_mask = infreq_map < infreq_map.max() infrequent_cat = "infrequent_sklearn" # infrequent category is always at the end cats = np.concatenate( (cats[frequent_mask], np.array([infrequent_cat], dtype=object)) ) if remove_dropped: cats = self._remove_dropped_categories(cats, i) return cats def _remove_dropped_categories(self, categories, i): """Remove dropped categories.""" if ( self._drop_idx_after_grouping is not None and self._drop_idx_after_grouping[i] is not None ): return np.delete(categories, self._drop_idx_after_grouping[i]) return categories def _compute_n_features_outs(self): """Compute the n_features_out for each input feature.""" output = [len(cats) for cats in self.categories_] if self._drop_idx_after_grouping is not None: for i, drop_idx in enumerate(self._drop_idx_after_grouping): if drop_idx is not None: output[i] -= 1 if not self._infrequent_enabled: return output # infrequent is enabled, the number of features out are reduced # because the infrequent categories are grouped together for i, infreq_idx in enumerate(self._infrequent_indices): if infreq_idx is None: continue output[i] -= infreq_idx.size - 1 return output @_fit_context(prefer_skip_nested_validation=True) def fit(self, X, y=None): """ Fit OneHotEncoder to X. Parameters ---------- X : array-like of shape (n_samples, n_features) The data to determine the categories of each feature. y : None Ignored. This parameter exists only for compatibility with :class:`~sklearn.pipeline.Pipeline`. Returns ------- self Fitted encoder. """ self._fit( X, handle_unknown=self.handle_unknown, ensure_all_finite="allow-nan", ) self._set_drop_idx() self._n_features_outs = self._compute_n_features_outs() return self def transform(self, X): """ Transform X using one-hot encoding. If `sparse_output=True` (default), it returns an instance of :class:`scipy.sparse._csr.csr_matrix` (CSR format). If there are infrequent categories for a feature, set by specifying `max_categories` or `min_frequency`, the infrequent categories are grouped into a single category. Parameters ---------- X : array-like of shape (n_samples, n_features) The data to encode. Returns ------- X_out : {ndarray, sparse matrix} of shape \ (n_samples, n_encoded_features) Transformed input. If `sparse_output=True`, a sparse matrix will be returned. """ check_is_fitted(self) transform_output = _get_output_config("transform", estimator=self)["dense"] if transform_output != "default" and self.sparse_output: capitalize_transform_output = transform_output.capitalize() raise ValueError( f"{capitalize_transform_output} output does not support sparse data." f" Set sparse_output=False to output {transform_output} dataframes or" f" disable {capitalize_transform_output} output via" '` ohe.set_output(transform="default").' ) # validation of X happens in _check_X called by _transform if self.handle_unknown == "warn": warn_on_unknown, handle_unknown = True, "infrequent_if_exist" else: warn_on_unknown = self.drop is not None and self.handle_unknown in { "ignore", "infrequent_if_exist", } handle_unknown = self.handle_unknown X_int, X_mask = self._transform( X, handle_unknown=handle_unknown, ensure_all_finite="allow-nan", warn_on_unknown=warn_on_unknown, ) n_samples, n_features = X_int.shape if self._drop_idx_after_grouping is not None: to_drop = self._drop_idx_after_grouping.copy() # We remove all the dropped categories from mask, and decrement all # categories that occur after them to avoid an empty column. keep_cells = X_int != to_drop for i, cats in enumerate(self.categories_): # drop='if_binary' but feature isn't binary if to_drop[i] is None: # set to cardinality to not drop from X_int to_drop[i] = len(cats) to_drop = to_drop.reshape(1, -1) X_int[X_int > to_drop] -= 1 X_mask &= keep_cells mask = X_mask.ravel() feature_indices = np.cumsum([0] + self._n_features_outs) indices = (X_int + feature_indices[:-1]).ravel()[mask] indptr = np.empty(n_samples + 1, dtype=int) indptr[0] = 0 np.sum(X_mask, axis=1, out=indptr[1:], dtype=indptr.dtype) np.cumsum(indptr[1:], out=indptr[1:]) data = np.ones(indptr[-1]) out = sparse.csr_matrix( (data, indices, indptr), shape=(n_samples, feature_indices[-1]), dtype=self.dtype, ) if not self.sparse_output: return out.toarray() else: return out def inverse_transform(self, X): """ Convert the data back to the original representation. When unknown categories are encountered (all zeros in the one-hot encoding), ``None`` is used to represent this category. If the feature with the unknown category has a dropped category, the dropped category will be its inverse. For a given input feature, if there is an infrequent category, 'infrequent_sklearn' will be used to represent the infrequent category. Parameters ---------- X : {array-like, sparse matrix} of shape \ (n_samples, n_encoded_features) The transformed data. Returns ------- X_original : ndarray of shape (n_samples, n_features) Inverse transformed array. """ check_is_fitted(self) X = check_array(X, accept_sparse="csr") n_samples, _ = X.shape n_features = len(self.categories_) n_features_out = np.sum(self._n_features_outs) # validate shape of passed X msg = ( "Shape of the passed X data is not correct. Expected {0} columns, got {1}." ) if X.shape[1] != n_features_out: raise ValueError(msg.format(n_features_out, X.shape[1])) transformed_features = [ self._compute_transformed_categories(i, remove_dropped=False) for i, _ in enumerate(self.categories_) ] # create resulting array of appropriate dtype dt = np.result_type(*[cat.dtype for cat in transformed_features]) X_tr = np.empty((n_samples, n_features), dtype=dt) j = 0 found_unknown = {} if self._infrequent_enabled: infrequent_indices = self._infrequent_indices else: infrequent_indices = [None] * n_features for i in range(n_features): cats_wo_dropped = self._remove_dropped_categories( transformed_features[i], i ) n_categories = cats_wo_dropped.shape[0] # Only happens if there was a column with a unique # category. In this case we just fill the column with this # unique category value. if n_categories == 0: X_tr[:, i] = self.categories_[i][self._drop_idx_after_grouping[i]] j += n_categories continue sub = X[:, j : j + n_categories] # for sparse X argmax returns 2D matrix, ensure 1D array labels = np.asarray(sub.argmax(axis=1)).flatten() X_tr[:, i] = cats_wo_dropped[labels] if self.handle_unknown == "ignore" or ( self.handle_unknown in ("infrequent_if_exist", "warn") and infrequent_indices[i] is None ): unknown = np.asarray(sub.sum(axis=1) == 0).flatten() # ignored unknown categories: we have a row of all zero if unknown.any(): # if categories were dropped then unknown categories will # be mapped to the dropped category if ( self._drop_idx_after_grouping is None or self._drop_idx_after_grouping[i] is None ): found_unknown[i] = unknown else: X_tr[unknown, i] = self.categories_[i][ self._drop_idx_after_grouping[i] ] else: dropped = np.asarray(sub.sum(axis=1) == 0).flatten() if dropped.any(): if self._drop_idx_after_grouping is None: all_zero_samples = np.flatnonzero(dropped) raise ValueError( f"Samples {all_zero_samples} can not be inverted " "when drop=None and handle_unknown='error' " "because they contain all zeros" ) # we can safely assume that all of the nulls in each column # are the dropped value drop_idx = self._drop_idx_after_grouping[i] X_tr[dropped, i] = transformed_features[i][drop_idx] j += n_categories # if ignored are found: potentially need to upcast result to # insert None values if found_unknown: if X_tr.dtype != object: X_tr = X_tr.astype(object) for idx, mask in found_unknown.items(): X_tr[mask, idx] = None return X_tr def get_feature_names_out(self, input_features=None): """Get output feature names for transformation. Parameters ---------- input_features : array-like of str or None, default=None Input features. - If `input_features` is `None`, then `feature_names_in_` is used as feature names in. If `feature_names_in_` is not defined, then the following input feature names are generated: `["x0", "x1", ..., "x(n_features_in_ - 1)"]`. - If `input_features` is an array-like, then `input_features` must match `feature_names_in_` if `feature_names_in_` is defined. Returns ------- feature_names_out : ndarray of str objects Transformed feature names. """ check_is_fitted(self) input_features = _check_feature_names_in(self, input_features) cats = [ self._compute_transformed_categories(i) for i, _ in enumerate(self.categories_) ] name_combiner = self._check_get_feature_name_combiner() feature_names = [] for i in range(len(cats)): names = [name_combiner(input_features[i], t) for t in cats[i]] feature_names.extend(names) return np.array(feature_names, dtype=object) def _check_get_feature_name_combiner(self): if self.feature_name_combiner == "concat": return lambda feature, category: feature + "_" + str(category) else: # callable dry_run_combiner = self.feature_name_combiner("feature", "category") if not isinstance(dry_run_combiner, str): raise TypeError( "When `feature_name_combiner` is a callable, it should return a " f"Python string. Got {type(dry_run_combiner)} instead." ) return self.feature_name_combiner
OneHotEncoder
python
google__jax
jax/_src/pallas/mosaic_gpu/lowering.py
{ "start": 3295, "end": 3674 }
class ____: axis_names: _AxisNames lowering_semantics: mgpu.LoweringSemantics @property def arrival_multiplier(self) -> int: return ( WARPGROUP_SIZE if self.lowering_semantics == mgpu.LoweringSemantics.Lane else 1 ) AnyBarrier = mgpu.Barrier | mgpu.ClusterBarrier @dataclasses.dataclass(kw_only=True, frozen=True)
ResourceEstimatorContext
python
jazzband__django-simple-history
simple_history/registry_tests/tests.py
{ "start": 3500, "end": 6544 }
class ____(TestCase): def test_tracked_abstract_base(self): self.assertEqual( sorted( f.attname for f in TrackedWithAbstractBase.history.model._meta.fields ), sorted( [ "id", "history_id", "history_change_reason", "history_date", "history_user_id", "history_type", ] ), ) def test_tracked_concrete_base(self): self.assertEqual( sorted( f.attname for f in TrackedWithConcreteBase.history.model._meta.fields ), sorted( [ "id", "trackedconcretebase_ptr_id", "history_id", "history_change_reason", "history_date", "history_user_id", "history_type", ] ), ) def test_multiple_tracked_bases(self): with self.assertRaises(exceptions.MultipleRegistrationsError): class TrackedWithMultipleAbstractBases( TrackedAbstractBaseA, TrackedAbstractBaseB ): pass def test_tracked_abstract_and_untracked_concrete_base(self): self.assertEqual( sorted(f.attname for f in InheritTracking1.history.model._meta.fields), sorted( [ "id", "untrackedconcretebase_ptr_id", "history_id", "history_change_reason", "history_date", "history_user_id", "history_type", ] ), ) def test_indirect_tracked_abstract_base(self): self.assertEqual( sorted(f.attname for f in InheritTracking2.history.model._meta.fields), sorted( [ "id", "baseinherittracking2_ptr_id", "history_id", "history_change_reason", "history_date", "history_user_id", "history_type", ] ), ) def test_indirect_tracked_concrete_base(self): self.assertEqual( sorted(f.attname for f in InheritTracking3.history.model._meta.fields), sorted( [ "id", "baseinherittracking3_ptr_id", "history_id", "history_change_reason", "history_date", "history_user_id", "history_type", ] ), ) def test_registering_with_tracked_abstract_base(self): with self.assertRaises(exceptions.MultipleRegistrationsError): register(InheritTracking4)
TestTrackingInheritance
python
realpython__materials
bulk-file-rename-tool-python/source_code_step_2/rprename/views.py
{ "start": 153, "end": 314 }
class ____(QWidget, Ui_Window): def __init__(self): super().__init__() self._setupUI() def _setupUI(self): self.setupUi(self)
Window
python
apache__airflow
airflow-core/tests/unit/serialization/test_dag_serialization.py
{ "start": 158620, "end": 160311 }
class ____: """Test schema defaults functionality.""" def test_get_schema_defaults_operator(self): """Test getting schema defaults for operator type.""" schema_defaults = SerializedBaseOperator.get_schema_defaults("operator") assert isinstance(schema_defaults, dict) # Should contain expected operator defaults expected_fields = [ "owner", "trigger_rule", "depends_on_past", "retries", "queue", "pool", "pool_slots", "priority_weight", "weight_rule", "do_xcom_push", ] for field in expected_fields: assert field in schema_defaults, f"Expected field {field} not in schema defaults" def test_get_schema_defaults_nonexistent_type(self): """Test getting schema defaults for nonexistent type.""" schema_defaults = SerializedBaseOperator.get_schema_defaults("nonexistent") assert schema_defaults == {} def test_get_operator_optional_fields_from_schema(self): """Test getting optional fields from schema.""" optional_fields = SerializedBaseOperator.get_operator_optional_fields_from_schema() assert isinstance(optional_fields, set) # Should not contain required fields required_fields = { "task_type", "_task_module", "task_id", "ui_color", "ui_fgcolor", "template_fields", } overlap = optional_fields & required_fields assert not overlap, f"Optional fields should not overlap with required fields: {overlap}"
TestSchemaDefaults
python
huggingface__transformers
src/transformers/models/sam3/configuration_sam3.py
{ "start": 15456, "end": 20328 }
class ____(PreTrainedConfig): r""" Configuration class to store the configuration of a [`Sam3Model`]. Instantiating a configuration defaults will yield a similar configuration to that of SAM 3 [facebook/sam3](https://huggingface.co/facebook/sam3) architecture. This is the main configuration class that combines all sub-configurations for the SAM3 model. Args: vision_config (`dict` or `Sam3VisionConfig`, *optional*): Configuration for the vision encoder. text_config (`dict` or `Sam3TextConfig`, *optional*): Configuration for the text encoder. geometry_encoder_config (`dict` or `Sam3GeometryEncoderConfig`, *optional*): Configuration for the geometry encoder. detr_encoder_config (`dict` or `Sam3DETREncoderConfig`, *optional*): Configuration for the DETR encoder. detr_decoder_config (`dict` or `Sam3DETRDecoderConfig`, *optional*): Configuration for the DETR decoder. mask_decoder_config (`dict` or `Sam3MaskDecoderConfig`, *optional*): Configuration for the mask decoder. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing weight matrices. Example: ```python >>> from transformers import Sam3Config, Sam3Model >>> # Initializing a SAM3 configuration >>> configuration = Sam3Config() >>> # Initializing a model from the configuration >>> model = Sam3Model(configuration) >>> # Accessing the model configuration >>> configuration = model.config ``` """ model_type = "sam3" is_composition = True sub_configs = { "vision_config": Sam3VisionConfig, "text_config": CLIPTextConfig, "geometry_encoder_config": Sam3GeometryEncoderConfig, "detr_encoder_config": Sam3DETREncoderConfig, "detr_decoder_config": Sam3DETRDecoderConfig, "mask_decoder_config": Sam3MaskDecoderConfig, } def __init__( self, vision_config=None, text_config=None, geometry_encoder_config=None, detr_encoder_config=None, detr_decoder_config=None, mask_decoder_config=None, initializer_range=0.02, **kwargs, ): # Vision config if vision_config is None: vision_config = {} if isinstance(vision_config, dict): self.vision_config = Sam3VisionConfig(**vision_config) else: self.vision_config = vision_config # Text config (CLIPTextModelWithProjection defaults) if text_config is None: text_config = { "vocab_size": 49408, "hidden_size": 1024, "intermediate_size": 4096, # hidden_size * mlp_ratio (1024 * 4) "projection_dim": 512, # CLIP's internal projection dimension "num_hidden_layers": 24, "num_attention_heads": 16, "max_position_embeddings": 32, "hidden_act": "gelu", } if isinstance(text_config, dict): self.text_config = CLIPTextConfig(**text_config) else: self.text_config = text_config # Geometry encoder config if geometry_encoder_config is None: geometry_encoder_config = {} if isinstance(geometry_encoder_config, dict): self.geometry_encoder_config = Sam3GeometryEncoderConfig(**geometry_encoder_config) else: self.geometry_encoder_config = geometry_encoder_config # DETR encoder config if detr_encoder_config is None: detr_encoder_config = {} if isinstance(detr_encoder_config, dict): self.detr_encoder_config = Sam3DETREncoderConfig(**detr_encoder_config) else: self.detr_encoder_config = detr_encoder_config # DETR decoder config if detr_decoder_config is None: detr_decoder_config = {} if isinstance(detr_decoder_config, dict): self.detr_decoder_config = Sam3DETRDecoderConfig(**detr_decoder_config) else: self.detr_decoder_config = detr_decoder_config # Mask decoder config if mask_decoder_config is None: mask_decoder_config = {} if isinstance(mask_decoder_config, dict): self.mask_decoder_config = Sam3MaskDecoderConfig(**mask_decoder_config) else: self.mask_decoder_config = mask_decoder_config self.initializer_range = initializer_range super().__init__(**kwargs) __all__ = [ "Sam3Config", "Sam3ViTConfig", "Sam3VisionConfig", "Sam3GeometryEncoderConfig", "Sam3DETREncoderConfig", "Sam3DETRDecoderConfig", "Sam3MaskDecoderConfig", ]
Sam3Config
python
google__jax
jax/_src/pjit.py
{ "start": 52959, "end": 66270 }
class ____: val: Any def __hash__(self): return hash(self.__class__) def __eq__(self, other): return isinstance(other, IgnoreKey) # ignore self.val! def pjit_check_aval_sharding( shardings, flat_avals, names: Sequence[str], what_aval: str, allow_uneven_sharding: bool, allow_partial_manual: bool = False): for aval, s, name in zip(flat_avals, shardings, names): if isinstance(s, (UnspecifiedValue, AUTO)): continue name_str = f' with pytree key path {name}' if name else '' shape = aval.shape try: # Sharding interfaces can implement `check_compatible_aval` as an optional # method to raise a more meaningful error. if hasattr(s, 'check_compatible_aval'): s.check_compatible_aval(shape) else: s._to_xla_hlo_sharding(len(shape)) except ValueError as e: raise ValueError( f'One of {what_aval}{name_str} is incompatible with its sharding ' f'annotation {s}: {e}') # Use the `OpSharding` proto to find out how many ways each dimension of # the aval is sharded. This approach will work across all # Sharding. hlo_sharding = s._to_xla_hlo_sharding(len(shape)) assert hlo_sharding is not None num_ways_dim_sharded, _ = op_shardings.get_num_ways_dim_sharded( hlo_sharding, allow_partial_manual) for i, size in enumerate(num_ways_dim_sharded): if not allow_uneven_sharding and shape[i] % size != 0: raise ValueError(f"One of {what_aval}{name_str} was given the sharding " f"of {s}, which implies that " f"the global size of its dimension {i} should be " f"divisible by {size}, but it is equal to {shape[i]} " f"(full shape: {shape})") def check_aval_layout_compatibility( layouts, flat_avals, names: Sequence[str], what_aval: str): for aval, l, name in zip(flat_avals, layouts, names): if l is None or isinstance(l, AutoLayout): continue name_str = f' with pytree key path {name}' if name else '' try: l.check_compatible_aval(aval.shape) except ValueError as e: raise ValueError( f'One of {what_aval}{name_str} is incompatible with its layout ' f'annotation {l}: {e}') # -------------------- pjit rules -------------------- jit_p = core.Primitive("jit") jit_p.is_effectful = lambda params: bool(params['jaxpr'].effects) # type: ignore jit_p.multiple_results = True jit_p.skip_canonicalization = True def _is_high(*_, jaxpr, **__) -> bool: return jaxpr.jaxpr.is_high jit_p.is_high = _is_high # type: ignore def _to_lojax(*hi_args, jaxpr, **params): # convert closed-over boxes to explicit args jaxpr, closed_over_himutables = pe.convert_const_himutables(jaxpr) hi_args = [*closed_over_himutables, *hi_args] params = _converted_mutables_add_params(len(closed_over_himutables), **params) # expand pjit params that must match number of lo inputs/outputs lo_nums_in = [len(aval.lo_ty()) for aval in jaxpr.in_aval_qdds] lo_nums_out = [len(t.lo_ty()) for t in jaxpr.out_avals] lo_muts_out = pe.num_himuts_out(jaxpr) params = _lojax_expand_params(lo_nums_in, lo_nums_out, lo_muts_out, **params) # collect lo input values lo_args = [lo_val for aval, x in zip(jaxpr.in_aval_qdds, hi_args) for lo_val in (aval.read_loval(x) if aval.has_qdd else aval.lower_val(x))] # lower the jaxpr and bind it using lo input values lo_jaxpr = pe.lower_jaxpr(jaxpr) all_outs = jit_p.bind(*lo_args, jaxpr=lo_jaxpr, **params) out_mut, lo_outs = split_list(all_outs, [lo_muts_out]) pe.apply_himut(jaxpr, hi_args, out_mut) return pe.raise_lo_outs(jaxpr.out_avals, lo_outs) jit_p.to_lojax = _to_lojax def _converted_mutables_add_params( n, *, donated_invars, in_shardings, in_layouts, **params): donated_invars = (False,) * n + donated_invars in_shardings = (UNSPECIFIED,) * n + in_shardings in_layouts = (None,) * n + in_layouts return dict(params, donated_invars=donated_invars, in_shardings=in_shardings, in_layouts=in_layouts) def _lojax_expand_params( nums_in, nums_out, muts_out, *, donated_invars, in_shardings, in_layouts, out_shardings, out_layouts, **params): # some pjit params match the length of hi_jaxpr.invars/outvars, so when # lowering we must expand them to match their number of lojax types def expand(ns, xs): return tuple(y for n, x in zip(ns, xs) for y in (x,) * n) donated_invars = expand(nums_in , donated_invars) in_shardings = expand(nums_in , in_shardings ) in_layouts = expand(nums_in , in_layouts ) out_shardings = expand(nums_out, out_shardings ) out_layouts = expand(nums_out, out_layouts ) # also, the lo_jaxpr has pure outputs corresponding to mutable hi_jaxpr types out_shardings = (UNSPECIFIED,) * muts_out + out_shardings out_layouts = (None,) * muts_out + out_layouts new_params = dict(params, donated_invars=donated_invars, in_shardings=in_shardings, in_layouts=in_layouts, out_shardings=out_shardings, out_layouts=out_layouts) return new_params def _resolve_in_layouts(args, jit_in_layouts, resolved_in_shardings, in_avals) -> Sequence[Layout | AutoLayout | None]: # If device or backend is set, return the default layout. This is because you # can pass arrays on cpu (with untiled layouts) to jit with backend='tpu' # which causes error checks to fail. Returning the default layout allows # this to exist. It's the same for handling shardings. if pxla.check_device_backend_on_shardings(resolved_in_shardings): return (None,) * len(jit_in_layouts) resolved_in_layouts: list[Layout | AutoLayout | None] = [] for arg, jit_in_l, rs, aval in safe_zip( args, jit_in_layouts, resolved_in_shardings, in_avals): committed = arg.committed # `arg_layout` is only used for checking purposes in the `else` branch # below. We cannot replace default layout with None to raise nicer errors. # `dispatch_arg_layout` replaces default layouts with `None` to simplify # dispatch and lowering logic downstream. if arg.format is not None: arg_layout = arg.format.layout dispatch_arg_layout = (None if pxla.is_default_layout(arg_layout, rs, aval) else arg_layout) else: arg_layout, dispatch_arg_layout = None, None # Sharding can be unspecified when array is committed if it's a PmapSharding. is_pmap_sharding = (isinstance(rs, UnspecifiedValue) or isinstance(arg.sharding, PmapSharding)) if jit_in_l is None: if committed: if is_pmap_sharding: resolved_in_layouts.append(None) else: resolved_in_layouts.append(dispatch_arg_layout) else: resolved_in_layouts.append(None) else: # arg_layout can be None because some backends don't implement the # required layout methods. Hence `arr.format` can return # `Format(None, sharding)` if (committed and not is_pmap_sharding and arg_layout is not None and not pxla.is_user_xla_layout_equal(jit_in_l, arg_layout)): extra_msg = '' if isinstance(jit_in_l, AutoLayout): extra_msg = ( ' The layout given to `jax.jit` is `Layout.AUTO` but' ' the corresponding argument passed is a `jax.Array` with a' ' concrete layout. Consider passing a `jax.ShapeDtypeStruct`' ' instead of `jax.Array` as an argument to the jitted function ' ' when using `Layout.AUTO`.' ) raise ValueError('Layout passed to jit does not match the layout ' 'on the respective arg. ' f'Got jit layout: {jit_in_l},\n' f'arg layout: {arg_layout} for arg type: {arg.aval}.' f'{extra_msg}') jit_in_l = (None if isinstance(jit_in_l, Layout) and pxla.is_default_layout(jit_in_l, rs, aval) else jit_in_l) resolved_in_layouts.append(jit_in_l) return tuple(resolved_in_layouts) def _resolve_out_layouts(out_layouts, out_shardings, out_avals): new_out_layouts = [] for out_l, out_s, out_aval in safe_zip(out_layouts, out_shardings, out_avals): if out_l is None: new_out_layouts.append(None) elif (isinstance(out_l, Layout) and pxla.is_default_layout(out_l, out_s, out_aval)): new_out_layouts.append(None) else: new_out_layouts.append(out_l) return tuple(new_out_layouts) def finalize_arg_sharding(arg_s, committed): if isinstance(arg_s, UnspecifiedValue): return arg_s else: if committed: # If the arg has a PmapSharding, then reshard it unconditionally. return UNSPECIFIED if isinstance(arg_s, PmapSharding) else arg_s else: assert isinstance(arg_s, Sharding) if dispatch.is_single_device_sharding(arg_s): return UNSPECIFIED raise NotImplementedError('Having uncommitted Array sharded on ' 'multiple devices is not supported.') def _resolve_in_shardings(args, pjit_in_shardings: Sequence[PjitSharding] ) -> Sequence[PjitSharding]: # If True, means that device or backend is set by the user on pjit and it # has the same semantics as device_put i.e. doesn't matter which device the # arg is on, reshard it to the device mentioned. So don't do any of the # checks and just return the pjit_in_shardings directly. `shard_args` will # handle the resharding. if pxla.check_device_backend_on_shardings(pjit_in_shardings): return pjit_in_shardings resolved_in_shardings: list[PjitSharding] = [] for arg, pjit_in_s in zip(args, pjit_in_shardings): # arg sharding can be None in case of ShapeDtypeStruct. jax.Array does # not allow None as the sharding. arg_s, committed = ((arg.sharding, arg.committed) if arg.sharding is not None else (UNSPECIFIED, False)) if isinstance(arg_s, NamedSharding) and arg_s.mesh.empty: arg_s, committed = UNSPECIFIED, False if isinstance(pjit_in_s, UnspecifiedValue): resolved_in_shardings.append(finalize_arg_sharding(arg_s, committed)) else: if (arg.is_np_array and not pjit_in_s.is_fully_replicated and # type: ignore[union-attr] xb.process_count() > 1): raise ValueError( 'Passing non-trivial shardings for numpy ' 'inputs is not allowed. To fix this error, either specify a ' 'replicated sharding explicitly or use ' '`jax.make_array_from_process_local_data(...)` ' 'to convert your host local numpy inputs to a jax.Array which you ' 'can pass to jit. ' 'If the numpy input is the same on each process, then you can use ' '`jax.make_array_from_callback(...) to create a `jax.Array` which ' f'you can pass to jit. Got arg type: {arg.aval}') if not isinstance(arg_s, UnspecifiedValue) and arg_s._is_concrete: # jax.jit does not allow resharding across different memory kinds even # if the argument is uncommitted. Use jax.device_put for those cases, # either outside or inside jax.jit. if pjit_in_s.memory_kind != arg_s.memory_kind: # type: ignore[union-attr] raise ValueError( 'Memory kinds passed to jax.jit does not match memory kind on the' f' respective arg. Got jit memory kind: {pjit_in_s.memory_kind}, ' # type: ignore[union-attr] f'arg memory kind: {arg_s.memory_kind} for arg type: {arg.aval}') if (committed and not isinstance(arg_s, PmapSharding) and not op_shardings.are_hlo_shardings_equal( pjit_in_s._to_xla_hlo_sharding(arg.ndim), # type: ignore[union-attr] arg_s._to_xla_hlo_sharding(arg.ndim))): raise ValueError('Sharding passed to jit does not match the sharding ' 'on the respective arg. ' f'Got jit sharding: {pjit_in_s},\n' f'arg sharding: {arg_s} for arg type: {arg.aval}') resolved_in_shardings.append(pjit_in_s) return tuple(resolved_in_shardings) def _resolve_and_lower( args, jaxpr: core.ClosedJaxpr, in_shardings, out_shardings, in_layouts, out_layouts, donated_invars, ctx_mesh, name, keep_unused, inline, lowering_platforms, lowering_parameters, pgle_profiler, compiler_options_kvs) -> pxla.MeshComputation: in_shardings = _resolve_in_shardings(args, in_shardings) in_layouts = _resolve_in_layouts(args, in_layouts, in_shardings, jaxpr.in_avals) out_layouts = _resolve_out_layouts(out_layouts, out_shardings, jaxpr.out_avals) return _pjit_lower( jaxpr, in_shardings, out_shardings, in_layouts, out_layouts, donated_invars, ctx_mesh, name, keep_unused, inline, compiler_options_kvs, lowering_platforms=lowering_platforms, lowering_parameters=lowering_parameters, pgle_profiler=pgle_profiler) _pgle_profiler_dict = weakref.WeakKeyDictionary() # type: ignore @dataclass(frozen=True)
IgnoreKey
python
kamyu104__LeetCode-Solutions
Python/search-in-a-sorted-array-of-unknown-size.py
{ "start": 32, "end": 531 }
class ____(object): def search(self, reader, target): """ :type reader: ArrayReader :type target: int :rtype: int """ left, right = 0, 19999 while left <= right: mid = left + (right-left)//2 response = reader.get(mid) if response > target: right = mid-1 elif response < target: left = mid+1 else: return mid return -1
Solution
python
pytorch__pytorch
test/test_mps.py
{ "start": 15550, "end": 16968 }
class ____(TestCaseMPS): def test_mps_memory_leak_detection(self): l = [] @self.wrap_with_mps_memory_check def no_leak(): pass # Trigger an intentional memory leak @self.wrap_with_mps_memory_check def leak_gpu0(): # increasing to 8MB to force acquiring a new block and overcome blocksize differences across platforms l.append(torch.randn(1024 * 1024 * 8, device=torch.device("mps"))) no_leak() # check if a runtime error for memory leak was emitted which would # confirm whether memory leak detection worked successfully or not. with self.assertRaisesRegex(RuntimeError, r"MPS driver API confirmed .+"): leak_gpu0() def test_copy_cast_no_leak(self): def step(x): x = x.to(device='cpu', dtype=torch.float32) x = x.to(device='mps', dtype=torch.float16) a = torch.randn(128, 128, device='mps', dtype=torch.float16) # Warm up / prebuild MPS shaders (otherwise check fails on 13.2) step(a) torch.mps.empty_cache() driver_before = torch.mps.driver_allocated_memory() step(a) torch.mps.empty_cache() driver_after = torch.mps.driver_allocated_memory() self.assertEqual(driver_before, driver_after, f"Detected {driver_after - driver_before} bytes leak of GPU memory")
TestMemoryLeak
python
tensorflow__tensorflow
tensorflow/python/autograph/operators/control_flow.py
{ "start": 27025, "end": 46556 }
class ____(object): """Verifies Python loops for TF-specific limits.""" __slots__ = ( 'iterations', 'check_inefficient_unroll', 'check_op_count_after_iteration', 'ops_before_iteration', ) def __init__(self): self.iterations = 1 self.check_inefficient_unroll = WARN_INEFFICIENT_UNROLL # Triggered when we decided to test the op counts. self.check_op_count_after_iteration = False def _get_ops(self): return set(ops.get_default_graph().get_operations()) def _check_unroll_limits(self): if self.iterations > PYTHON_MAX_ITERATIONS: raise ValueError('iteration limit exceeded') def _stop_checking_inefficient_unroll(self): self.check_inefficient_unroll = False self.check_op_count_after_iteration = False self.ops_before_iteration = None def _verify_inefficient_unroll(self): """Checks for possibly-inefficient creation of ops in a Python loop.""" assert self.ops_before_iteration is not None ops_after_iteration = self._get_ops() new_ops = tuple( op for op in ops_after_iteration if op not in self.ops_before_iteration) if len(new_ops) < INEFFICIENT_UNROLL_MIN_OPS: return False ag_logging.warning( 'Large unrolled loop detected. Did you mean to use a TF loop?' ' The following ops were created after iteration %s: %s' '\nSee' ' https://github.com/tensorflow/tensorflow/blob/master/' 'tensorflow/python/autograph/g3doc/reference/common_errors.md' '#warning-large-unrolled-loop-detected' '\n' 'Location:' '\n%s' '', self.iterations, new_ops, '\n'.join(traceback.format_stack())) return True def before_iteration(self): """Called before each iteration in a Python loop.""" if (self.check_inefficient_unroll and self.iterations > INEFFICIENT_UNROLL_MIN_ITERATIONS): self.ops_before_iteration = self._get_ops() self.check_op_count_after_iteration = True def after_iteration(self): """Called after each iteration in a Python loop.""" self.iterations += 1 self._check_unroll_limits() if self.check_op_count_after_iteration: did_warn = self._verify_inefficient_unroll() if did_warn: self._stop_checking_inefficient_unroll() # Only warn once. elif self.iterations > INEFFICIENT_UNROLL_MIN_ITERATIONS + 3: # Once deciding to check the op counts, only do it for a few iterations. self._stop_checking_inefficient_unroll() def _py_while_stmt(test, body, get_state, set_state, opts): """Overload of while_stmt that executes a Python while loop.""" del opts, get_state, set_state if __debug__: checker = _PythonLoopChecker() before_iteration = checker.before_iteration after_iteration = checker.after_iteration before_iteration() original_body = body def protected_body(): original_body() after_iteration() before_iteration() body = protected_body def guarded_test(): test_result = test() try: # Note: Using try/except and not tensor_util.is_tf_type to avoid # performance degradation. return bool(test_result) except errors_impl.OperatorNotAllowedInGraphError as e: ag_logging.log( 1, 'Caught error while evaluating while loop condition', exc_info=True) # TODO(mdan): distinguish between these two cases. raise NotImplementedError( 'The condition of while loop started as non-Tensor, then changed to' ' Tensor. This may happen either because variables changed type, or' ' when a break or return statement inside the loop depends on a' ' Tensor condition. In both cases, changing to a TF loop should' ' remove the error.\nSee ' 'https://github.com/tensorflow/tensorflow/blob/master/tensorflow/' 'python/autograph/g3doc/reference/limitations.md' '#consistency-of-control-flow-types for more info.') from e while guarded_test(): body() def _shape_invariants_mapping_to_positional_list(mapping, keys): # The keys are not expected to be hashable. mapping = {id(k): (k, v) for k, v in mapping} result = [] for k in keys: map_key, map_val = mapping.get(id(k), (None, None)) result.append( map_val if map_key is k else nest.map_structure(lambda _: None, k)) return tuple(result) # Textual description of what a legal TF loop variable is. This description # summarizes types that _placeholder_value below can handle. Keep the two # together and in sync. LEGAL_LOOP_TYPES = 'Tensor, int, float, bool or a list, tuple or dict thereof' def _placeholder_value(like, shape_invariant, original=None): """Constructs a (dummy) placeholder value for a loop-initialized variable. Args: like: Any object. The value created by the first iteration of the loop. If a Python scalar, the placeholder will be the zero value of that type. If a Tensor, the placeholder will be a zero tensor of matching shape and dtype. If a list, dict or tuple, the placeholder will be an identical structure of placeholders. shape_invariant: The shape invariant specified by the user (or None, if nothing was specified) for the respective variable. original: Any object. The value of the variable prior to entering the loop. Typically, this is one of the special "Undefined" value, because that's when a placeholder is needed. Returns: Either a zero value of structure, shape and dtype matching 'like', or 'original', if no such zero value could be created. """ if like is None: return original, None elif isinstance(like, (variables.Undefined, variables.UndefinedReturnValue)): return original, None elif isinstance(like, (int, float, bool)): return type(like)(0), None elif tensor_util.is_tf_type(like): like_shape = shape_invariant if shape_invariant is not None else like.shape if like_shape is None or like_shape.rank is None: return array_ops.zeros((), like.dtype), like_shape # If the shape contains dynamic values, set the corresponding starting # dimension to either zero or what the shape invariant specified. placeholder_shape = [] has_dynamic_dims = False for s, i in zip(like.shape, like_shape): if i is None: like_dim = 0 elif isinstance(i, tensor_shape.Dimension): if i.value is None: like_dim = 0 else: like_dim = i.value else: like_dim = i if s is None: placeholder_shape.append(like_dim) has_dynamic_dims = True elif isinstance(s, tensor_shape.Dimension): if s.value is None: placeholder_shape.append(like_dim) has_dynamic_dims = True else: placeholder_shape.append(s.value) else: placeholder_shape.append(s) if has_dynamic_dims: invariant = like_shape else: invariant = None return array_ops.zeros(placeholder_shape, like.dtype), invariant elif isinstance(like, (list, tuple, dict)): if shape_invariant is None: zipped = nest.map_structure(lambda v: _placeholder_value(v, None), nest.flatten(like)) else: zipped = nest.map_structure(_placeholder_value, nest.flatten(like), nest.flatten(shape_invariant)) vals, invars = zip(*zipped) return (nest.pack_sequence_as(like, vals), nest.pack_sequence_as(like, invars)) # This is to be caught by _try_handling_undefineds, to give more context. raise TypeError( "Found an unsupported type '{}' while creating placeholder for {}." ' Supported types include Tensor, int, float, bool, list, tuple or dict.' .format(type(like).__name__, like)) def _try_handling_undefineds(body, get_state, set_state, init_vars, nulls, shape_invariants, symbol_names): """Makes a best-effort attempt to substitute undefineds with placeholders. Note: this substitution requires two things to happen: 1. the types of loop variables could be inferred (usually by staging one iteration) 2. these types could be replaced by placeholders (e.g. zero values, for tensors). Args: body: a function representing the loop body. See while_stmt. get_state: state getter for the loop statement. See while_stmt. set_state: state getter for the loop statement. See while_stmt. init_vars: loop variables before entering the loop. See while_stmt. nulls: list of boolean flags indicating whether the corresponding loop var is None or undefined. shape_invariants: user-specified shape invariant for each loop variable. symbol_names: list of loop variable names. See while_stmt. Returns: A tuple (success, new_init_vars, extra_shape_invariants, failure_message): * success is a boolean flag indicating whether types could be successfully inferred (step 1 above) * new_init_vars contains the loop vars, with None or undefined values replaced by default values, where possible (step 2 above) * extra_shape_invariants contains shape invariants that would be needed by while_stmt, for instance if the placeholder values had a shape different from the corresponding loop outputs """ state_modified = False first_iter_vars = None failure_message = None try: # Stage an iteration of the loop body in a temporary graph. with func_graph.FuncGraph('tmp').as_default(): # This call to set_state helps report nicer error messages when symbols # are inconsistently used. # Another complication is that non_tensor values will be autocast to # Tensor by while_loop, and their static value lost. So we need to account # that here. def autocast_to_tensor(v): if isinstance( v, (int, float, bool, str, list, tuple, np.ndarray, np.generic)): init_val = tensor_conversion.convert_to_tensor_v2(v) return array_ops.placeholder(init_val.dtype, init_val.shape) return v autocast_init_vars = nest.map_structure(autocast_to_tensor, init_vars) set_state(autocast_init_vars) state_modified = True body() first_iter_vars = get_state() # Note: the actual placeholder value doesn't matter, because as the # staging proved, it will be replaced by an actual value before being # read. inits_and_invariants = tuple( (_placeholder_value(iv, i, v) if n else (v, None)) for v, n, iv, i in zip(init_vars, nulls, first_iter_vars, shape_invariants)) init_vars, extra_shape_invariants = zip(*inits_and_invariants) success = True except (UnboundLocalError, TypeError, ValueError, KeyError): ag_logging.log(1, 'Caught error while staging loop body', exc_info=True) # Fall back to the old functionality. It will likely result in an input # validation failure. exc = sys.exc_info() failure_message = ( 'Note: AutoGraph tried to define it automatically, but ran into a' ' {}: {}'.format(exc[0].__name__, exc[1])) finally: if state_modified: set_state(init_vars) # This check runs regardless, in case we captured non-Tensor inputs. verify_loop_init_vars( init_vars, symbol_names, first_iter_vars, extra_message=failure_message) return success, init_vars, extra_shape_invariants def _runtime_zero_iterations_errmsg(symbol_names, nulls, init_vars): """Creates an error message asking for the loop to iterate at least once.""" var_names = [] for sn, n, v in zip(symbol_names, nulls, init_vars): if not n: continue if isinstance(v, variables.UndefinedReturnValue): var_names.append('the function return value') else: var_names.append(sn) var_names = ', '.join(var_names) return 'loop must iterate at least once to initialize {}'.format(var_names) def _tf_while_stmt(test, body, get_state, set_state, symbol_names, opts): """Overload of while_stmt that stages a TF while_stmt.""" init_vars = get_state() orig_init_vars = init_vars nulls = tuple(_is_none_or_undef(v) for v in init_vars) if any(nulls): shape_invars_by_init_vals = { id(v): i for v, i in opts.get('shape_invariants', ()) } shape_invariants = tuple( shape_invars_by_init_vals.get(id(v), None) for v in orig_init_vars) (require_one_iteration, init_vars, extra_shape_invariants) = _try_handling_undefineds(body, get_state, set_state, init_vars, nulls, shape_invariants, symbol_names) else: require_one_iteration = False if require_one_iteration: merged_shape_invariants = dict(shape_invars_by_init_vals) # This has two roles: # 1. Shape invariants are remapped from the old init vars to the new ones. # 2. Any new shape invariants created by the init vars are kept, but only # if the user didn't already specify some. for v, nv, ni in zip(orig_init_vars, init_vars, extra_shape_invariants): merged_invariant = merged_shape_invariants.get(id(v), ni) if merged_invariant is not None: merged_shape_invariants[id(nv)] = merged_invariant merged_shape_invariants = tuple((nv, merged_shape_invariants[id(nv)]) for nv in init_vars if id(nv) in merged_shape_invariants) if merged_shape_invariants: opts = dict(**opts) opts['shape_invariants'] = merged_shape_invariants def aug_test(*loop_vars): if require_one_iteration: loop_vars = loop_vars[1:] set_state(loop_vars) return _verify_tf_condition(test(), 'while loop') def aug_body(*loop_vars): if require_one_iteration: loop_vars = loop_vars[1:] set_state(loop_vars) body() new_loop_vars = get_state() verify_tf_loop_vars( init_vars, loop_vars, new_loop_vars, symbol_names, opts) if require_one_iteration: new_loop_vars = (True,) + new_loop_vars return new_loop_vars if 'shape_invariants' in opts: opts['shape_invariants'] = _shape_invariants_mapping_to_positional_list( opts['shape_invariants'], init_vars) while_loop_opts = dict(opts) while_loop_opts.pop('iterate_names', None) # Non-v2 while_loop unpacks the results when there is only one return value. # This enforces consistency across versions. while_loop_opts['return_same_structure'] = True if require_one_iteration: aug_init_vars = (False,) + init_vars if 'shape_invariants' in while_loop_opts: while_loop_opts['shape_invariants'] = ( (None,) + while_loop_opts['shape_invariants']) else: aug_init_vars = init_vars final_loop_vars = while_loop.while_loop(aug_test, aug_body, aug_init_vars, **while_loop_opts) if require_one_iteration: with ops.control_dependencies([ control_flow_assert.Assert(final_loop_vars[0], [ _runtime_zero_iterations_errmsg(symbol_names, nulls, orig_init_vars) ]) ]): final_loop_vars = nest.map_structure( lambda v: (array_ops.identity(v) if tensor_util.is_tf_type(v) else v), final_loop_vars[1:], ) set_state(final_loop_vars) def if_stmt(cond, body, orelse, get_state, set_state, symbol_names, nouts): """Functional form of an if statement. The conditional operates on a state, which includes all symbols whose values are a function of the branch taken. For example, given the code below that calculates the abs function: ``` x = 1 if x > 0: x = -x ``` The state is represented by the variable `x`. The `body, `orelse` and `set_state` functions must bind to the original `x` symbol, using `nonlocal`. The inputs and outputs of the callables representing the loop blocks are not explicit - instead, these functions must use nonlocal/global for side effects. The inputs and outputs are instead controlled by the set_state/get_state functions. Args: cond: Boolean. body: Callable representing the main block of the conditional. orelse: Callable representing the else block of the conditional. get_state: Function that returns a tuple containing the values of all composite symbols modified within the conditional. This allows access to state that branches may mutate through side effects. This function is not needed and should not be called when dispatching to code matching Python's default semantics. This is useful for checkpointing to avoid unintended side-effects when staging requires evaluating all code-paths. set_state: Function to set the values of all composite symbols modified within the conditional. This is the complement to get_state, used to restore checkpointed values. The single argument a tuple containing values for each composite symbol that may be modified in a branch of the conditional. The is usually the result of a call to get_state. symbol_names: Tuple containing basic loop var names. nouts: Number of variables output by the statement. Vars which are not outputs will not be passed through staged control flow such as tf.cond. This includes variables that are defined before the conditional, but are not used after it. """ # Note: tf.cond doesn't support SparseTensor. if tensors.is_dense_tensor(cond): _tf_if_stmt(cond, body, orelse, get_state, set_state, symbol_names, nouts) else: _py_if_stmt(cond, body, orelse) def _tf_if_stmt( cond, body, orelse, get_state, set_state, symbol_names, nouts): """Overload of if_stmt that stages a TF cond.""" cond = _verify_tf_condition(cond, 'if statement') if not nouts: prev_get_state, prev_set_state = get_state, set_state # Control flow V1 wants at least one output. get_state = lambda: (0,) + prev_get_state() set_state = lambda v: prev_set_state(v[1:]) symbol_names += ('<unused dummy>',) nouts = 1 init_vars = get_state() # TODO(mdan): Use nonlocal once we no longer need to support py2. new_body_vars_ = [None] new_orelse_vars_ = [None] def aug_body(): set_state(init_vars) body() new_body_vars = get_state() new_body_vars = new_body_vars[:nouts] new_body_vars_[0] = new_body_vars _verify_tf_cond_branch_vars(new_body_vars, symbol_names, 'main') if new_orelse_vars_[0] is not None: _verify_tf_cond_vars(new_body_vars, new_orelse_vars_[0], symbol_names) return new_body_vars def aug_orelse(): set_state(init_vars) orelse() new_orelse_vars = get_state() new_orelse_vars = new_orelse_vars[:nouts] new_orelse_vars_[0] = new_orelse_vars _verify_tf_cond_branch_vars(new_orelse_vars, symbol_names, 'else') if new_body_vars_[0] is not None: _verify_tf_cond_vars(new_body_vars_[0], new_orelse_vars, symbol_names) return new_orelse_vars final_cond_vars = tf_cond.cond( cond, aug_body, aug_orelse, strict=True) final_cond_vars = final_cond_vars + init_vars[nouts:] set_state(final_cond_vars) def _py_if_stmt(cond, body, orelse): """Overload of if_stmt that executes a Python if statement.""" return body() if cond else orelse()
_PythonLoopChecker
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 294199, "end": 294847 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("EnterpriseOutsideCollaboratorEdge"), graphql_name="edges" ) nodes = sgqlc.types.Field(sgqlc.types.list_of("User"), graphql_name="nodes") page_info = sgqlc.types.Field( sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo" ) total_count = sgqlc.types.Field( sgqlc.types.non_null(Int), graphql_name="totalCount" )
EnterpriseOutsideCollaboratorConnection
python
walkccc__LeetCode
solutions/3556. Sum of Largest Prime Substrings/3556.py
{ "start": 0, "end": 441 }
class ____: def sumOfLargestPrimes(self, s: str) -> int: primes = set() n = len(s) for i in range(n): for j in range(i + 1, n + 1): num = int(s[i:j]) if num not in primes and self._isPrime(num): primes.add(num) top3 = sorted(primes, reverse=True)[:3] return sum(top3) def _isPrime(self, n: int) -> bool: return n > 1 and all(n % i != 0 for i in range(2, math.isqrt(n) + 1))
Solution
python
astral-sh__uv
scripts/benchmark/src/benchmark/__init__.py
{ "start": 286, "end": 1931 }
class ____(typing.NamedTuple): name: str """The benchmark to run.""" commands: list[Command] """The commands to benchmark.""" warmup: int | None """The number of warmup runs to perform.""" min_runs: int | None """The minimum number of runs to perform.""" runs: int | None """The number of runs to perform.""" verbose: bool """Whether to print verbose output.""" json: bool """Whether to export results to JSON.""" def run(self) -> None: """Run the benchmark using `hyperfine`.""" args = ["hyperfine"] # Export to JSON. if self.json: args.append("--export-json") args.append(f"{self.name}.json") # Preamble: benchmark-wide setup. if self.verbose: args.append("--show-output") if self.warmup is not None: args.append("--warmup") args.append(str(self.warmup)) if self.min_runs is not None: args.append("--min-runs") args.append(str(self.min_runs)) if self.runs is not None: args.append("--runs") args.append(str(self.runs)) # Add all command names, for command in self.commands: args.append("--command-name") args.append(command.name) # Add all prepare statements. for command in self.commands: args.append("--prepare") args.append(command.prepare or "") # Add all commands. for command in self.commands: args.append(shlex.join(command.command)) subprocess.check_call(args)
Hyperfine
python
getsentry__sentry
src/sentry/api/endpoints/chunk.py
{ "start": 1863, "end": 2068 }
class ____(BytesIO): def __init__(self, file): data = GzipFile(fileobj=file, mode="rb").read() self.size = len(data) self.name = file.name super().__init__(data)
GzipChunk
python
kamyu104__LeetCode-Solutions
Python/time-needed-to-inform-all-employees.py
{ "start": 76, "end": 895 }
class ____(object): def numOfMinutes(self, n, headID, manager, informTime): """ :type n: int :type headID: int :type manager: List[int] :type informTime: List[int] :rtype: int """ children = collections.defaultdict(list) for child, parent in enumerate(manager): if parent != -1: children[parent].append(child) result = 0 stk = [(headID, 0)] while stk: node, curr = stk.pop() curr += informTime[node] result = max(result, curr) if node not in children: continue for c in children[node]: stk.append((c, curr)) return result # Time: O(n) # Space: O(n) # dfs solution with recursion
Solution
python
PyCQA__pylint
tests/functional/i/invalid/invalid_unary_operand_type.py
{ "start": 215, "end": 1595 }
class ____: def __invert__(self): return 42 def __pos__(self): return 42 def __neg__(self): return 42 def these_are_good(): negative = -1 negative1 = -1.0 positive = +1 positive2 = +1.0 inverted = ~1 not_int = not 1 not_float = not 2.0 not_string = not "" not_list = not [] not_dict = not {} not_tuple = not (1, 2) inverted_instance = ~Implemented() positive_instance = +Implemented() negative_instance = -Implemented() not_instance = not Implemented() def these_are_bad(): invert_list = ~[] # [invalid-unary-operand-type] invert_tuple = ~() # [invalid-unary-operand-type] invert_dict = ~dict() # [invalid-unary-operand-type] invert_dict_1 = ~{} # [invalid-unary-operand-type] invert_set = ~set() # [invalid-unary-operand-type] neg_set = -set() # [invalid-unary-operand-type] neg_str = -"" # [invalid-unary-operand-type] invert_str = ~"" # [invalid-unary-operand-type] pos_str = +"" # [invalid-unary-operand-type] class A: pass invert_func = ~(lambda: None) # [invalid-unary-operand-type] invert_class = ~A # [invalid-unary-operand-type] invert_instance = ~A() # [invalid-unary-operand-type] invert_module = ~collections # [invalid-unary-operand-type] invert_float = ~2.0 # [invalid-unary-operand-type]
Implemented
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_index.py
{ "start": 1102, "end": 1209 }
class ____: def __index__(self): print("raise some error") raise NotImplementedError
Index6
python
ApeWorX__ape
tests/functional/test_exceptions.py
{ "start": 5694, "end": 7474 }
class ____: def test_close_match(self): net = "sepolai" error = NetworkNotFoundError(net, ecosystem="ethereum", options=("sepolia",)) actual = str(error) expected = f"No network in 'ethereum' named '{net}'. Did you mean 'sepolia'?" assert actual == expected def test_no_close_matches(self): net = "madeup" error = NetworkNotFoundError(net, ecosystem="ethereum", options=("sepolia",)) actual = str(error) expected = f"No network in 'ethereum' named '{net}'. Options:\nsepolia" assert actual == expected def test_ecosystem_no_network_options(self): net = "madeup" error = NetworkNotFoundError(net, ecosystem="ethereum", options=()) actual = str(error) expected = "'ethereum' has no networks." assert actual == expected def test_no_options(self): net = "madeup" error = NetworkNotFoundError(net, options=()) actual = str(error) expected = "No networks found." assert actual == expected def test_handle_ape_exception_hides_home_dir(mocker): base_paths = ["this/is/base/path"] mock_tb_get = mocker.patch("ape.exceptions._get_relevant_frames") tb_str = f""" File "{Path.home()}/this/is/base/path/myfile.vy", line 18, in setNumber2 setNumber(5) """.lstrip() mock_tb_get.return_value = [tb_str] print_watcher = mocker.patch("ape.exceptions.rich_print") ape_exception = ContractLogicError() assert handle_ape_exception(ape_exception, base_paths) is True actual = print_watcher.call_args[0][0] # We expect the same only the home dir has been hidden. expected = "\n" + tb_str.replace(str(Path.home()), "$HOME") assert actual == expected
TestNetworkNotFoundError
python
fluentpython__example-code
attic/descriptors/doc_descriptor.py
{ "start": 813, "end": 1378 }
class ____: """A documented descriptor""" def __init__(self, documentation): self.__doc__ = documentation cls_name = self.__class__.__name__ self.storage_name = '_{}_{:x}'.format(cls_name, id(self)) def __get__(self, instance, owner): """The __get__ method""" if instance is None: return doc_descriptor_wrapper_factory(self) else: return getattr(instance, self.storage_name) def __set__(self, instance, value): setattr(instance, self.storage_name, value)
DocDescriptor
python
great-expectations__great_expectations
tests/integration/metrics/column/test_distinct_values.py
{ "start": 683, "end": 2030 }
class ____: @parameterize_batch_for_data_sources( data_source_configs=get_pandas_data_sources(), data=DATA_FRAME, ) def test_distinct_values_pandas(self, batch_for_datasource: Batch) -> None: metric = ColumnDistinctValues(column=COLUMN_NAME) metric_result = batch_for_datasource.compute_metrics(metric) assert isinstance(metric_result, ColumnDistinctValuesResult) # For pandas, we expect the null values to be included assert len(metric_result.value) == 4 # a, b, c, and null assert "a" in metric_result.value assert "b" in metric_result.value assert "c" in metric_result.value # Check for either None or nan depending on source assert any(pd.isna(val) for val in metric_result.value) @parameterize_batch_for_data_sources( data_source_configs=get_non_pandas_data_sources(), data=DATA_FRAME, ) def test_distinct_values_non_pandas(self, batch_for_datasource: Batch) -> None: metric = ColumnDistinctValues(column=COLUMN_NAME) metric_result = batch_for_datasource.compute_metrics(metric) assert isinstance(metric_result, ColumnDistinctValuesResult) # For SQL and Spark, we expect only the non-null values assert metric_result.value == {"a", "b", "c"}
TestColumnDistinctValues
python
pytorch__pytorch
test/test_overrides.py
{ "start": 46009, "end": 46254 }
class ____(TestCase): """ Regression test for gh-47069 """ def test_newones(self): t = torch.tensor([1, 2]).as_subclass(SubTensor2) n = t.new_ones((1, 2)) self.assertEqual(type(n), SubTensor2)
TestGradNewOnesOverride
python
neetcode-gh__leetcode
python/0560-subarray-sum-equals-k.py
{ "start": 0, "end": 508 }
class ____: def subarraySum(self, nums: List[int], k: int) -> int: count = 0 sum = 0 dic = {} dic[0] = 1 for i in range(len(nums)): sum += nums[i] if sum-k in dic: count += dic[sum-k] dic[sum] = dic.get(sum, 0)+1 return count # Time Complexity : # O(N) -> Where N is the size of the array and we are iterating over the array once # Space Complexity: # O(N) -> Creating a hashmap/dictionary
Solution
python
getsentry__sentry
tests/sentry/rules/conditions/test_level_event.py
{ "start": 229, "end": 2871 }
class ____(RuleTestCase): rule_cls = LevelCondition def test_render_label(self) -> None: rule = self.get_rule(data={"match": MatchType.EQUAL, "level": "30"}) assert rule.render_label() == "The event's level is equal to warning" def test_equals(self) -> None: event = self.store_event(data={"level": "info"}, project_id=self.project.id) rule = self.get_rule(data={"match": MatchType.EQUAL, "level": "20"}) self.assertPasses(rule, event) rule = self.get_rule(data={"match": MatchType.EQUAL, "level": "30"}) self.assertDoesNotPass(rule, event) def test_greater_than(self) -> None: event = self.store_event(data={"level": "info"}, project_id=self.project.id) rule = self.get_rule(data={"match": MatchType.GREATER_OR_EQUAL, "level": "40"}) self.assertDoesNotPass(rule, event) rule = self.get_rule(data={"match": MatchType.GREATER_OR_EQUAL, "level": "20"}) self.assertPasses(rule, event) def test_less_than(self) -> None: event = self.store_event(data={"level": "info"}, project_id=self.project.id) rule = self.get_rule(data={"match": MatchType.LESS_OR_EQUAL, "level": "10"}) self.assertDoesNotPass(rule, event) rule = self.get_rule(data={"match": MatchType.LESS_OR_EQUAL, "level": "30"}) self.assertPasses(rule, event) def test_without_tag(self) -> None: event = self.store_event(data={}, project_id=self.project.id) rule = self.get_rule(data={"match": MatchType.EQUAL, "level": "30"}) self.assertDoesNotPass(rule, event) # This simulates the following case: # - Rule is setup to accept >= error # - error event finishes the save_event task, group has a level of error # - warning event finishes the save event, group now has a level of warning # - error event starts post_process_group should pass even though the group # has a warning level set # # Specifically here to make sure the check is properly checking the event's level def test_differing_levels(self) -> None: eevent = self.store_event(data={"level": "error"}, project_id=self.project.id) wevent = self.store_event(data={"level": "warning"}, project_id=self.project.id) assert wevent.event_id != eevent.event_id assert eevent.group is not None assert wevent.group is not None assert wevent.group.id == eevent.group.id rule = self.get_rule(data={"match": MatchType.GREATER_OR_EQUAL, "level": "40"}) self.assertDoesNotPass(rule, wevent) self.assertPasses(rule, eevent)
LevelConditionTest
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 244287, "end": 244597 }
class ____(_PrintableStructure): _fields_ = [ ('version', c_uint), ('numMetrics', c_uint), ('sample1', c_nvmlGpmSample_t), ('sample2', c_nvmlGpmSample_t), ('metrics', c_nvmlGpmMetric_t * NVML_GPM_METRIC_MAX) ] NVML_GPM_METRICS_GET_VERSION = 1
c_nvmlGpmMetricsGet_t
python
numba__numba
docs/source/conf.py
{ "start": 10763, "end": 11554 }
class ____(SphinxDirective): def run(self): # Generate a warning admonition to contain the deprecation notice warning = nodes.admonition(classes=["warning"]) warning += nodes.title(text="CUDA Built-in Target deprecation notice") # Parse CUDA deprecation text so that the link and reference get # resolved eventually dummy = nodes.Element() dummy.document = self.state.document lines = StringList(string2lines(cuda_deprecation_text)) self.state.nested_parse(lines, 0, dummy) # Add the text into the body of the warning warning += dummy.children return [warning] def setup(app): app.add_css_file('rtd-overrides.css') app.add_directive('cuda-deprecated', CudaDeprecated)
CudaDeprecated
python
Textualize__textual
docs/examples/styles/scrollbars2.py
{ "start": 385, "end": 569 }
class ____(App): CSS_PATH = "scrollbars2.tcss" def compose(self): yield Label(TEXT * 10) if __name__ == "__main__": app = Scrollbar2App() app.run()
Scrollbar2App
python
dagster-io__dagster
python_modules/libraries/dagster-aws/dagster_aws/pipes/clients/emr_containers.py
{ "start": 1318, "end": 11182 }
class ____(PipesClient, TreatAsResourceParam): """A pipes client for running workloads on AWS EMR Containers. Args: client (Optional[boto3.client]): The boto3 AWS EMR containers client used to interact with AWS EMR Containers. context_injector (Optional[PipesContextInjector]): A context injector to use to inject context into AWS EMR Containers workload. Defaults to :py:class:`PipesEnvContextInjector`. message_reader (Optional[PipesMessageReader]): A message reader to use to read messages from the AWS EMR Containers workload. It's recommended to use :py:class:`PipesS3MessageReader`. forward_termination (bool): Whether to cancel the AWS EMR Containers workload if the Dagster process receives a termination signal. pipes_params_bootstrap_method (Literal["args", "env"]): The method to use to inject parameters into the AWS EMR Containers workload. Defaults to "args". waiter_config (Optional[WaiterConfig]): Optional waiter configuration to use. Defaults to 70 days (Delay: 6, MaxAttempts: 1000000). """ AWS_SERVICE_NAME = AWS_SERVICE_NAME def __init__( self, client: Optional["EMRContainersClient"] = None, context_injector: Optional[PipesContextInjector] = None, message_reader: Optional[PipesMessageReader] = None, forward_termination: bool = True, pipes_params_bootstrap_method: Literal["args", "env"] = "env", waiter_config: Optional[WaiterConfig] = None, ): self._client = client or boto3.client("emr-containers") self._context_injector = context_injector or PipesEnvContextInjector() self._message_reader = message_reader or PipesCloudWatchMessageReader() self.forward_termination = check.bool_param(forward_termination, "forward_termination") self.pipes_params_bootstrap_method = pipes_params_bootstrap_method self.waiter_config = waiter_config or WaiterConfig(Delay=6, MaxAttempts=1000000) @property def client(self) -> "EMRContainersClient": return self._client @property def context_injector(self) -> PipesContextInjector: return self._context_injector @property def message_reader(self) -> PipesMessageReader: return self._message_reader @classmethod def _is_dagster_maintained(cls) -> bool: return True @public def run( # pyright: ignore[reportIncompatibleMethodOverride] self, *, context: Union[OpExecutionContext, AssetExecutionContext], start_job_run_params: "StartJobRunRequestTypeDef", extras: Optional[dict[str, Any]] = None, ) -> PipesClientCompletedInvocation: """Run a workload on AWS EMR Containers, enriched with the pipes protocol. Args: context (Union[OpExecutionContext, AssetExecutionContext]): The context of the currently executing Dagster op or asset. params (dict): Parameters for the ``start_job_run`` boto3 AWS EMR Containers client call. See `Boto3 EMR Containers API Documentation <https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/emr-containers/client/start_job_run.html>`_ extras (Optional[Dict[str, Any]]): Additional information to pass to the Pipes session in the external process. Returns: PipesClientCompletedInvocation: Wrapper containing results reported by the external process. """ with open_pipes_session( context=context, message_reader=self.message_reader, context_injector=self.context_injector, extras=extras, ) as session: start_job_run_params = self._enrich_start_params(context, session, start_job_run_params) start_response = self._start(context, start_job_run_params) try: completion_response = self._wait_for_completion(context, start_response) context.log.info(f"[pipes] {self.AWS_SERVICE_NAME} workload is complete!") return PipesClientCompletedInvocation( session, metadata=self._extract_dagster_metadata(completion_response) ) except DagsterExecutionInterruptedError: if self.forward_termination: context.log.warning( f"[pipes] Dagster process interrupted! Will terminate external {self.AWS_SERVICE_NAME} workload." ) self._terminate(context, start_response) raise def _enrich_start_params( self, context: Union[OpExecutionContext, AssetExecutionContext], session: PipesSession, params: "StartJobRunRequestTypeDef", ) -> "StartJobRunRequestTypeDef": # inject Dagster tags tags = params.get("tags", {}) params["tags"] = {**tags, **session.default_remote_invocation_info} params["jobDriver"] = params.get("jobDriver", {}) if self.pipes_params_bootstrap_method == "env": params["configurationOverrides"] = params.get("configurationOverrides", {}) params["configurationOverrides"]["applicationConfiguration"] = params[ # type: ignore "configurationOverrides" ].get("applicationConfiguration", []) # we can reuse the same method as in standard EMR # since configurations format is the same params["configurationOverrides"]["applicationConfiguration"] = ( # type: ignore emr_inject_pipes_env_vars( session, params["configurationOverrides"]["applicationConfiguration"], # type: ignore emr_flavor="containers", ) ) # the other option is sparkSqlJobDriver - in this case there won't be a remote Pipes session # and no Pipes messages will arrive from the job # but we can still run it and get the logs if spark_submit_job_driver := params["jobDriver"].get("sparkSubmitJobDriver"): if self.pipes_params_bootstrap_method == "args": spark_submit_job_driver["sparkSubmitParameters"] = spark_submit_job_driver.get( "sparkSubmitParameters", "" ) for key, value in session.get_bootstrap_cli_arguments().items(): spark_submit_job_driver["sparkSubmitParameters"] += f" {key} {value}" params["jobDriver"]["sparkSubmitJobDriver"] = spark_submit_job_driver # type: ignore return cast("StartJobRunRequestTypeDef", params) def _start( self, context: Union[OpExecutionContext, AssetExecutionContext], params: "StartJobRunRequestTypeDef", ) -> "StartJobRunResponseTypeDef": response = self.client.start_job_run(**params) virtual_cluster_id = response["virtualClusterId"] job_run_id = response["id"] context.log.info( f"[pipes] {self.AWS_SERVICE_NAME} job started with job_run_id {job_run_id} on virtual cluster {virtual_cluster_id}." ) return response def _wait_for_completion( self, context: Union[OpExecutionContext, AssetExecutionContext], start_response: "StartJobRunResponseTypeDef", ) -> "DescribeJobRunResponseTypeDef": job_run_id = start_response["id"] virtual_cluster_id = start_response["virtualClusterId"] # TODO: use a native boto3 waiter instead of a while loop # once it's available (it does not exist at the time of writing) attempts = 0 while attempts < self.waiter_config.get("MaxAttempts", 1000000): response = self.client.describe_job_run( id=job_run_id, virtualClusterId=virtual_cluster_id ) state = response["jobRun"].get("state") if state in ["COMPLETED", "FAILED", "CANCELLED"]: break time.sleep(self.waiter_config.get("Delay", 6)) if state in ["FAILED", "CANCELLED"]: # pyright: ignore[reportPossiblyUnboundVariable] raise RuntimeError( f"EMR Containers job run {job_run_id} failed with state {state}. Reason: {response['jobRun'].get('failureReason')}, details: {response['jobRun'].get('stateDetails')}" # pyright: ignore[reportPossiblyUnboundVariable] ) return self.client.describe_job_run(virtualClusterId=virtual_cluster_id, id=job_run_id) def _extract_dagster_metadata( self, response: "DescribeJobRunResponseTypeDef" ) -> RawMetadataMapping: metadata: RawMetadataMapping = {} metadata["AWS EMR Containers Virtual Cluster ID"] = response["jobRun"].get( "virtualClusterId" ) metadata["AWS EMR Containers Job Run ID"] = response["jobRun"].get("id") # TODO: it would be great to add a url to EMR Studio page for this run # such urls look like: https://es-638xhdetxum2td9nc3a45evmn.emrstudio-prod.eu-north-1.amazonaws.com/#/containers-applications/00fm4oe0607u5a1d # but we need to get the Studio ID from the application_id # which is not possible with the current AWS API return metadata def _terminate( self, context: Union[OpExecutionContext, AssetExecutionContext], start_response: "StartJobRunResponseTypeDef", ): virtual_cluster_id = start_response["virtualClusterId"] job_run_id = start_response["id"] context.log.info(f"[pipes] Terminating {self.AWS_SERVICE_NAME} job run {job_run_id}") self.client.cancel_job_run(virtualClusterId=virtual_cluster_id, id=job_run_id) context.log.info(f"[pipes] {self.AWS_SERVICE_NAME} job run {job_run_id} terminated.")
PipesEMRContainersClient
python
pennersr__django-allauth
allauth/headless/mfa/response.py
{ "start": 2088, "end": 2315 }
class ____(APIResponse): def __init__(self, request, authenticators): data = [_authenticator_data(authenticator) for authenticator in authenticators] super().__init__(request, data=data)
AuthenticatorsResponse
python
scipy__scipy
scipy/io/matlab/_mio5.py
{ "start": 5201, "end": 15942 }
class ____(MatFileReader): ''' Reader for Mat 5 mat files Adds the following attribute to base class uint16_codec - char codec to use for uint16 char arrays (defaults to system default codec) Uses variable reader that has the following standard interface (see abstract class in ``miobase``:: __init__(self, file_reader) read_header(self) array_from_header(self) and added interface:: set_stream(self, stream) read_full_tag(self) ''' @docfiller def __init__(self, mat_stream, byte_order=None, mat_dtype=False, squeeze_me=False, chars_as_strings=True, matlab_compatible=False, struct_as_record=True, verify_compressed_data_integrity=True, uint16_codec=None, simplify_cells=False): '''Initializer for matlab 5 file format reader %(matstream_arg)s %(load_args)s %(struct_arg)s uint16_codec : {None, string} Set codec to use for uint16 char arrays (e.g., 'utf-8'). Use system default codec if None ''' super().__init__( mat_stream, byte_order, mat_dtype, squeeze_me, chars_as_strings, matlab_compatible, struct_as_record, verify_compressed_data_integrity, simplify_cells) # Set uint16 codec if not uint16_codec: uint16_codec = sys.getdefaultencoding() self.uint16_codec = uint16_codec # placeholders for readers - see initialize_read method self._file_reader = None self._matrix_reader = None def guess_byte_order(self): ''' Guess byte order. Sets stream pointer to 0''' self.mat_stream.seek(126) mi = self.mat_stream.read(2) self.mat_stream.seek(0) return mi == b'IM' and '<' or '>' def read_file_header(self): ''' Read in mat 5 file header ''' hdict = {} hdr_dtype = MDTYPES[self.byte_order]['dtypes']['file_header'] hdr = read_dtype(self.mat_stream, hdr_dtype) hdict['__header__'] = hdr['description'].item().strip(b' \t\n\000') v_major = hdr['version'] >> 8 v_minor = hdr['version'] & 0xFF hdict['__version__'] = f'{v_major}.{v_minor}' return hdict def initialize_read(self): ''' Run when beginning read of variables Sets up readers from parameters in `self` ''' # reader for top level stream. We need this extra top-level # reader because we use the matrix_reader object to contain # compressed matrices (so they have their own stream) self._file_reader = VarReader5(self) # reader for matrix streams self._matrix_reader = VarReader5(self) def read_var_header(self): ''' Read header, return header, next position Header has to define at least .name and .is_global Parameters ---------- None Returns ------- header : object object that can be passed to self.read_var_array, and that has attributes .name and .is_global next_position : int position in stream of next variable ''' mdtype, byte_count = self._file_reader.read_full_tag() if not byte_count > 0: raise ValueError("Did not read any bytes") next_pos = self.mat_stream.tell() + byte_count if mdtype == miCOMPRESSED: # Make new stream from compressed data stream = ZlibInputStream(self.mat_stream, byte_count) self._matrix_reader.set_stream(stream) check_stream_limit = self.verify_compressed_data_integrity mdtype, byte_count = self._matrix_reader.read_full_tag() else: check_stream_limit = False self._matrix_reader.set_stream(self.mat_stream) if not mdtype == miMATRIX: raise TypeError(f'Expecting miMATRIX type here, got {mdtype}') header = self._matrix_reader.read_header(check_stream_limit) return header, next_pos def read_var_array(self, header, process=True): ''' Read array, given `header` Parameters ---------- header : header object object with fields defining variable header process : {True, False} bool, optional If True, apply recursive post-processing during loading of array. Returns ------- arr : array array with post-processing applied or not according to `process`. ''' return self._matrix_reader.array_from_header(header, process) def get_variables(self, variable_names=None): ''' get variables from stream as dictionary variable_names - optional list of variable names to get If variable_names is None, then get all variables in file ''' if isinstance(variable_names, str): variable_names = [variable_names] elif variable_names is not None: variable_names = list(variable_names) self.mat_stream.seek(0) # Here we pass all the parameters in self to the reading objects self.initialize_read() mdict = self.read_file_header() mdict['__globals__'] = [] while not self.end_of_stream(): hdr, next_position = self.read_var_header() name = 'None' if hdr.name is None else hdr.name.decode('latin1') if name in mdict: msg = ( f'Duplicate variable name "{name}" in stream' " - replacing previous with new\nConsider" "scipy.io.matlab.varmats_from_mat to split " "file into single variable files" ) warnings.warn(msg, MatReadWarning, stacklevel=2) if name == '': # can only be a matlab 7 function workspace name = '__function_workspace__' # We want to keep this raw because mat_dtype processing # will break the format (uint8 as mxDOUBLE_CLASS) process = False else: process = True if variable_names is not None and name not in variable_names: self.mat_stream.seek(next_position) continue try: res = self.read_var_array(hdr, process) except MatReadError as err: warnings.warn( f'Unreadable variable "{name}", because "{err}"', Warning, stacklevel=2) res = f"Read error: {err}" self.mat_stream.seek(next_position) mdict[name] = res if hdr.is_global: mdict['__globals__'].append(name) if variable_names is not None: variable_names.remove(name) if len(variable_names) == 0: break if self.simplify_cells: return _simplify_cells(mdict) else: return mdict def list_variables(self): ''' list variables from stream ''' self.mat_stream.seek(0) # Here we pass all the parameters in self to the reading objects self.initialize_read() self.read_file_header() vars = [] while not self.end_of_stream(): hdr, next_position = self.read_var_header() name = 'None' if hdr.name is None else hdr.name.decode('latin1') if name == '': # can only be a matlab 7 function workspace name = '__function_workspace__' shape = self._matrix_reader.shape_from_header(hdr) if hdr.is_logical: info = 'logical' else: info = mclass_info.get(hdr.mclass, 'unknown') vars.append((name, shape, info)) self.mat_stream.seek(next_position) return vars def varmats_from_mat(file_obj): """ Pull variables out of mat 5 file as a sequence of mat file objects This can be useful with a difficult mat file, containing unreadable variables. This routine pulls the variables out in raw form and puts them, unread, back into a file stream for saving or reading. Another use is the pathological case where there is more than one variable of the same name in the file; this routine returns the duplicates, whereas the standard reader will overwrite duplicates in the returned dictionary. The file pointer in `file_obj` will be undefined. File pointers for the returned file-like objects are set at 0. Parameters ---------- file_obj : file-like file object containing mat file Returns ------- named_mats : list list contains tuples of (name, BytesIO) where BytesIO is a file-like object containing mat file contents as for a single variable. The BytesIO contains a string with the original header and a single var. If ``var_file_obj`` is an individual BytesIO instance, then save as a mat file with something like ``open('test.mat', 'wb').write(var_file_obj.read())`` Examples -------- >>> import scipy.io >>> import numpy as np >>> from io import BytesIO >>> from scipy.io.matlab._mio5 import varmats_from_mat >>> mat_fileobj = BytesIO() >>> scipy.io.savemat(mat_fileobj, {'b': np.arange(10), 'a': 'a string'}) >>> varmats = varmats_from_mat(mat_fileobj) >>> sorted([name for name, str_obj in varmats]) ['a', 'b'] """ rdr = MatFile5Reader(file_obj) file_obj.seek(0) # Raw read of top-level file header hdr_len = MDTYPES[native_code]['dtypes']['file_header'].itemsize raw_hdr = file_obj.read(hdr_len) # Initialize variable reading file_obj.seek(0) rdr.initialize_read() rdr.read_file_header() next_position = file_obj.tell() named_mats = [] while not rdr.end_of_stream(): start_position = next_position hdr, next_position = rdr.read_var_header() name = 'None' if hdr.name is None else hdr.name.decode('latin1') # Read raw variable string file_obj.seek(start_position) byte_count = next_position - start_position var_str = file_obj.read(byte_count) # write to stringio object out_obj = BytesIO() out_obj.write(raw_hdr) out_obj.write(var_str) out_obj.seek(0) named_mats.append((name, out_obj)) return named_mats
MatFile5Reader
python
wandb__wandb
wandb/vendor/watchdog_0_9_0/wandb_watchdog/observers/read_directory_changes.py
{ "start": 4931, "end": 5262 }
class ____(BaseObserver): """ Observer thread that schedules watching directories and dispatches calls to event handlers. """ def __init__(self, timeout=DEFAULT_OBSERVER_TIMEOUT): BaseObserver.__init__(self, emitter_class=WindowsApiEmitter, timeout=timeout)
WindowsApiObserver