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
getsentry__sentry
tests/flagpole/test_evaluation_context.py
{ "start": 172, "end": 2509 }
class ____: # Identity fields tests are mainly upholding that our hashing strategy does # not change in the future, and that we calculate the id using the correct # context values and keys in order. def test_adds_identity_fields(self) -> None: eval_context = EvaluationContext({}, set()) assert eval_context.id == 1245845410931227995499360226027473197403882391305 eval_context = EvaluationContext({"foo": "bar", "baz": "barfoo"}, {"foo"}) expected_id = 484477975355580460928302712356218993825269143262 assert eval_context.id == expected_id # Assert that we skip the missing field but still generate the same # context ID. eval_context = EvaluationContext({"foo": "bar", "baz": "barfoo"}, {"foo", "whoops"}) assert eval_context.id == expected_id eval_context = EvaluationContext({"foo": "bar", "baz": "barfoo"}, {"foo", "baz"}) expected_id = 1249805218608667754842212156585681631068251083301 assert eval_context.id == expected_id # Assert that we use all properties to generate the context when all # identity fields are missing. eval_context = EvaluationContext({"foo": "bar", "baz": "barfoo"}, {"whoops", "test"}) assert eval_context.id == expected_id def test_no_identity_fields_included(self) -> None: eval_context = EvaluationContext({}) assert eval_context.id == 1245845410931227995499360226027473197403882391305 eval_context = EvaluationContext({"foo": "bar", "baz": "barfoo"}) expected_id = 1249805218608667754842212156585681631068251083301 assert eval_context.id == expected_id eval_context = EvaluationContext({"foo": "bar", "baz": "barfoo", "test": "property"}) expected_id = 1395427532315258482176540981434194664973697472186 assert eval_context.id == expected_id def test_get_has_data(self) -> None: eval_context = EvaluationContext({"foo": "bar", "baz": "barfoo"}, {"foo"}) assert eval_context.has("foo") is True assert eval_context.get("foo") == "bar" assert eval_context.has("baz") is True assert eval_context.get("baz") == "barfoo" assert eval_context.has("bar") is False assert eval_context.get("bar") is None @dataclass
TestEvaluationContext
python
FactoryBoy__factory_boy
tests/cyclic/foo.py
{ "start": 223, "end": 355 }
class ____(factory.Factory): class Meta: model = Foo x = 42 bar = factory.SubFactory(bar_mod.BarFactory)
FooFactory
python
getsentry__sentry
tests/sentry/users/api/endpoints/test_user_role_details.py
{ "start": 1675, "end": 2672 }
class ____(UserUserRolesTest): method = "POST" def test_adds_role(self) -> None: UserRole.objects.create(name="support", permissions=["broadcasts.admin"]) UserRole.objects.create(name="admin", permissions=["users.admin"]) resp = self.get_response("me", "support") assert resp.status_code == 201 assert UserRole.objects.filter(users=self.user, name="support").exists() assert not UserRole.objects.filter(users=self.user, name="admin").exists() def test_invalid_role(self) -> None: UserRole.objects.create(name="other", permissions=["users.edit"]) resp = self.get_response("me", "blah") assert resp.status_code == 404 def test_existing_role(self) -> None: role = UserRole.objects.create(name="support", permissions=["broadcasts.admin"]) role.users.add(self.user) resp = self.get_response("me", "support") assert resp.status_code == 410 @control_silo_test
UserUserRolesCreateTest
python
dagster-io__dagster
python_modules/libraries/dagster-databricks/dagster_databricks/components/databricks_asset_bundle/configs.py
{ "start": 21028, "end": 21166 }
class ____(Resolvable, Model): spark_version: str node_type_id: str num_workers: int @preview
ResolvedDatabricksNewClusterConfig
python
pennersr__django-allauth
allauth/socialaccount/providers/yandex/provider.py
{ "start": 512, "end": 1647 }
class ____(OAuth2Provider): id = "yandex" name = "Yandex" account_class = YandexAccount oauth2_adapter_class = YandexOAuth2Adapter def get_default_scope(self): scope = ["login:info"] if app_settings.QUERY_EMAIL: scope.append("login:email") return scope def extract_uid(self, data): return str(data["id"]) def get_user_email(self, data): email = data.get("default_email") if not email: emails = data.get("emails") email = emails[0] if emails else "" return email def extract_common_fields(self, data): email = self.get_user_email(data) return dict( email=email, last_name=data.get("last_name"), username=data.get("display_name"), first_name=data.get("first_name"), ) def extract_email_addresses(self, data): ret = [] email = self.get_user_email(data) if email: ret.append(EmailAddress(email=email, verified=True, primary=True)) return ret provider_classes = [YandexProvider]
YandexProvider
python
pennersr__django-allauth
allauth/socialaccount/providers/figma/provider.py
{ "start": 309, "end": 436 }
class ____(ProviderAccount): def get_avatar_url(self): return self.account.extra_data.get("img_url", "")
FigmaAccount
python
pandas-dev__pandas
pandas/tests/indexes/interval/test_constructors.py
{ "start": 7757, "end": 10629 }
class ____(ConstructorTests): """Tests specific to IntervalIndex.from_arrays""" @pytest.fixture def constructor(self): """Fixture for IntervalIndex.from_arrays constructor""" return IntervalIndex.from_arrays def get_kwargs_from_breaks(self, breaks, closed="right"): """ converts intervals in breaks format to a dictionary of kwargs to specific to the format expected by IntervalIndex.from_arrays """ return {"left": breaks[:-1], "right": breaks[1:]} def test_constructor_errors(self): # GH 19016: categorical data data = Categorical(list("01234abcde"), ordered=True) msg = ( "category, object, and string subtypes are not supported for IntervalIndex" ) with pytest.raises(TypeError, match=msg): IntervalIndex.from_arrays(data[:-1], data[1:]) # unequal length left = [0, 1, 2] right = [2, 3] msg = "left and right must have the same length" with pytest.raises(ValueError, match=msg): IntervalIndex.from_arrays(left, right) @pytest.mark.parametrize( "left_subtype, right_subtype", [(np.int64, np.float64), (np.float64, np.int64)] ) def test_mixed_float_int(self, left_subtype, right_subtype): """mixed int/float left/right results in float for both sides""" left = np.arange(9, dtype=left_subtype) right = np.arange(1, 10, dtype=right_subtype) result = IntervalIndex.from_arrays(left, right) expected_left = Index(left, dtype=np.float64) expected_right = Index(right, dtype=np.float64) expected_subtype = np.float64 tm.assert_index_equal(result.left, expected_left) tm.assert_index_equal(result.right, expected_right) assert result.dtype.subtype == expected_subtype @pytest.mark.parametrize("interval_cls", [IntervalArray, IntervalIndex]) def test_from_arrays_mismatched_datetimelike_resos(self, interval_cls): # GH#55714 left = date_range("2016-01-01", periods=3, unit="s") right = date_range("2017-01-01", periods=3, unit="ms") result = interval_cls.from_arrays(left, right) expected = interval_cls.from_arrays(left.as_unit("ms"), right) tm.assert_equal(result, expected) # td64 left2 = left - left[0] right2 = right - left[0] result2 = interval_cls.from_arrays(left2, right2) expected2 = interval_cls.from_arrays(left2.as_unit("ms"), right2) tm.assert_equal(result2, expected2) # dt64tz left3 = left.tz_localize("UTC") right3 = right.tz_localize("UTC") result3 = interval_cls.from_arrays(left3, right3) expected3 = interval_cls.from_arrays(left3.as_unit("ms"), right3) tm.assert_equal(result3, expected3)
TestFromArrays
python
PrefectHQ__prefect
src/integrations/prefect-aws/tests/observers/test_ecs_observer.py
{ "start": 25792, "end": 29544 }
class ____: def test_empty_tags(self): result = _related_resources_from_tags({}) assert result == [] def test_flow_run_tags(self): tags = { "prefect.io/flow-run-id": "flow-run-123", "prefect.io/flow-run-name": "my-flow-run", } result = _related_resources_from_tags(tags) assert len(result) == 1 assert ( result[0].model_dump()["prefect.resource.id"] == "prefect.flow-run.flow-run-123" ) assert result[0].model_dump()["prefect.resource.role"] == "flow-run" assert result[0].model_dump()["prefect.resource.name"] == "my-flow-run" def test_deployment_tags(self): tags = { "prefect.io/deployment-id": "deployment-456", "prefect.io/deployment-name": "my-deployment", } result = _related_resources_from_tags(tags) assert len(result) == 1 assert ( result[0].model_dump()["prefect.resource.id"] == "prefect.deployment.deployment-456" ) assert result[0].model_dump()["prefect.resource.role"] == "deployment" assert result[0].model_dump()["prefect.resource.name"] == "my-deployment" def test_flow_tags(self): tags = { "prefect.io/flow-id": "flow-789", "prefect.io/flow-name": "my-flow", } result = _related_resources_from_tags(tags) assert len(result) == 1 assert result[0].model_dump()["prefect.resource.id"] == "prefect.flow.flow-789" assert result[0].model_dump()["prefect.resource.role"] == "flow" assert result[0].model_dump()["prefect.resource.name"] == "my-flow" def test_work_pool_tags(self): tags = { "prefect.io/work-pool-id": "pool-abc", "prefect.io/work-pool-name": "my-pool", } result = _related_resources_from_tags(tags) assert len(result) == 1 assert ( result[0].model_dump()["prefect.resource.id"] == "prefect.work-pool.pool-abc" ) assert result[0].model_dump()["prefect.resource.role"] == "work-pool" assert result[0].model_dump()["prefect.resource.name"] == "my-pool" def test_worker_tags(self): tags = { "prefect.io/worker-name": "My Worker", } result = _related_resources_from_tags(tags) assert len(result) == 1 assert ( result[0].model_dump()["prefect.resource.id"] == "prefect.worker.ecs.my-worker" ) assert result[0].model_dump()["prefect.resource.role"] == "worker" assert result[0].model_dump()["prefect.resource.name"] == "My Worker" def test_all_tags_combined(self): tags = { "prefect.io/flow-run-id": "flow-run-123", "prefect.io/flow-run-name": "my-flow-run", "prefect.io/deployment-id": "deployment-456", "prefect.io/deployment-name": "my-deployment", "prefect.io/flow-id": "flow-789", "prefect.io/flow-name": "my-flow", "prefect.io/work-pool-id": "pool-abc", "prefect.io/work-pool-name": "my-pool", "prefect.io/worker-name": "my-worker", } result = _related_resources_from_tags(tags) assert len(result) == 5 resource_ids = [r.model_dump()["prefect.resource.id"] for r in result] assert "prefect.flow-run.flow-run-123" in resource_ids assert "prefect.deployment.deployment-456" in resource_ids assert "prefect.flow.flow-789" in resource_ids assert "prefect.work-pool.pool-abc" in resource_ids assert "prefect.worker.ecs.my-worker" in resource_ids
TestRelatedResourcesFromTags
python
numpy__numpy
benchmarks/benchmarks/bench_ufunc_strides.py
{ "start": 4162, "end": 4337 }
class ____(_AbstractBinary): params = [ [np.add, np.subtract, np.multiply, np.divide], [1, 2, 4], [1, 2, 4], [1, 2, 4], ['F', 'D'] ]
BinaryComplex
python
numba__numba
numba/core/typing/builtins.py
{ "start": 13826, "end": 13895 }
class ____(ConstOpEq): pass @infer_global(operator.eq)
ConstOpNotEq
python
celery__celery
t/unit/utils/test_time.py
{ "start": 636, "end": 1469 }
class ____: def test_daylight(self, patching): time = patching('celery.utils.time._time') time.timezone = 3600 time.daylight = False x = LocalTimezone() assert x.STDOFFSET == timedelta(seconds=-3600) assert x.DSTOFFSET == x.STDOFFSET time.daylight = True time.altzone = 3600 y = LocalTimezone() assert y.STDOFFSET == timedelta(seconds=-3600) assert y.DSTOFFSET == timedelta(seconds=-3600) assert repr(y) y._isdst = Mock() y._isdst.return_value = True assert y.utcoffset(datetime.now()) assert not y.dst(datetime.now()) y._isdst.return_value = False assert y.utcoffset(datetime.now()) assert not y.dst(datetime.now()) assert y.tzname(datetime.now())
test_LocalTimezone
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 343559, "end": 343923 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("client_mutation_id", "organization") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") organization = sgqlc.types.Field("Organization", graphql_name="organization")
FollowOrganizationPayload
python
conda__conda
conda/models/channel.py
{ "start": 1145, "end": 1984 }
class ____(type): """ This metaclass does basic caching and enables static constructor method usage with a single arg. """ def __call__(cls, *args, **kwargs): if len(args) == 1 and not kwargs: value = args[0] if isinstance(value, Channel): return value elif value in Channel._cache_: return Channel._cache_[value] else: c = Channel._cache_[value] = Channel.from_value(value) return c elif "channels" in kwargs: # presence of 'channels' kwarg indicates MultiChannel channels = tuple(cls(**_kwargs) for _kwargs in kwargs["channels"]) return MultiChannel(kwargs["name"], channels) else: return super().__call__(*args, **kwargs)
ChannelType
python
neetcode-gh__leetcode
python/1464-maximum-product-of-two-elements-in-an-array.py
{ "start": 0, "end": 314 }
class ____: def maxProduct(self, nums: List[int]) -> int: high = secondHigh = 0 for n in nums: if n > high: secondHigh = high high = n else: secondHigh = max(n, secondHigh) return (high - 1) * (secondHigh - 1)
Solution
python
getsentry__sentry
src/sentry/auth/providers/google/provider.py
{ "start": 1430, "end": 4549 }
class ____(OAuth2Provider): name = "Google" key = "google" def __init__( self, domain: str | None = None, domains: list[str] | None = None, version: str | None = None, **config: Any, ) -> None: if domain: if domains: domains.append(domain) else: domains = [domain] self.domains = domains # if a domain is not configured this is part of the setup pipeline # this is a bit complex in Sentry's SSO implementation as we don't # provide a great way to get initial state for new setup pipelines # vs missing state in case of migrations. if domains is None: version = DATA_VERSION else: version = None self.version = version super().__init__(**config) def get_client_id(self) -> str: return options.get("auth-google.client-id") def get_client_secret(self) -> str: return options.get("auth-google.client-secret") def get_configure_view( self, ) -> Callable[[HttpRequest, RpcOrganization, RpcAuthProvider], DeferredResponse]: return google_configure_view def get_auth_pipeline(self) -> list[AuthView]: return [ GoogleOAuth2Login(domains=self.domains, client_id=self.get_client_id()), OAuth2Callback( access_token_url=ACCESS_TOKEN_URL, client_id=self.get_client_id(), client_secret=self.get_client_secret(), ), FetchUser(domains=self.domains, version=self.version), ] def get_refresh_token_url(self) -> str: return ACCESS_TOKEN_URL def build_config(self, state: Mapping[str, Any]) -> dict[str, Any]: return {"domains": [state["domain"]], "version": DATA_VERSION} def build_identity(self, state: Mapping[str, Any]) -> Mapping[str, Any]: # https://developers.google.com/identity/protocols/OpenIDConnect#server-flow # data.user => { # "iss":"accounts.google.com", # "at_hash":"HK6E_P6Dh8Y93mRNtsDB1Q", # "email_verified":"true", # "sub":"10769150350006150715113082367", # "azp":"1234987819200.apps.googleusercontent.com", # "email":"jsmith@example.com", # "aud":"1234987819200.apps.googleusercontent.com", # "iat":1353601026, # "exp":1353604926, # "hd":"example.com" # } data = state["data"] user_data = state["user"] # XXX(epurkhiser): We initially were using the email as the id key. # This caused account dupes on domain changes. Migrate to the # account-unique sub key. user_id = MigratingIdentityId(id=user_data["sub"], legacy_id=user_data["email"]) return { "id": user_id, "email": user_data["email"], "name": user_data["email"], "data": self.get_oauth_data(data), "email_verified": user_data["email_verified"], }
GoogleOAuth2Provider
python
bokeh__bokeh
src/bokeh/events.py
{ "start": 15826, "end": 16211 }
class ____(PointEvent): ''' Announce a pressup event on a Bokeh plot. Attributes: sx (float) : x-coordinate of the event in *screen* space sy (float) : y-coordinate of the event in *screen* space x (float) : x-coordinate of the event in *data* space y (float) : y-coordinate of the event in *data* space ''' event_name = 'pressup'
PressUp
python
wandb__wandb
wandb/sdk/data_types/_dtypes.py
{ "start": 13200, "end": 13341 }
class ____(Type): name = "boolean" types: t.ClassVar[t.List[type]] = [bool] if np: BooleanType.types.append(np.bool_)
BooleanType
python
apache__airflow
providers/standard/src/airflow/providers/standard/decorators/sensor.py
{ "start": 1158, "end": 3028 }
class ____(PythonSensor): """ Wraps a Python callable and captures args/kwargs when called for execution. :param python_callable: A reference to an object that is callable :param task_id: task Id :param op_args: a list of positional arguments that will get unpacked when calling your callable (templated) :param op_kwargs: a dictionary of keyword arguments that will get unpacked in your function (templated) :param kwargs_to_upstream: For certain operators, we might need to upstream certain arguments that would otherwise be absorbed by the DecoratedOperator (for example python_callable for the PythonOperator). This gives a user the option to upstream kwargs as needed. """ template_fields: Sequence[str] = ("op_args", "op_kwargs") template_fields_renderers: ClassVar[dict[str, str]] = {"op_args": "py", "op_kwargs": "py"} custom_operator_name = "@task.sensor" # since we won't mutate the arguments, we should just do the shallow copy # there are some cases we can't deepcopy the objects (e.g protobuf). shallow_copy_attrs: Sequence[str] = ("python_callable",) def __init__( self, *, task_id: str, **kwargs, ) -> None: kwargs["task_id"] = get_unique_task_id(task_id, kwargs.get("dag"), kwargs.get("task_group")) super().__init__(**kwargs) def sensor_task(python_callable: Callable | None = None, **kwargs) -> TaskDecorator: """ Wrap a function into an Airflow operator. Accepts kwargs for operator kwarg. Can be reused in a single DAG. :param python_callable: Function to decorate """ return task_decorator_factory( python_callable=python_callable, multiple_outputs=False, decorated_operator_class=DecoratedSensorOperator, **kwargs, )
DecoratedSensorOperator
python
sqlalchemy__sqlalchemy
test/orm/test_collection.py
{ "start": 83204, "end": 87385 }
class ____(fixtures.TestBase): def _fixture(self, decl_base, collection_fn, ignore_unpopulated): class B(decl_base): __tablename__ = "b" id = Column(Integer, primary_key=True) data = Column(String(30)) a_id = Column(ForeignKey("a.id")) if collection_fn is collections.attribute_keyed_dict: cc = collection_fn( "data", ignore_unpopulated_attribute=ignore_unpopulated ) elif collection_fn is collections.column_keyed_dict: cc = collection_fn( B.data, ignore_unpopulated_attribute=ignore_unpopulated ) else: assert False class A(decl_base): __tablename__ = "a" id = Column(Integer, primary_key=True) bs = relationship( "B", collection_class=cc, backref="a", ) return A, B @testing.combinations( collections.attribute_keyed_dict, collections.column_keyed_dict, argnames="collection_fn", ) @testing.combinations(True, False, argnames="ignore_unpopulated") def test_attr_unpopulated_backref_assign( self, decl_base, collection_fn, ignore_unpopulated ): A, B = self._fixture(decl_base, collection_fn, ignore_unpopulated) a1 = A() if ignore_unpopulated: a1.bs["bar"] = b = B(a=a1) eq_(a1.bs, {"bar": b}) assert None not in a1.bs else: with expect_raises_message( sa_exc.InvalidRequestError, "In event triggered from population of attribute 'B.a'", ): a1.bs["bar"] = B(a=a1) @testing.combinations( collections.attribute_keyed_dict, collections.column_keyed_dict, argnames="collection_fn", ) @testing.combinations(True, False, argnames="ignore_unpopulated") def test_attr_unpopulated_backref_del( self, decl_base, collection_fn, ignore_unpopulated ): A, B = self._fixture(decl_base, collection_fn, ignore_unpopulated) a1 = A() b1 = B(data="bar") a1.bs["bar"] = b1 del b1.__dict__["data"] if ignore_unpopulated: b1.a = None else: with expect_raises_message( sa_exc.InvalidRequestError, "In event triggered from population of attribute 'B.a'", ): b1.a = None @testing.combinations( collections.attribute_keyed_dict, collections.column_keyed_dict, argnames="collection_fn", ) @testing.variation("ignore_unpopulated", [True, False]) @testing.variation("attr_is_actually_none", [True, False]) def test_what_about_lazy_loading( self, decl_base, collection_fn, ignore_unpopulated, attr_is_actually_none, ): """test additional use case that wasn't considered for #8372""" A, B = self._fixture( decl_base, collection_fn, bool(ignore_unpopulated) ) decl_base.metadata.create_all(testing.db) sess = fixture_session() a1 = A() if attr_is_actually_none: b1 = B() else: b1 = B(data="bar") sess.add_all([a1, b1]) sess.commit() # load empty a1.bs so that backref populates it a1.bs # b1.data not loaded assert "data" not in b1.__dict__ # a1.bs is present, will need to be populated assert "bs" in a1.__dict__ if attr_is_actually_none and not ignore_unpopulated: with expect_warnings( "Attribute keyed dictionary value for attribute " "'B.a' was None;", ): b1.a = a1 else: b1.a = a1 # it loaded assert "data" in b1.__dict__ if attr_is_actually_none: if ignore_unpopulated: eq_(a1.bs, {}) else: eq_(a1.bs, {None: b1}) else: eq_(a1.bs, {"bar": b1})
UnpopulatedAttrTest
python
django__django
django/contrib/gis/db/models/lookups.py
{ "start": 5868, "end": 6095 }
class ____(GISLookup): """ The 'bbcontains' operator returns true if A's bounding box completely contains by B's bounding box. """ lookup_name = "bbcontains" @BaseSpatialField.register_lookup
BBContainsLookup
python
huggingface__transformers
src/transformers/models/mask2former/modeling_mask2former.py
{ "start": 59497, "end": 67701 }
class ____(nn.Module): def __init__(self, config: Mask2FormerConfig, feature_channels): super().__init__() self.config = config feature_dim = config.feature_size mask_dim = config.mask_feature_size num_pos_features = feature_dim // 2 self.position_embedding = Mask2FormerSinePositionEmbedding(num_pos_feats=num_pos_features, normalize=True) self.num_feature_levels = 3 transformer_in_channels = feature_channels[-self.num_feature_levels :] self.transformer_feature_strides = config.feature_strides[-self.num_feature_levels :] self.feature_channels = feature_channels self.level_embed = nn.Parameter(torch.Tensor(self.num_feature_levels, feature_dim)) # Create input projection layers if self.num_feature_levels > 1: input_projections_list = [] for in_channels in transformer_in_channels[::-1]: input_projections_list.append( nn.Sequential( nn.Conv2d(in_channels, feature_dim, kernel_size=1), nn.GroupNorm(32, feature_dim), ) ) self.input_projections = nn.ModuleList(input_projections_list) else: self.input_projections = nn.ModuleList( [ nn.Sequential( nn.Conv2d(transformer_in_channels[-1], feature_dim, kernel_size=1), nn.GroupNorm(32, feature_dim), ) ] ) self.encoder = Mask2FormerPixelDecoderEncoderOnly(config) self.mask_projection = nn.Conv2d(feature_dim, mask_dim, kernel_size=1, stride=1, padding=0) # Extra FPN levels stride = min(self.transformer_feature_strides) self.common_stride = config.common_stride self.num_fpn_levels = int(np.log2(stride) - np.log2(self.common_stride)) lateral_convs = [] output_convs = [] for idx, in_channels in enumerate(self.feature_channels[: self.num_fpn_levels]): lateral_conv = nn.Sequential( nn.Conv2d(in_channels, feature_dim, kernel_size=1, bias=False), nn.GroupNorm(32, feature_dim), ) output_conv = nn.Sequential( nn.Conv2d(feature_dim, feature_dim, kernel_size=3, stride=1, padding=1, bias=False), nn.GroupNorm(32, feature_dim), nn.ReLU(), ) self.add_module(f"adapter_{idx + 1}", lateral_conv) self.add_module(f"layer_{idx + 1}", output_conv) lateral_convs.append(lateral_conv) output_convs.append(output_conv) # Order convolutional layers from low to high resolution self.lateral_convolutions = lateral_convs[::-1] self.output_convolutions = output_convs[::-1] def get_valid_ratio(self, mask, dtype=torch.float32): """Get the valid ratio of all feature maps.""" _, height, width = mask.shape valid_height = torch.sum(~mask[:, :, 0], 1) valid_width = torch.sum(~mask[:, 0, :], 1) valid_ratio_height = valid_height.to(dtype) / height valid_ratio_width = valid_width.to(dtype) / width valid_ratio = torch.stack([valid_ratio_width, valid_ratio_height], -1) return valid_ratio def forward( self, features, encoder_outputs=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) # Apply 1x1 convolution to reduce the channel dimension to d_model (256 by default) input_embeds = [] position_embeddings = [] for level, x in enumerate(features[::-1][: self.num_feature_levels]): input_embeds.append(self.input_projections[level](x)) position_embeddings.append(self.position_embedding(x.shape, x.device, x.dtype)) masks = [ torch.zeros((x.size(0), x.size(2), x.size(3)), device=x.device, dtype=torch.bool) for x in input_embeds ] # Prepare encoder inputs (by flattening) spatial_shapes_list = [(embed.shape[2], embed.shape[3]) for embed in input_embeds] input_embeds_flat = torch.cat([embed.flatten(2).transpose(1, 2) for embed in input_embeds], 1) spatial_shapes = torch.as_tensor(spatial_shapes_list, dtype=torch.long, device=input_embeds_flat.device) masks_flat = torch.cat([mask.flatten(1) for mask in masks], 1) position_embeddings = [embed.flatten(2).transpose(1, 2) for embed in position_embeddings] level_pos_embed_flat = [x + self.level_embed[i].view(1, 1, -1) for i, x in enumerate(position_embeddings)] level_pos_embed_flat = torch.cat(level_pos_embed_flat, 1) level_start_index = torch.cat((spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1])) valid_ratios = torch.stack([self.get_valid_ratio(mask, dtype=input_embeds_flat.dtype) for mask in masks], 1) # Send input_embeds_flat + masks_flat + level_pos_embed_flat (backbone + proj layer output) through encoder if encoder_outputs is None: encoder_outputs = self.encoder( inputs_embeds=input_embeds_flat, attention_mask=masks_flat, position_embeddings=level_pos_embed_flat, spatial_shapes_list=spatial_shapes_list, level_start_index=level_start_index, valid_ratios=valid_ratios, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) last_hidden_state = encoder_outputs.last_hidden_state batch_size = last_hidden_state.shape[0] # We compute level_start_index_list separately from the tensor version level_start_index # to avoid iterating over a tensor which breaks torch.compile/export. level_start_index_list = [0] for height, width in spatial_shapes_list[:-1]: level_start_index_list.append(level_start_index_list[-1] + height * width) split_sizes = [None] * self.num_feature_levels for i in range(self.num_feature_levels): if i < self.num_feature_levels - 1: split_sizes[i] = level_start_index_list[i + 1] - level_start_index_list[i] else: split_sizes[i] = last_hidden_state.shape[1] - level_start_index_list[i] encoder_output = torch.split(last_hidden_state, split_sizes, dim=1) # Compute final features outputs = [ x.transpose(1, 2).view(batch_size, -1, spatial_shapes_list[i][0], spatial_shapes_list[i][1]) for i, x in enumerate(encoder_output) ] # Append extra FPN levels to outputs, ordered from low to high resolution for idx, feature in enumerate(features[: self.num_fpn_levels][::-1]): lateral_conv = self.lateral_convolutions[idx] output_conv = self.output_convolutions[idx] current_fpn = lateral_conv(feature) # Following FPN implementation, we use nearest upsampling here out = current_fpn + nn.functional.interpolate( outputs[-1], size=current_fpn.shape[-2:], mode="bilinear", align_corners=False ) out = output_conv(out) outputs.append(out) num_cur_levels = 0 multi_scale_features = [] for out in outputs: if num_cur_levels < self.num_feature_levels: multi_scale_features.append(out) num_cur_levels += 1 return Mask2FormerPixelDecoderOutput( mask_features=self.mask_projection(outputs[-1]), multi_scale_features=tuple(multi_scale_features), attentions=encoder_outputs.attentions, )
Mask2FormerPixelDecoder
python
scipy__scipy
scipy/stats/_multivariate.py
{ "start": 230333, "end": 254996 }
class ____(multi_rv_generic): r"""A von Mises-Fisher variable. The `mu` keyword specifies the mean direction vector. The `kappa` keyword specifies the concentration parameter. Methods ------- pdf(x, mu=None, kappa=1) Probability density function. logpdf(x, mu=None, kappa=1) Log of the probability density function. rvs(mu=None, kappa=1, size=1, random_state=None) Draw random samples from a von Mises-Fisher distribution. entropy(mu=None, kappa=1) Compute the differential entropy of the von Mises-Fisher distribution. fit(data) Fit a von Mises-Fisher distribution to data. Parameters ---------- mu : array_like Mean direction of the distribution. Must be a one-dimensional unit vector of norm 1. kappa : float Concentration parameter. Must be positive. seed : {None, int, np.random.RandomState, np.random.Generator}, optional Used for drawing random variates. If `seed` is `None`, the `~np.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with seed. If `seed` is already a ``RandomState`` or ``Generator`` instance, then that object is used. Default is `None`. See Also -------- scipy.stats.vonmises : Von-Mises Fisher distribution in 2D on a circle uniform_direction : uniform distribution on the surface of a hypersphere Notes ----- The von Mises-Fisher distribution is a directional distribution on the surface of the unit hypersphere. The probability density function of a unit vector :math:`\mathbf{x}` is .. math:: f(\mathbf{x}) = \frac{\kappa^{d/2-1}}{(2\pi)^{d/2}I_{d/2-1}(\kappa)} \exp\left(\kappa \mathbf{\mu}^T\mathbf{x}\right), where :math:`\mathbf{\mu}` is the mean direction, :math:`\kappa` the concentration parameter, :math:`d` the dimension and :math:`I` the modified Bessel function of the first kind. As :math:`\mu` represents a direction, it must be a unit vector or in other words, a point on the hypersphere: :math:`\mathbf{\mu}\in S^{d-1}`. :math:`\kappa` is a concentration parameter, which means that it must be positive (:math:`\kappa>0`) and that the distribution becomes more narrow with increasing :math:`\kappa`. In that sense, the reciprocal value :math:`1/\kappa` resembles the variance parameter of the normal distribution. The von Mises-Fisher distribution often serves as an analogue of the normal distribution on the sphere. Intuitively, for unit vectors, a useful distance measure is given by the angle :math:`\alpha` between them. This is exactly what the scalar product :math:`\mathbf{\mu}^T\mathbf{x}=\cos(\alpha)` in the von Mises-Fisher probability density function describes: the angle between the mean direction :math:`\mathbf{\mu}` and the vector :math:`\mathbf{x}`. The larger the angle between them, the smaller the probability to observe :math:`\mathbf{x}` for this particular mean direction :math:`\mathbf{\mu}`. In dimensions 2 and 3, specialized algorithms are used for fast sampling [2]_, [3]_. For dimensions of 4 or higher the rejection sampling algorithm described in [4]_ is utilized. This implementation is partially based on the geomstats package [5]_, [6]_. .. versionadded:: 1.11 References ---------- .. [1] Von Mises-Fisher distribution, Wikipedia, https://en.wikipedia.org/wiki/Von_Mises%E2%80%93Fisher_distribution .. [2] Mardia, K., and Jupp, P. Directional statistics. Wiley, 2000. .. [3] J. Wenzel. Numerically stable sampling of the von Mises Fisher distribution on S2. https://www.mitsuba-renderer.org/~wenzel/files/vmf.pdf .. [4] Wood, A. Simulation of the von mises fisher distribution. Communications in statistics-simulation and computation 23, 1 (1994), 157-164. https://doi.org/10.1080/03610919408813161 .. [5] geomstats, Github. MIT License. Accessed: 06.01.2023. https://github.com/geomstats/geomstats .. [6] Miolane, N. et al. Geomstats: A Python Package for Riemannian Geometry in Machine Learning. Journal of Machine Learning Research 21 (2020). http://jmlr.org/papers/v21/19-027.html Examples -------- **Visualization of the probability density** Plot the probability density in three dimensions for increasing concentration parameter. The density is calculated by the ``pdf`` method. >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy.stats import vonmises_fisher >>> from matplotlib.colors import Normalize >>> n_grid = 100 >>> u = np.linspace(0, np.pi, n_grid) >>> v = np.linspace(0, 2 * np.pi, n_grid) >>> u_grid, v_grid = np.meshgrid(u, v) >>> vertices = np.stack([np.cos(v_grid) * np.sin(u_grid), ... np.sin(v_grid) * np.sin(u_grid), ... np.cos(u_grid)], ... axis=2) >>> x = np.outer(np.cos(v), np.sin(u)) >>> y = np.outer(np.sin(v), np.sin(u)) >>> z = np.outer(np.ones_like(u), np.cos(u)) >>> def plot_vmf_density(ax, x, y, z, vertices, mu, kappa): ... vmf = vonmises_fisher(mu, kappa) ... pdf_values = vmf.pdf(vertices) ... pdfnorm = Normalize(vmin=pdf_values.min(), vmax=pdf_values.max()) ... ax.plot_surface(x, y, z, rstride=1, cstride=1, ... facecolors=plt.cm.viridis(pdfnorm(pdf_values)), ... linewidth=0) ... ax.set_aspect('equal') ... ax.view_init(azim=-130, elev=0) ... ax.axis('off') ... ax.set_title(rf"$\kappa={kappa}$") >>> fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(9, 4), ... subplot_kw={"projection": "3d"}) >>> left, middle, right = axes >>> mu = np.array([-np.sqrt(0.5), -np.sqrt(0.5), 0]) >>> plot_vmf_density(left, x, y, z, vertices, mu, 5) >>> plot_vmf_density(middle, x, y, z, vertices, mu, 20) >>> plot_vmf_density(right, x, y, z, vertices, mu, 100) >>> plt.subplots_adjust(top=1, bottom=0.0, left=0.0, right=1.0, wspace=0.) >>> plt.show() As we increase the concentration parameter, the points are getting more clustered together around the mean direction. **Sampling** Draw 5 samples from the distribution using the ``rvs`` method resulting in a 5x3 array. >>> rng = np.random.default_rng() >>> mu = np.array([0, 0, 1]) >>> samples = vonmises_fisher(mu, 20).rvs(5, random_state=rng) >>> samples array([[ 0.3884594 , -0.32482588, 0.86231516], [ 0.00611366, -0.09878289, 0.99509023], [-0.04154772, -0.01637135, 0.99900239], [-0.14613735, 0.12553507, 0.98126695], [-0.04429884, -0.23474054, 0.97104814]]) These samples are unit vectors on the sphere :math:`S^2`. To verify, let us calculate their euclidean norms: >>> np.linalg.norm(samples, axis=1) array([1., 1., 1., 1., 1.]) Plot 20 observations drawn from the von Mises-Fisher distribution for increasing concentration parameter :math:`\kappa`. The red dot highlights the mean direction :math:`\mu`. >>> def plot_vmf_samples(ax, x, y, z, mu, kappa): ... vmf = vonmises_fisher(mu, kappa) ... samples = vmf.rvs(20) ... ax.plot_surface(x, y, z, rstride=1, cstride=1, linewidth=0, ... alpha=0.2) ... ax.scatter(samples[:, 0], samples[:, 1], samples[:, 2], c='k', s=5) ... ax.scatter(mu[0], mu[1], mu[2], c='r', s=30) ... ax.set_aspect('equal') ... ax.view_init(azim=-130, elev=0) ... ax.axis('off') ... ax.set_title(rf"$\kappa={kappa}$") >>> mu = np.array([-np.sqrt(0.5), -np.sqrt(0.5), 0]) >>> fig, axes = plt.subplots(nrows=1, ncols=3, ... subplot_kw={"projection": "3d"}, ... figsize=(9, 4)) >>> left, middle, right = axes >>> plot_vmf_samples(left, x, y, z, mu, 5) >>> plot_vmf_samples(middle, x, y, z, mu, 20) >>> plot_vmf_samples(right, x, y, z, mu, 100) >>> plt.subplots_adjust(top=1, bottom=0.0, left=0.0, ... right=1.0, wspace=0.) >>> plt.show() The plots show that with increasing concentration :math:`\kappa` the resulting samples are centered more closely around the mean direction. **Fitting the distribution parameters** The distribution can be fitted to data using the ``fit`` method returning the estimated parameters. As a toy example let's fit the distribution to samples drawn from a known von Mises-Fisher distribution. >>> mu, kappa = np.array([0, 0, 1]), 20 >>> samples = vonmises_fisher(mu, kappa).rvs(1000, random_state=rng) >>> mu_fit, kappa_fit = vonmises_fisher.fit(samples) >>> mu_fit, kappa_fit (array([0.01126519, 0.01044501, 0.99988199]), 19.306398751730995) We see that the estimated parameters `mu_fit` and `kappa_fit` are very close to the ground truth parameters. """ def __init__(self, seed=None): super().__init__(seed) def __call__(self, mu=None, kappa=1, seed=None): """Create a frozen von Mises-Fisher distribution. See `vonmises_fisher_frozen` for more information. """ return vonmises_fisher_frozen(mu, kappa, seed=seed) def _process_parameters(self, mu, kappa): """ Infer dimensionality from mu and ensure that mu is a one-dimensional unit vector and kappa positive. """ mu = np.asarray(mu) if mu.ndim > 1: raise ValueError("'mu' must have one-dimensional shape.") if not np.allclose(np.linalg.norm(mu), 1.): raise ValueError("'mu' must be a unit vector of norm 1.") if not mu.size > 1: raise ValueError("'mu' must have at least two entries.") kappa_error_msg = "'kappa' must be a positive scalar." if not np.isscalar(kappa) or kappa < 0: raise ValueError(kappa_error_msg) if float(kappa) == 0.: raise ValueError("For 'kappa=0' the von Mises-Fisher distribution " "becomes the uniform distribution on the sphere " "surface. Consider using " "'scipy.stats.uniform_direction' instead.") dim = mu.size return dim, mu, kappa def _check_data_vs_dist(self, x, dim): if x.shape[-1] != dim: raise ValueError("The dimensionality of the last axis of 'x' must " "match the dimensionality of the " "von Mises Fisher distribution.") if not np.allclose(np.linalg.norm(x, axis=-1), 1.): msg = "'x' must be unit vectors of norm 1 along last dimension." raise ValueError(msg) def _log_norm_factor(self, dim, kappa): # normalization factor is given by # c = kappa**(dim/2-1)/((2*pi)**(dim/2)*I[dim/2-1](kappa)) # = kappa**(dim/2-1)*exp(-kappa) / # ((2*pi)**(dim/2)*I[dim/2-1](kappa)*exp(-kappa) # = kappa**(dim/2-1)*exp(-kappa) / # ((2*pi)**(dim/2)*ive[dim/2-1](kappa) # Then the log is given by # log c = 1/2*(dim -1)*log(kappa) - kappa - -1/2*dim*ln(2*pi) - # ive[dim/2-1](kappa) halfdim = 0.5 * dim return (0.5 * (dim - 2)*np.log(kappa) - halfdim * _LOG_2PI - np.log(ive(halfdim - 1, kappa)) - kappa) def _logpdf(self, x, dim, mu, kappa): """Log of the von Mises-Fisher probability density function. As this function does no argument checking, it should not be called directly; use 'logpdf' instead. """ x = np.asarray(x) self._check_data_vs_dist(x, dim) dotproducts = np.einsum('i,...i->...', mu, x) return self._log_norm_factor(dim, kappa) + kappa * dotproducts def logpdf(self, x, mu=None, kappa=1): """Log of the von Mises-Fisher probability density function. Parameters ---------- x : array_like Points at which to evaluate the log of the probability density function. The last axis of `x` must correspond to unit vectors of the same dimensionality as the distribution. mu : array_like, default: None Mean direction of the distribution. Must be a one-dimensional unit vector of norm 1. kappa : float, default: 1 Concentration parameter. Must be positive. Returns ------- logpdf : ndarray or scalar Log of the probability density function evaluated at `x`. """ dim, mu, kappa = self._process_parameters(mu, kappa) return self._logpdf(x, dim, mu, kappa) def pdf(self, x, mu=None, kappa=1): """Von Mises-Fisher probability density function. Parameters ---------- x : array_like Points at which to evaluate the probability density function. The last axis of `x` must correspond to unit vectors of the same dimensionality as the distribution. mu : array_like Mean direction of the distribution. Must be a one-dimensional unit vector of norm 1. kappa : float Concentration parameter. Must be positive. Returns ------- pdf : ndarray or scalar Probability density function evaluated at `x`. """ dim, mu, kappa = self._process_parameters(mu, kappa) return np.exp(self._logpdf(x, dim, mu, kappa)) def _rvs_2d(self, mu, kappa, size, random_state): """ In 2D, the von Mises-Fisher distribution reduces to the von Mises distribution which can be efficiently sampled by numpy. This method is much faster than the general rejection sampling based algorithm. """ mean_angle = np.arctan2(mu[1], mu[0]) angle_samples = random_state.vonmises(mean_angle, kappa, size=size) samples = np.stack([np.cos(angle_samples), np.sin(angle_samples)], axis=-1) return samples def _rvs_3d(self, kappa, size, random_state): """ Generate samples from a von Mises-Fisher distribution with mu = [1, 0, 0] and kappa. Samples then have to be rotated towards the desired mean direction mu. This method is much faster than the general rejection sampling based algorithm. Reference: https://www.mitsuba-renderer.org/~wenzel/files/vmf.pdf """ if size is None: sample_size = 1 else: sample_size = size # compute x coordinate acc. to equation from section 3.1 x = random_state.random(sample_size) x = 1. + np.log(x + (1. - x) * np.exp(-2 * kappa))/kappa # (y, z) are random 2D vectors that only have to be # normalized accordingly. Then (x, y z) follow a VMF distribution temp = np.sqrt(1. - np.square(x)) uniformcircle = _sample_uniform_direction(2, sample_size, random_state) samples = np.stack([x, temp * uniformcircle[..., 0], temp * uniformcircle[..., 1]], axis=-1) if size is None: samples = np.squeeze(samples) return samples def _rejection_sampling(self, dim, kappa, size, random_state): """ Generate samples from an n-dimensional von Mises-Fisher distribution with mu = [1, 0, ..., 0] and kappa via rejection sampling. Samples then have to be rotated towards the desired mean direction mu. Reference: https://doi.org/10.1080/03610919408813161 """ dim_minus_one = dim - 1 # calculate number of requested samples if size is not None: if not np.iterable(size): size = (size, ) n_samples = math.prod(size) else: n_samples = 1 # calculate envelope for rejection sampler (eq. 4) sqrt = np.sqrt(4 * kappa ** 2. + dim_minus_one ** 2) envelop_param = (-2 * kappa + sqrt) / dim_minus_one if envelop_param == 0: # the regular formula suffers from loss of precision for high # kappa. This can only be detected by checking for 0 here. # Workaround: expansion for sqrt variable # https://www.wolframalpha.com/input?i=sqrt%284*x%5E2%2Bd%5E2%29 # e = (-2 * k + sqrt(k**2 + d**2)) / d # ~ (-2 * k + 2 * k + d**2/(4 * k) - d**4/(64 * k**3)) / d # = d/(4 * k) - d**3/(64 * k**3) envelop_param = (dim_minus_one/4 * kappa**-1. - dim_minus_one**3/64 * kappa**-3.) # reference step 0 node = (1. - envelop_param) / (1. + envelop_param) # t = ln(1 - ((1-x)/(1+x))**2) # = ln(4 * x / (1+x)**2) # = ln(4) + ln(x) - 2*log1p(x) correction = (kappa * node + dim_minus_one * (np.log(4) + np.log(envelop_param) - 2 * np.log1p(envelop_param))) n_accepted = 0 x = np.zeros((n_samples, )) halfdim = 0.5 * dim_minus_one # main loop while n_accepted < n_samples: # generate candidates acc. to reference step 1 sym_beta = random_state.beta(halfdim, halfdim, size=n_samples - n_accepted) coord_x = (1 - (1 + envelop_param) * sym_beta) / ( 1 - (1 - envelop_param) * sym_beta) # accept or reject: reference step 2 # reformulation for numerical stability: # t = ln(1 - (1-x)/(1+x) * y) # = ln((1 + x - y +x*y)/(1 +x)) accept_tol = random_state.random(n_samples - n_accepted) criterion = ( kappa * coord_x + dim_minus_one * (np.log((1 + envelop_param - coord_x + coord_x * envelop_param) / (1 + envelop_param))) - correction) > np.log(accept_tol) accepted_iter = np.sum(criterion) x[n_accepted:n_accepted + accepted_iter] = coord_x[criterion] n_accepted += accepted_iter # concatenate x and remaining coordinates: step 3 coord_rest = _sample_uniform_direction(dim_minus_one, n_accepted, random_state) coord_rest = np.einsum( '...,...i->...i', np.sqrt(1 - x ** 2), coord_rest) samples = np.concatenate([x[..., None], coord_rest], axis=1) # reshape output to (size, dim) if size is not None: samples = samples.reshape(size + (dim, )) else: samples = np.squeeze(samples) return samples def _rotate_samples(self, samples, mu, dim): """A QR decomposition is used to find the rotation that maps the north pole (1, 0,...,0) to the vector mu. This rotation is then applied to all samples. Parameters ---------- samples: array_like, shape = [..., n] mu : array-like, shape=[n, ] Point to parametrise the rotation. Returns ------- samples : rotated samples """ base_point = np.zeros((dim, )) base_point[0] = 1. embedded = np.concatenate([mu[None, :], np.zeros((dim - 1, dim))]) rotmatrix, _ = np.linalg.qr(np.transpose(embedded)) if np.allclose(np.matmul(rotmatrix, base_point[:, None])[:, 0], mu): rotsign = 1 else: rotsign = -1 # apply rotation samples = np.einsum('ij,...j->...i', rotmatrix, samples) * rotsign return samples def _rvs(self, dim, mu, kappa, size, random_state): if dim == 2: samples = self._rvs_2d(mu, kappa, size, random_state) elif dim == 3: samples = self._rvs_3d(kappa, size, random_state) else: samples = self._rejection_sampling(dim, kappa, size, random_state) if dim != 2: samples = self._rotate_samples(samples, mu, dim) return samples def rvs(self, mu=None, kappa=1, size=1, random_state=None): """Draw random samples from a von Mises-Fisher distribution. Parameters ---------- mu : array_like Mean direction of the distribution. Must be a one-dimensional unit vector of norm 1. kappa : float Concentration parameter. Must be positive. size : int or tuple of ints, optional Given a shape of, for example, (m,n,k), m*n*k samples are generated, and packed in an m-by-n-by-k arrangement. Because each sample is N-dimensional, the output shape is (m,n,k,N). If no shape is specified, a single (N-D) sample is returned. random_state : {None, int, np.random.RandomState, np.random.Generator}, optional Used for drawing random variates. If `seed` is `None`, the `~np.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with seed. If `seed` is already a ``RandomState`` or ``Generator`` instance, then that object is used. Default is `None`. Returns ------- rvs : ndarray Random variates of shape (`size`, `N`), where `N` is the dimension of the distribution. """ dim, mu, kappa = self._process_parameters(mu, kappa) random_state = self._get_random_state(random_state) samples = self._rvs(dim, mu, kappa, size, random_state) return samples def _entropy(self, dim, kappa): halfdim = 0.5 * dim return (-self._log_norm_factor(dim, kappa) - kappa * ive(halfdim, kappa) / ive(halfdim - 1, kappa)) def entropy(self, mu=None, kappa=1): """Compute the differential entropy of the von Mises-Fisher distribution. Parameters ---------- mu : array_like, default: None Mean direction of the distribution. Must be a one-dimensional unit vector of norm 1. kappa : float, default: 1 Concentration parameter. Must be positive. Returns ------- h : scalar Entropy of the von Mises-Fisher distribution. """ dim, _, kappa = self._process_parameters(mu, kappa) return self._entropy(dim, kappa) def fit(self, x): """Fit the von Mises-Fisher distribution to data. Parameters ---------- x : array-like Data the distribution is fitted to. Must be two dimensional. The second axis of `x` must be unit vectors of norm 1 and determine the dimensionality of the fitted von Mises-Fisher distribution. Returns ------- mu : ndarray Estimated mean direction. kappa : float Estimated concentration parameter. """ # validate input data x = np.asarray(x) if x.ndim != 2: raise ValueError("'x' must be two dimensional.") if not np.allclose(np.linalg.norm(x, axis=-1), 1.): msg = "'x' must be unit vectors of norm 1 along last dimension." raise ValueError(msg) dim = x.shape[-1] # mu is simply the directional mean dirstats = directional_stats(x) mu = dirstats.mean_direction r = dirstats.mean_resultant_length # kappa is the solution to the equation: # r = I[dim/2](kappa) / I[dim/2 -1](kappa) # = I[dim/2](kappa) * exp(-kappa) / I[dim/2 -1](kappa) * exp(-kappa) # = ive(dim/2, kappa) / ive(dim/2 -1, kappa) halfdim = 0.5 * dim def solve_for_kappa(kappa): bessel_vals = ive([halfdim, halfdim - 1], kappa) return bessel_vals[0]/bessel_vals[1] - r root_res = root_scalar(solve_for_kappa, method="brentq", bracket=(1e-8, 1e9)) kappa = root_res.root return mu, kappa vonmises_fisher = vonmises_fisher_gen()
vonmises_fisher_gen
python
cython__cython
Cython/Utils.py
{ "start": 898, "end": 15837 }
class ____: """ Fast, bare minimum @contextmanager, only for try-finally, not for exception handling. """ def __init__(self, gen): self._gen = gen def __enter__(self): return next(self._gen) def __exit__(self, exc_type, exc_val, exc_tb): try: next(self._gen) except (StopIteration, GeneratorExit): pass def try_finally_contextmanager(gen_func): @wraps(gen_func) def make_gen(*args, **kwargs): return _TryFinallyGeneratorContextManager(gen_func(*args, **kwargs)) return make_gen try: from functools import cache as _cache_function except ImportError: from functools import lru_cache _cache_function = lru_cache(maxsize=None) _function_caches = [] def clear_function_caches(): for cache in _function_caches: cache.cache_clear() def cached_function(f): cf = _cache_function(f) _function_caches.append(cf) cf.uncached = f # needed by coverage plugin return cf def _find_cache_attributes(obj): """The function iterates over the attributes of the object and, if it finds the name of the cache, it returns it and the corresponding method name. The method may not be present in the object. """ for attr_name in dir(obj): match = _CACHE_NAME_PATTERN.match(attr_name) if match is not None: yield attr_name, match.group(1) def clear_method_caches(obj): """Removes every cache found in the object, if a corresponding method exists for that cache. """ for cache_name, method_name in _find_cache_attributes(obj): if hasattr(obj, method_name): delattr(obj, cache_name) # if there is no corresponding method, then we assume # that this attribute was not created by our cached method def cached_method(f): cache_name = _build_cache_name(f.__name__) def wrapper(self, *args): cache = getattr(self, cache_name, None) if cache is None: cache = {} setattr(self, cache_name, cache) if args in cache: return cache[args] res = cache[args] = f(self, *args) return res return wrapper def replace_suffix(path, newsuf): base, _ = os.path.splitext(path) return base + newsuf def open_new_file(path): if os.path.exists(path): # Make sure to create a new file here so we can # safely hard link the output files. os.unlink(path) # We only write pure ASCII code strings, but need to write file paths in position comments. # Those are encoded in UTF-8 so that tools can parse them out again. return open(path, "w", encoding="UTF-8") def castrate_file(path, st): # Remove junk contents from an output file after a # failed compilation. # Also sets access and modification times back to # those specified by st (a stat struct). if not is_cython_generated_file(path, allow_failed=True, if_not_found=False): return try: f = open_new_file(path) except OSError: pass else: f.write( "#error Do not use this file, it is the result of a failed Cython compilation.\n") f.close() if st: os.utime(path, (st.st_atime, st.st_mtime-1)) def is_cython_generated_file(path, allow_failed=False, if_not_found=True): failure_marker = b"#error Do not use this file, it is the result of a failed Cython compilation." file_content = None if os.path.exists(path): try: with open(path, "rb") as f: file_content = f.read(len(failure_marker)) except OSError: pass # Probably just doesn't exist any more if file_content is None: # file does not exist (yet) return if_not_found return ( # Cython C file? file_content.startswith(b"/* Generated by Cython ") or # Cython output file after previous failures? (allow_failed and file_content == failure_marker) or # Let's allow overwriting empty files as well. They might have resulted from previous failures. not file_content ) def file_generated_by_this_cython(path): file_content = b'' if os.path.exists(path): try: with open(path, "rb") as f: file_content = f.read(len(GENERATED_BY_MARKER_BYTES)) except OSError: pass # Probably just doesn't exist any more return file_content and file_content.startswith(GENERATED_BY_MARKER_BYTES) def file_newer_than(path, time): ftime = modification_time(path) return ftime > time def safe_makedirs(path): try: os.makedirs(path) except OSError: if not os.path.isdir(path): raise def copy_file_to_dir_if_newer(sourcefile, destdir): """ Copy file sourcefile to directory destdir (creating it if needed), preserving metadata. If the destination file exists and is not older than the source file, the copying is skipped. """ destfile = os.path.join(destdir, os.path.basename(sourcefile)) try: desttime = modification_time(destfile) except OSError: # New file does not exist, destdir may or may not exist safe_makedirs(destdir) else: # New file already exists if not file_newer_than(sourcefile, desttime): return shutil.copy2(sourcefile, destfile) @cached_function def find_root_package_dir(file_path): dir = os.path.dirname(file_path) if file_path == dir: return dir elif is_package_dir(dir): return find_root_package_dir(dir) else: return dir @cached_function def check_package_dir(dir_path, package_names): namespace = True for dirname in package_names: dir_path = os.path.join(dir_path, dirname) has_init = contains_init(dir_path) if has_init: namespace = False return dir_path, namespace @cached_function def contains_init(dir_path): for filename in PACKAGE_FILES: path = os.path.join(dir_path, filename) if path_exists(path): return 1 def is_package_dir(dir_path): if contains_init(dir_path): return 1 @cached_function def path_exists(path): # try on the filesystem first if os.path.exists(path): return True # figure out if a PEP 302 loader is around try: loader = __loader__ # XXX the code below assumes a 'zipimport.zipimporter' instance # XXX should be easy to generalize, but too lazy right now to write it archive_path = getattr(loader, 'archive', None) if archive_path: normpath = os.path.normpath(path) if normpath.startswith(archive_path): arcname = normpath[len(archive_path)+1:] try: loader.get_data(arcname) return True except OSError: return False except NameError: pass return False _parse_file_version = re.compile(r".*[.]cython-([0-9]+)[.][^./\\]+$").findall @cached_function def find_versioned_file(directory, filename, suffix, _current_version=int(re.sub(r"^([0-9]+)[.]([0-9]+).*", r"\1\2", cython_version))): """ Search a directory for versioned pxd files, e.g. "lib.cython-30.pxd" for a Cython 3.0+ version. @param directory: the directory to search @param filename: the filename without suffix @param suffix: the filename extension including the dot, e.g. ".pxd" @return: the file path if found, or None """ assert not suffix or suffix[:1] == '.' path_prefix = os.path.join(directory, filename) matching_files = glob.glob(glob.escape(path_prefix) + ".cython-*" + suffix) path = path_prefix + suffix if not os.path.exists(path): path = None best_match = (-1, path) # last resort, if we do not have versioned .pxd files for path in matching_files: versions = _parse_file_version(path) if versions: int_version = int(versions[0]) # Let's assume no duplicates. if best_match[0] < int_version <= _current_version: best_match = (int_version, path) return best_match[1] # file name encodings def decode_filename(filename): if isinstance(filename, bytes): try: filename_encoding = sys.getfilesystemencoding() if filename_encoding is None: filename_encoding = sys.getdefaultencoding() filename = filename.decode(filename_encoding) except UnicodeDecodeError: pass return filename # support for source file encoding detection _match_file_encoding = re.compile(br"(\w*coding)[:=]\s*([-\w.]+)").search def detect_opened_file_encoding(f, default='UTF-8'): # PEPs 263 and 3120 # Most of the time the first two lines fall in the first couple of hundred chars, # and this bulk read/split is much faster. lines = () start = b'' while len(lines) < 3: data = f.read(500) start += data lines = start.split(b"\n") if not data: break m = _match_file_encoding(lines[0]) if m and m.group(1) != b'c_string_encoding': return m.group(2).decode('iso8859-1') elif len(lines) > 1: m = _match_file_encoding(lines[1]) if m: return m.group(2).decode('iso8859-1') return default def skip_bom(f): """ Read past a BOM at the beginning of a source file. This could be added to the scanner, but it's *substantially* easier to keep it at this level. """ if f.read(1) != '\uFEFF': f.seek(0) def open_source_file(source_filename, encoding=None, error_handling=None): stream = None try: if encoding is None: # Most of the time the encoding is not specified, so try hard to open the file only once. f = open(source_filename, 'rb') encoding = detect_opened_file_encoding(f) f.seek(0) stream = io.TextIOWrapper(f, encoding=encoding, errors=error_handling) else: stream = open(source_filename, encoding=encoding, errors=error_handling) except OSError: if os.path.exists(source_filename): raise # File is there, but something went wrong reading from it. # Allow source files to be in zip files etc. try: loader = __loader__ if source_filename.startswith(loader.archive): stream = open_source_from_loader( loader, source_filename, encoding, error_handling) except (NameError, AttributeError): pass if stream is None: raise FileNotFoundError(source_filename) skip_bom(stream) return stream def open_source_from_loader(loader, source_filename, encoding=None, error_handling=None): nrmpath = os.path.normpath(source_filename) arcname = nrmpath[len(loader.archive)+1:] data = loader.get_data(arcname) return io.TextIOWrapper(io.BytesIO(data), encoding=encoding, errors=error_handling) def str_to_number(value): # note: this expects a string as input that was accepted by the # parser already, with an optional "-" sign in front is_neg = False if value[:1] == '-': is_neg = True value = value[1:] if len(value) < 2: value = int(value, 0) elif value[0] == '0': literal_type = value[1] # 0'o' - 0'b' - 0'x' if literal_type in 'xX': # hex notation ('0x1AF') value = strip_py2_long_suffix(value) value = int(value[2:], 16) elif literal_type in 'oO': # Py3 octal notation ('0o136') value = int(value[2:], 8) elif literal_type in 'bB': # Py3 binary notation ('0b101') value = int(value[2:], 2) else: # Py2 octal notation ('0136') value = int(value, 8) else: value = int(value, 0) return -value if is_neg else value def strip_py2_long_suffix(value_str): """ Python 2 likes to append 'L' to stringified numbers which in then can't process when converting them to numbers. """ if value_str[-1] in 'lL': return value_str[:-1] return value_str def long_literal(value): if isinstance(value, str): value = str_to_number(value) return not -2**31 <= value < 2**31 @try_finally_contextmanager def captured_fd(stream=2, encoding=None): orig_stream = os.dup(stream) # keep copy of original stream try: with tempfile.TemporaryFile(mode="a+b") as temp_file: def read_output(_output=[b'']): if not temp_file.closed: temp_file.seek(0) _output[0] = temp_file.read() return _output[0] os.dup2(temp_file.fileno(), stream) # replace stream by copy of pipe def get_output(): result = read_output() return result.decode(encoding) if encoding else result yield get_output # note: @contextlib.contextmanager requires try-finally here os.dup2(orig_stream, stream) # restore original stream read_output() # keep the output in case it's used after closing the context manager finally: os.close(orig_stream) def get_encoding_candidates(): candidates = [sys.getdefaultencoding()] for stream in (sys.stdout, sys.stdin, sys.__stdout__, sys.__stdin__): encoding = getattr(stream, 'encoding', None) # encoding might be None (e.g. somebody redirects stdout): if encoding is not None and encoding not in candidates: candidates.append(encoding) return candidates def prepare_captured(captured): captured_bytes = captured.strip() if not captured_bytes: return None for encoding in get_encoding_candidates(): try: return captured_bytes.decode(encoding) except UnicodeDecodeError: pass # last resort: print at least the readable ascii parts correctly. return captured_bytes.decode('latin-1') def print_captured(captured, output, header_line=None): captured = prepare_captured(captured) if captured: if header_line: output.write(header_line) output.write(captured) def print_bytes(s, header_text=None, end=b'\n', file=sys.stdout, flush=True): if header_text: file.write(header_text) # note: text! => file.write() instead of out.write() file.flush() out = file.buffer out.write(s) if end: out.write(end) if flush: out.flush()
_TryFinallyGeneratorContextManager
python
redis__redis-py
redis/multidb/failover.py
{ "start": 372, "end": 683 }
class ____(ABC): @abstractmethod def database(self) -> SyncDatabase: """Select the database according to the strategy.""" pass @abstractmethod def set_databases(self, databases: Databases) -> None: """Set the database strategy operates on.""" pass
FailoverStrategy
python
keras-team__keras
keras/src/layers/preprocessing/string_lookup.py
{ "start": 360, "end": 18495 }
class ____(IndexLookup): """A preprocessing layer that maps strings to (possibly encoded) indices. This layer translates a set of arbitrary strings into integer output via a table-based vocabulary lookup. This layer will perform no splitting or transformation of input strings. For a layer that can split and tokenize natural language, see the `keras.layers.TextVectorization` layer. The vocabulary for the layer must be either supplied on construction or learned via `adapt()`. During `adapt()`, the layer will analyze a data set, determine the frequency of individual strings tokens, and create a vocabulary from them. If the vocabulary is capped in size, the most frequent tokens will be used to create the vocabulary and all others will be treated as out-of-vocabulary (OOV). There are two possible output modes for the layer. When `output_mode` is `"int"`, input strings are converted to their index in the vocabulary (an integer). When `output_mode` is `"multi_hot"`, `"count"`, or `"tf_idf"`, input strings are encoded into an array where each dimension corresponds to an element in the vocabulary. The vocabulary can optionally contain a mask token as well as an OOV token (which can optionally occupy multiple indices in the vocabulary, as set by `num_oov_indices`). The position of these tokens in the vocabulary is fixed. When `output_mode` is `"int"`, the vocabulary will begin with the mask token (if set), followed by OOV indices, followed by the rest of the vocabulary. When `output_mode` is `"multi_hot"`, `"count"`, or `"tf_idf"` the vocabulary will begin with OOV indices and instances of the mask token will be dropped. **Note:** This layer uses TensorFlow internally. It cannot be used as part of the compiled computation graph of a model with any backend other than TensorFlow. It can however be used with any backend when running eagerly. It can also always be used as part of an input preprocessing pipeline with any backend (outside the model itself), which is how we recommend using this layer. **Note:** This layer is safe to use inside a `tf.data` pipeline (independently of which backend you're using). Args: max_tokens: Maximum size of the vocabulary for this layer. This should only be specified when adapting the vocabulary or when setting `pad_to_max_tokens=True`. If None, there is no cap on the size of the vocabulary. Note that this size includes the OOV and mask tokens. Defaults to `None`. num_oov_indices: The number of out-of-vocabulary tokens to use. If this value is more than 1, OOV inputs are modulated to determine their OOV value. If this value is 0, OOV inputs will cause an error when calling the layer. Defaults to `1`. mask_token: A token that represents masked inputs. When `output_mode` is `"int"`, the token is included in the vocabulary and mapped to index 0. In other output modes, the token will not appear in the vocabulary and instances of the mask token in the input will be dropped. If set to `None`, no mask term will be added. Defaults to `None`. oov_token: Only used when `invert` is True. The token to return for OOV indices. Defaults to `"[UNK]"`. vocabulary: Optional. Either an array of strings or a string path to a text file. If passing an array, you can pass a tuple, list, 1D NumPy array, or 1D tensor containing the string vocabulary terms. If passing a file path, the file should contain one line per term in the vocabulary. If this argument is set, there is no need to `adapt()` the layer. idf_weights: Only valid when `output_mode` is `"tf_idf"`. A tuple, list, 1D NumPy array, or 1D tensor or the same length as the vocabulary, containing the floating point inverse document frequency weights, which will be multiplied by per sample term counts for the final TF-IDF weight. If the `vocabulary` argument is set and `output_mode` is `"tf_idf"`, this argument must be supplied. invert: Only valid when `output_mode` is `"int"`. If `True`, this layer will map indices to vocabulary items instead of mapping vocabulary items to indices. Defaults to `False`. output_mode: Specification for the output of the layer. Values can be `"int"`, `"one_hot"`, `"multi_hot"`, `"count"`, or `"tf_idf"` configuring the layer as follows: - `"int"`: Return the vocabulary indices of the input tokens. - `"one_hot"`: Encodes each individual element in the input into an array the same size as the vocabulary, containing a 1 at the element index. If the last dimension is size 1, will encode on that dimension. If the last dimension is not size 1, will append a new dimension for the encoded output. - `"multi_hot"`: Encodes each sample in the input into a single array the same size as the vocabulary containing a 1 for each vocabulary term present in the sample. Treats the last dimension as the sample dimension, if the input shape is `(..., sample_length)`, the output shape will be `(..., num_tokens)`. - `"count"`: As `"multi_hot"`, but the int array contains a count of the number of times the token at that index appeared in the sample. - `"tf_idf"`: As `"multi_hot"`, but the TF-IDF algorithm is applied to find the value in each token slot. For `"int"` output, any shape of input and output is supported. For all other output modes, currently only output up to rank 2 is supported. Defaults to `"int"`. pad_to_max_tokens: Only applicable when `output_mode` is `"multi_hot"`, `"count"`, or `"tf_idf"`. If `True`, the output will have its feature axis padded to `max_tokens` even if the number of unique tokens in the vocabulary is less than `max_tokens`, resulting in a tensor of shape `(batch_size, max_tokens)` regardless of vocabulary size. Defaults to `False`. sparse: Boolean. Only applicable to `"multi_hot"`, `"count"`, and `"tf_idf"` output modes. Only supported with TensorFlow backend. If `True`, returns a `SparseTensor` instead of a dense `Tensor`. Defaults to `False`. encoding: Optional. The text encoding to use to interpret the input strings. Defaults to `"utf-8"`. Examples: **Creating a lookup layer with a known vocabulary** This example creates a lookup layer with a pre-existing vocabulary. >>> vocab = ["a", "b", "c", "d"] >>> data = [["a", "c", "d"], ["d", "z", "b"]] >>> layer = StringLookup(vocabulary=vocab) >>> layer(data) array([[1, 3, 4], [4, 0, 2]]) **Creating a lookup layer with an adapted vocabulary** This example creates a lookup layer and generates the vocabulary by analyzing the dataset. >>> data = [["a", "c", "d"], ["d", "z", "b"]] >>> layer = StringLookup() >>> layer.adapt(data) >>> layer.get_vocabulary() ['[UNK]', 'd', 'z', 'c', 'b', 'a'] Note that the OOV token `"[UNK]"` has been added to the vocabulary. The remaining tokens are sorted by frequency (`"d"`, which has 2 occurrences, is first) then by inverse sort order. >>> data = [["a", "c", "d"], ["d", "z", "b"]] >>> layer = StringLookup() >>> layer.adapt(data) >>> layer(data) array([[5, 3, 1], [1, 2, 4]]) **Lookups with multiple OOV indices** This example demonstrates how to use a lookup layer with multiple OOV indices. When a layer is created with more than one OOV index, any OOV values are hashed into the number of OOV buckets, distributing OOV values in a deterministic fashion across the set. >>> vocab = ["a", "b", "c", "d"] >>> data = [["a", "c", "d"], ["m", "z", "b"]] >>> layer = StringLookup(vocabulary=vocab, num_oov_indices=2) >>> layer(data) array([[2, 4, 5], [0, 1, 3]]) Note that the output for OOV value 'm' is 0, while the output for OOV value `"z"` is 1. The in-vocab terms have their output index increased by 1 from earlier examples (a maps to 2, etc) in order to make space for the extra OOV value. **One-hot output** Configure the layer with `output_mode='one_hot'`. Note that the first `num_oov_indices` dimensions in the ont_hot encoding represent OOV values. >>> vocab = ["a", "b", "c", "d"] >>> data = ["a", "b", "c", "d", "z"] >>> layer = StringLookup(vocabulary=vocab, output_mode='one_hot') >>> layer(data) array([[0., 1., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 1., 0.], [0., 0., 0., 0., 1.], [1., 0., 0., 0., 0.]], dtype=int64) **Multi-hot output** Configure the layer with `output_mode='multi_hot'`. Note that the first `num_oov_indices` dimensions in the multi_hot encoding represent OOV values. >>> vocab = ["a", "b", "c", "d"] >>> data = [["a", "c", "d", "d"], ["d", "z", "b", "z"]] >>> layer = StringLookup(vocabulary=vocab, output_mode='multi_hot') >>> layer(data) array([[0., 1., 0., 1., 1.], [1., 0., 1., 0., 1.]], dtype=int64) **Token count output** Configure the layer with `output_mode='count'`. As with multi_hot output, the first `num_oov_indices` dimensions in the output represent OOV values. >>> vocab = ["a", "b", "c", "d"] >>> data = [["a", "c", "d", "d"], ["d", "z", "b", "z"]] >>> layer = StringLookup(vocabulary=vocab, output_mode='count') >>> layer(data) array([[0., 1., 0., 1., 2.], [2., 0., 1., 0., 1.]], dtype=int64) **TF-IDF output** Configure the layer with `output_mode="tf_idf"`. As with multi_hot output, the first `num_oov_indices` dimensions in the output represent OOV values. Each token bin will output `token_count * idf_weight`, where the idf weights are the inverse document frequency weights per token. These should be provided along with the vocabulary. Note that the `idf_weight` for OOV values will default to the average of all idf weights passed in. >>> vocab = ["a", "b", "c", "d"] >>> idf_weights = [0.25, 0.75, 0.6, 0.4] >>> data = [["a", "c", "d", "d"], ["d", "z", "b", "z"]] >>> layer = StringLookup(output_mode="tf_idf") >>> layer.set_vocabulary(vocab, idf_weights=idf_weights) >>> layer(data) array([[0. , 0.25, 0. , 0.6 , 0.8 ], [1.0 , 0. , 0.75, 0. , 0.4 ]], dtype=float32) To specify the idf weights for OOV values, you will need to pass the entire vocabulary including the leading OOV token. >>> vocab = ["[UNK]", "a", "b", "c", "d"] >>> idf_weights = [0.9, 0.25, 0.75, 0.6, 0.4] >>> data = [["a", "c", "d", "d"], ["d", "z", "b", "z"]] >>> layer = StringLookup(output_mode="tf_idf") >>> layer.set_vocabulary(vocab, idf_weights=idf_weights) >>> layer(data) array([[0. , 0.25, 0. , 0.6 , 0.8 ], [1.8 , 0. , 0.75, 0. , 0.4 ]], dtype=float32) When adapting the layer in `"tf_idf"` mode, each input sample will be considered a document, and IDF weight per token will be calculated as `log(1 + num_documents / (1 + token_document_count))`. **Inverse lookup** This example demonstrates how to map indices to strings using this layer. (You can also use `adapt()` with `inverse=True`, but for simplicity we'll pass the vocab in this example.) >>> vocab = ["a", "b", "c", "d"] >>> data = [[1, 3, 4], [4, 0, 2]] >>> layer = StringLookup(vocabulary=vocab, invert=True) >>> layer(data) array([[b'a', b'c', b'd'], [b'd', b'[UNK]', b'b']], dtype=object) Note that the first index corresponds to the OOV token by default. **Forward and inverse lookup pairs** This example demonstrates how to use the vocabulary of a standard lookup layer to create an inverse lookup layer. >>> vocab = ["a", "b", "c", "d"] >>> data = [["a", "c", "d"], ["d", "z", "b"]] >>> layer = StringLookup(vocabulary=vocab) >>> i_layer = StringLookup(vocabulary=vocab, invert=True) >>> int_data = layer(data) >>> i_layer(int_data) array([[b'a', b'c', b'd'], [b'd', b'[UNK]', b'b']], dtype=object) In this example, the input value `"z"` resulted in an output of `"[UNK]"`, since 1000 was not in the vocabulary - it got represented as an OOV, and all OOV values are returned as `"[UNK]"` in the inverse layer. Also, note that for the inverse to work, you must have already set the forward layer vocabulary either directly or via `adapt()` before calling `get_vocabulary()`. """ def __init__( self, max_tokens=None, num_oov_indices=1, mask_token=None, oov_token="[UNK]", vocabulary=None, idf_weights=None, invert=False, output_mode="int", pad_to_max_tokens=False, sparse=False, encoding="utf-8", name=None, **kwargs, ): if not tf.available: raise ImportError( "Layer StringLookup requires TensorFlow. " "Install it via `pip install tensorflow`." ) if sparse and backend.backend() != "tensorflow": raise ValueError( "`sparse=True` can only be used with the TensorFlow backend." ) self.encoding = encoding super().__init__( max_tokens=max_tokens, num_oov_indices=num_oov_indices, mask_token=mask_token, oov_token=oov_token, vocabulary=vocabulary, idf_weights=idf_weights, invert=invert, output_mode=output_mode, pad_to_max_tokens=pad_to_max_tokens, sparse=sparse, name=name, vocabulary_dtype="string", **kwargs, ) self._convert_input_args = False self._allow_non_tensor_positional_args = True self.supports_jit = False def adapt(self, data, steps=None): """Computes a vocabulary of terms from tokens in a dataset. Calling `adapt()` on a `StringLookup` layer is an alternative to passing in a precomputed vocabulary on construction via the `vocabulary` argument. A `StringLookup` layer should always be either adapted over a dataset or supplied with a vocabulary. During `adapt()`, the layer will build a vocabulary of all string tokens seen in the dataset, sorted by occurrence count, with ties broken by sort order of the tokens (high to low). At the end of `adapt()`, if `max_tokens` is set, the vocabulary will be truncated to `max_tokens` size. For example, adapting a layer with `max_tokens=1000` will compute the 1000 most frequent tokens occurring in the input dataset. If `output_mode='tf-idf'`, `adapt()` will also learn the document frequencies of each token in the input dataset. Arguments: data: The data to train on. It can be passed either as a batched `tf.data.Dataset`, as a list of strings, or as a NumPy array. steps: Integer or `None`. Total number of steps (batches of samples) to process. If `data` is a `tf.data.Dataset`, and `steps` is `None`, `adapt()` will run until the input dataset is exhausted. When passing an infinitely repeating dataset, you must specify the `steps` argument. This argument is not supported with array inputs or list inputs. """ super().adapt(data, steps=steps) # Overridden methods from IndexLookup. def _tensor_vocab_to_numpy(self, vocabulary): vocabulary = vocabulary.numpy() return np.array( [tf.compat.as_text(x, self.encoding) for x in vocabulary] ) def get_config(self): config = {"encoding": self.encoding} base_config = super().get_config() # There is only one valid dtype for strings, so we don't expose this. del base_config["vocabulary_dtype"] return {**base_config, **config} def call(self, inputs): is_torch_backend = backend.backend() == "torch" # Handle input conversion inputs_for_processing = inputs was_tf_input = isinstance( inputs, (tf.Tensor, tf.RaggedTensor, tf.SparseTensor) ) if is_torch_backend and isinstance(inputs, torch.Tensor): inputs_for_processing = tf.convert_to_tensor( inputs.detach().cpu().numpy() ) elif isinstance(inputs, (np.ndarray, list, tuple)): inputs_for_processing = tf.convert_to_tensor(inputs) elif not was_tf_input: inputs_for_processing = tf.convert_to_tensor( backend.convert_to_numpy(inputs) ) output = super().call(inputs_for_processing) # Handle torch backend output conversion if is_torch_backend and isinstance( inputs, (torch.Tensor, np.ndarray, list, tuple) ): numpy_outputs = output.numpy() if self.invert: return [n.decode(self.encoding) for n in numpy_outputs] else: return torch.from_numpy(numpy_outputs) # other backends if not was_tf_input: output = backend_utils.convert_tf_tensor(output) return output
StringLookup
python
kubernetes-client__python
kubernetes/client/models/v1_rolling_update_deployment.py
{ "start": 383, "end": 7017 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'max_surge': 'object', 'max_unavailable': 'object' } attribute_map = { 'max_surge': 'maxSurge', 'max_unavailable': 'maxUnavailable' } def __init__(self, max_surge=None, max_unavailable=None, local_vars_configuration=None): # noqa: E501 """V1RollingUpdateDeployment - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._max_surge = None self._max_unavailable = None self.discriminator = None if max_surge is not None: self.max_surge = max_surge if max_unavailable is not None: self.max_unavailable = max_unavailable @property def max_surge(self): """Gets the max_surge of this V1RollingUpdateDeployment. # noqa: E501 The maximum number of pods that can be scheduled above the desired number of pods. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. Defaults to 25%. Example: when this is set to 30%, the new ReplicaSet can be scaled up immediately when the rolling update starts, such that the total number of old and new pods do not exceed 130% of desired pods. Once old pods have been killed, new ReplicaSet can be scaled up further, ensuring that total number of pods running at any time during the update is at most 130% of desired pods. # noqa: E501 :return: The max_surge of this V1RollingUpdateDeployment. # noqa: E501 :rtype: object """ return self._max_surge @max_surge.setter def max_surge(self, max_surge): """Sets the max_surge of this V1RollingUpdateDeployment. The maximum number of pods that can be scheduled above the desired number of pods. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. Defaults to 25%. Example: when this is set to 30%, the new ReplicaSet can be scaled up immediately when the rolling update starts, such that the total number of old and new pods do not exceed 130% of desired pods. Once old pods have been killed, new ReplicaSet can be scaled up further, ensuring that total number of pods running at any time during the update is at most 130% of desired pods. # noqa: E501 :param max_surge: The max_surge of this V1RollingUpdateDeployment. # noqa: E501 :type: object """ self._max_surge = max_surge @property def max_unavailable(self): """Gets the max_unavailable of this V1RollingUpdateDeployment. # noqa: E501 The maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. Defaults to 25%. Example: when this is set to 30%, the old ReplicaSet can be scaled down to 70% of desired pods immediately when the rolling update starts. Once new pods are ready, old ReplicaSet can be scaled down further, followed by scaling up the new ReplicaSet, ensuring that the total number of pods available at all times during the update is at least 70% of desired pods. # noqa: E501 :return: The max_unavailable of this V1RollingUpdateDeployment. # noqa: E501 :rtype: object """ return self._max_unavailable @max_unavailable.setter def max_unavailable(self, max_unavailable): """Sets the max_unavailable of this V1RollingUpdateDeployment. The maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. Defaults to 25%. Example: when this is set to 30%, the old ReplicaSet can be scaled down to 70% of desired pods immediately when the rolling update starts. Once new pods are ready, old ReplicaSet can be scaled down further, followed by scaling up the new ReplicaSet, ensuring that the total number of pods available at all times during the update is at least 70% of desired pods. # noqa: E501 :param max_unavailable: The max_unavailable of this V1RollingUpdateDeployment. # noqa: E501 :type: object """ self._max_unavailable = max_unavailable def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1RollingUpdateDeployment): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1RollingUpdateDeployment): return True return self.to_dict() != other.to_dict()
V1RollingUpdateDeployment
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 222261, "end": 223813 }
class ____(TestCase): def test_concurrent_consumers(self): result = 0 result_lock = Lock() def producer(limit): 'Non-concurrent producer. A generator version of range(limit).' for x in range(limit): yield x def consumer(iterator): 'Concurrent data consumer' nonlocal result reconstructed = [x for x in iterator] if reconstructed == list(range(limit)): with result_lock: result += 1 limit = 10**5 num_threads = 100 non_concurrent_source = producer(limit) tees = mi.concurrent_tee(non_concurrent_source, n=num_threads) # Verify that locks are shared self.assertEqual(len({id(t_obj.lock) for t_obj in tees}), 1) # Run the consumers workers = [Thread(target=consumer, args=[t_obj]) for t_obj in tees] for worker in workers: worker.start() for worker in workers: worker.join() # Verify that every consumer received 100% of the data (no dups or drops). self.assertEqual(result, len(tees)) # Corner case non_concurrent_source = producer(limit) tees = mi.concurrent_tee(non_concurrent_source, n=0) # Zero n self.assertEqual(tees, ()) # Error cases with self.assertRaises(ValueError): non_concurrent_source = producer(limit) mi.concurrent_tee(non_concurrent_source, n=-1) # Negative n
TestConcurrentTee
python
Textualize__textual
tests/test_data_bind.py
{ "start": 252, "end": 2350 }
class ____(App): bar = reactive("Bar") def compose(self) -> ComposeResult: yield FooLabel(id="label1").data_bind(foo=DataBindApp.bar) yield FooLabel(id="label2") # Not bound async def test_data_binding(): app = DataBindApp() async with app.run_test() as pilot: # Check default assert app.bar == "Bar" label1 = app.query_one("#label1", FooLabel) label2 = app.query_one("#label2", FooLabel) # These are bound, so should have the same value as the App.foo assert label1.foo == "Bar" # Not yet bound, so should have its own default assert label2.foo == "Foo" # Changing this reactive, should also change the bound widgets app.bar = "Baz" # Sanity check assert app.bar == "Baz" # Should also have updated bound labels assert label1.foo == "Baz" assert label2.foo == "Foo" with pytest.raises(ReactiveError): # This should be an error because FooLabel.foo is not defined on the app label2.data_bind(foo=FooLabel.foo) # Bind data outside of compose label2.data_bind(foo=DataBindApp.bar) await pilot.pause() # Confirm new binding has propagated assert label2.foo == "Baz" # Set reactive and check propagation app.bar = "Egg" assert label1.foo == "Egg" assert label2.foo == "Egg" # Test nothing goes awry when removing widget with bound data await label1.remove() # Try one last time app.bar = "Spam" # Confirm remaining widgets still propagate assert label2.foo == "Spam" async def test_data_binding_missing_reactive(): class DataBindErrorApp(App): foo = reactive("Bar") def compose(self) -> ComposeResult: yield FooLabel(id="label1").data_bind( nofoo=DataBindErrorApp.foo ) # Missing reactive app = DataBindErrorApp() with pytest.raises(ReactiveError): async with app.run_test(): pass
DataBindApp
python
jmcnamara__XlsxWriter
xlsxwriter/test/worksheet/test_cond_format08.py
{ "start": 345, "end": 6871 }
class ____(unittest.TestCase): """ Test assembling a complete Worksheet file. """ def test_assemble_xml_file(self): """Test writing a worksheet with conditional formatting.""" self.maxDiff = None fh = StringIO() worksheet = Worksheet() worksheet._set_filehandle(fh) worksheet.select() worksheet.write("A1", 10) worksheet.write("A2", 20) worksheet.write("A3", 30) worksheet.write("A4", 40) worksheet.conditional_format( "A1:A4", { "type": "time_period", "criteria": "yesterday", }, ) worksheet.conditional_format( "A1:A4", { "type": "time_period", "criteria": "today", "format": None, }, ) worksheet.conditional_format( "A1:A4", { "type": "time_period", "criteria": "tomorrow", "format": None, }, ) worksheet.conditional_format( "A1:A4", { "type": "time_period", "criteria": "last 7 days", "format": None, }, ) worksheet.conditional_format( "A1:A4", { "type": "time_period", "criteria": "last week", "format": None, }, ) worksheet.conditional_format( "A1:A4", { "type": "time_period", "criteria": "this week", "format": None, }, ) worksheet.conditional_format( "A1:A4", { "type": "time_period", # Test erroneous legacy criteria. "criteria": "continue week", "format": None, }, ) worksheet.conditional_format( "A1:A4", { "type": "time_period", "criteria": "last month", "format": None, }, ) worksheet.conditional_format( "A1:A4", { "type": "time_period", "criteria": "this month", "format": None, }, ) worksheet.conditional_format( "A1:A4", { "type": "time_period", # Test erroneous legacy criteria. "criteria": "continue month", "format": None, }, ) worksheet._assemble_xml_file() exp = _xml_to_list( """ <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"> <dimension ref="A1:A4"/> <sheetViews> <sheetView tabSelected="1" workbookViewId="0"/> </sheetViews> <sheetFormatPr defaultRowHeight="15"/> <sheetData> <row r="1" spans="1:1"> <c r="A1"> <v>10</v> </c> </row> <row r="2" spans="1:1"> <c r="A2"> <v>20</v> </c> </row> <row r="3" spans="1:1"> <c r="A3"> <v>30</v> </c> </row> <row r="4" spans="1:1"> <c r="A4"> <v>40</v> </c> </row> </sheetData> <conditionalFormatting sqref="A1:A4"> <cfRule type="timePeriod" priority="1" timePeriod="yesterday"> <formula>FLOOR(A1,1)=TODAY()-1</formula> </cfRule> <cfRule type="timePeriod" priority="2" timePeriod="today"> <formula>FLOOR(A1,1)=TODAY()</formula> </cfRule> <cfRule type="timePeriod" priority="3" timePeriod="tomorrow"> <formula>FLOOR(A1,1)=TODAY()+1</formula> </cfRule> <cfRule type="timePeriod" priority="4" timePeriod="last7Days"> <formula>AND(TODAY()-FLOOR(A1,1)&lt;=6,FLOOR(A1,1)&lt;=TODAY())</formula> </cfRule> <cfRule type="timePeriod" priority="5" timePeriod="lastWeek"> <formula>AND(TODAY()-ROUNDDOWN(A1,0)&gt;=(WEEKDAY(TODAY())),TODAY()-ROUNDDOWN(A1,0)&lt;(WEEKDAY(TODAY())+7))</formula> </cfRule> <cfRule type="timePeriod" priority="6" timePeriod="thisWeek"> <formula>AND(TODAY()-ROUNDDOWN(A1,0)&lt;=WEEKDAY(TODAY())-1,ROUNDDOWN(A1,0)-TODAY()&lt;=7-WEEKDAY(TODAY()))</formula> </cfRule> <cfRule type="timePeriod" priority="7" timePeriod="nextWeek"> <formula>AND(ROUNDDOWN(A1,0)-TODAY()&gt;(7-WEEKDAY(TODAY())),ROUNDDOWN(A1,0)-TODAY()&lt;(15-WEEKDAY(TODAY())))</formula> </cfRule> <cfRule type="timePeriod" priority="8" timePeriod="lastMonth"> <formula>AND(MONTH(A1)=MONTH(TODAY())-1,OR(YEAR(A1)=YEAR(TODAY()),AND(MONTH(A1)=1,YEAR(A1)=YEAR(TODAY())-1)))</formula> </cfRule> <cfRule type="timePeriod" priority="9" timePeriod="thisMonth"> <formula>AND(MONTH(A1)=MONTH(TODAY()),YEAR(A1)=YEAR(TODAY()))</formula> </cfRule> <cfRule type="timePeriod" priority="10" timePeriod="nextMonth"> <formula>AND(MONTH(A1)=MONTH(TODAY())+1,OR(YEAR(A1)=YEAR(TODAY()),AND(MONTH(A1)=12,YEAR(A1)=YEAR(TODAY())+1)))</formula> </cfRule> </conditionalFormatting> <pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/> </worksheet> """ ) got = _xml_to_list(fh.getvalue()) self.assertEqual(exp, got)
TestAssembleWorksheet
python
huggingface__transformers
tests/pipelines/test_pipelines_question_answering.py
{ "start": 22551, "end": 28001 }
class ____(unittest.TestCase): def test_argument_handler(self): qa = QuestionAnsweringArgumentHandler() Q = "Where was HuggingFace founded ?" C = "HuggingFace was founded in Paris" normalized = qa(Q, C) self.assertEqual(type(normalized), list) self.assertEqual(len(normalized), 1) self.assertEqual({type(el) for el in normalized}, {SquadExample}) normalized = qa(question=Q, context=C) self.assertEqual(type(normalized), list) self.assertEqual(len(normalized), 1) self.assertEqual({type(el) for el in normalized}, {SquadExample}) normalized = qa(question=Q, context=C) self.assertEqual(type(normalized), list) self.assertEqual(len(normalized), 1) self.assertEqual({type(el) for el in normalized}, {SquadExample}) normalized = qa(question=[Q, Q], context=C) self.assertEqual(type(normalized), list) self.assertEqual(len(normalized), 2) self.assertEqual({type(el) for el in normalized}, {SquadExample}) normalized = qa({"question": Q, "context": C}) self.assertEqual(type(normalized), list) self.assertEqual(len(normalized), 1) self.assertEqual({type(el) for el in normalized}, {SquadExample}) normalized = qa([{"question": Q, "context": C}]) self.assertEqual(type(normalized), list) self.assertEqual(len(normalized), 1) self.assertEqual({type(el) for el in normalized}, {SquadExample}) normalized = qa([{"question": Q, "context": C}, {"question": Q, "context": C}]) self.assertEqual(type(normalized), list) self.assertEqual(len(normalized), 2) self.assertEqual({type(el) for el in normalized}, {SquadExample}) normalized = qa(X={"question": Q, "context": C}) self.assertEqual(type(normalized), list) self.assertEqual(len(normalized), 1) self.assertEqual({type(el) for el in normalized}, {SquadExample}) normalized = qa(X=[{"question": Q, "context": C}]) self.assertEqual(type(normalized), list) self.assertEqual(len(normalized), 1) self.assertEqual({type(el) for el in normalized}, {SquadExample}) normalized = qa(data={"question": Q, "context": C}) self.assertEqual(type(normalized), list) self.assertEqual(len(normalized), 1) self.assertEqual({type(el) for el in normalized}, {SquadExample}) def test_argument_handler_error_handling(self): qa = QuestionAnsweringArgumentHandler() Q = "Where was HuggingFace founded ?" C = "HuggingFace was founded in Paris" with self.assertRaises(KeyError): qa({"context": C}) with self.assertRaises(KeyError): qa({"question": Q}) with self.assertRaises(KeyError): qa([{"context": C}]) with self.assertRaises(ValueError): qa(None, C) with self.assertRaises(ValueError): qa("", C) with self.assertRaises(ValueError): qa(Q, None) with self.assertRaises(ValueError): qa(Q, "") with self.assertRaises(ValueError): qa(question=None, context=C) with self.assertRaises(ValueError): qa(question="", context=C) with self.assertRaises(ValueError): qa(question=Q, context=None) with self.assertRaises(ValueError): qa(question=Q, context="") with self.assertRaises(ValueError): qa({"question": None, "context": C}) with self.assertRaises(ValueError): qa({"question": "", "context": C}) with self.assertRaises(ValueError): qa({"question": Q, "context": None}) with self.assertRaises(ValueError): qa({"question": Q, "context": ""}) with self.assertRaises(ValueError): qa([{"question": Q, "context": C}, {"question": None, "context": C}]) with self.assertRaises(ValueError): qa([{"question": Q, "context": C}, {"question": "", "context": C}]) with self.assertRaises(ValueError): qa([{"question": Q, "context": C}, {"question": Q, "context": None}]) with self.assertRaises(ValueError): qa([{"question": Q, "context": C}, {"question": Q, "context": ""}]) with self.assertRaises(ValueError): qa(question={"This": "Is weird"}, context="This is a context") with self.assertRaises(ValueError): qa(question=[Q, Q], context=[C, C, C]) with self.assertRaises(ValueError): qa(question=[Q, Q, Q], context=[C, C]) def test_argument_handler_old_format(self): qa = QuestionAnsweringArgumentHandler() Q = "Where was HuggingFace founded ?" C = "HuggingFace was founded in Paris" # Backward compatibility for this normalized = qa(question=[Q, Q], context=[C, C]) self.assertEqual(type(normalized), list) self.assertEqual(len(normalized), 2) self.assertEqual({type(el) for el in normalized}, {SquadExample}) def test_argument_handler_error_handling_odd(self): qa = QuestionAnsweringArgumentHandler() with self.assertRaises(ValueError): qa(None) with self.assertRaises(ValueError): qa(Y=None) with self.assertRaises(ValueError): qa(1)
QuestionAnsweringArgumentHandlerTests
python
numpy__numpy
numpy/lib/tests/test_function_base.py
{ "start": 7007, "end": 7714 }
class ____: def test_basic(self): y1 = [0, 1, 1, 0] y2 = [0, 0, 0, 0] y3 = [1, 1, 1, 1] assert_(not np.all(y1)) assert_(np.all(y3)) assert_(not np.all(y2)) assert_(np.all(~np.array(y2))) def test_nd(self): y1 = [[0, 0, 1], [0, 1, 1], [1, 1, 1]] assert_(not np.all(y1)) assert_array_equal(np.all(y1, axis=0), [0, 0, 1]) assert_array_equal(np.all(y1, axis=1), [0, 0, 1]) @pytest.mark.parametrize("dtype", ["i8", "U10", "object", "datetime64[ms]"]) def test_any_and_all_result_dtype(dtype): arr = np.ones(3, dtype=dtype) assert np.any(arr).dtype == np.bool assert np.all(arr).dtype == np.bool
TestAll
python
milvus-io__pymilvus
tests/test_check.py
{ "start": 1946, "end": 2399 }
class ____: def test_check_pass_param_valid(self): a = [[i * j for i in range(20)] for j in range(20)] check_pass_param(search_data=a) a = np.float32([[1, 2, 3, 4], [1, 2, 3, 4]]) check_pass_param(search_data=a) def test_check_param_invalid(self): with pytest.raises(TypeError): a = {[i * j for i in range(20) for j in range(20)]} check_pass_param(search_data=a)
TestCheckPassParam
python
astropy__astropy
astropy/io/misc/ecsv.py
{ "start": 12482, "end": 45520 }
class ____(ECSVEngine): """ECSV reader engine using pandas.""" name = "pandas" format = "pandas.csv" def convert_np_type(self, np_type: str) -> np.dtype: # Convert the np_type to a pandas dtype will support for nullable types. import pandas as pd dtype = np.dtype(np_type) if dtype.kind in ("i", "u"): # Convert int64 to Int64, uint32 to UInt32, etc for nullable types converter = dtype.name.replace("i", "I").replace("u", "U") elif dtype.kind == "b": converter = "boolean" else: converter = np_type return pd.api.types.pandas_dtype(converter) def get_data_kwargs( self, header: ECSVHeader, null_values: list[str], ) -> dict[str, Any]: fill_values = get_null_values_per_column( header.cols, header.table_meta, null_values ) null_values = collections.defaultdict(list) converters = self.get_converters(header) for null_value, _, col_name in fill_values: null_values[col_name].append(null_value) # Pandas parser does not natively parse nan or NaN for floats, so we need # to declare this as a null value. if converters[col_name].kind == "f": for nan in ("nan", "NaN"): null_values[col_name].append(nan) kw = { "na_values": null_values, "keep_default_na": False, "comment": "#", "dtype": converters, } # Would prefer setting `"skiprows": header.n_header` above (as in the original # implementation prior to #18756) instead of "comment": "#". However there is a # bug in pandas.read_csv where skiprows does not work when the line includes a # quote character, see https://github.com/pandas-dev/pandas/issues/62739. return kw # noqa: RET504 def is_numpy_dtype(np_type: str) -> bool: # Check if the given dtype is a valid numpy dtype. try: np.dtype(np_type) except Exception: return False else: return True def get_header_lines( input_file: str | os.PathLike | io.BytesIO, encoding="utf-8", ) -> tuple[list[str], int, int, int]: """ Extract header lines from a file or file-like object. This function reads a file or file-like object and extracts lines that start with a specific header prefix ("# ") while skipping blank lines and lines starting with a comment prefix ("##"). The function stops reading at the first non-blank, non-comment line that does not match the header prefix. Parameters ---------- input_file : str | os.PathLike | io.BytesIO The input file path or file-like object to read. If a file path is provided, the function automatically handles compressed file formats that are supported by `~astropy.utils.data.get_readable_fileobj`. encoding : str, optional The encoding used to decode the file content. Default is "utf-8". Returns ------- lines : list[str] List of decoded header lines without the header prefix. idx : int Index of the last line read. n_empty : int Number of empty lines read. n_comment : int Number of comment lines read. """ header_prefix = "# ".encode(encoding) comment_prefix = "##".encode(encoding) lines = [] n_empty = 0 n_comment = 0 with get_readable_fileobj(input_file, encoding="binary") as f: for idx, line in enumerate(f): line_strip = line.strip() if line_strip.startswith(header_prefix): lines.append(line_strip[2:].decode(encoding)) elif not line_strip: n_empty += 1 elif line_strip.startswith(comment_prefix): n_comment += 1 else: # Stop iterating on first failed comment match for a non-blank line break # Need to rewind the input file if it is a file-like object if isinstance(input_file, io.BytesIO): input_file.seek(0) return lines, idx, n_empty, n_comment def get_csv_np_type_dtype_shape( datatype: str, subtype: str | None, name: str ) -> DerivedColumnProperties: """Get the csv_np_type, dtype, and shape of the column from datatype and subtype. This function implements most of the complexity of the ECSV data type handling. The ECSV standard allows for a wide variety of data types and subtypes, and we also need to handle some legacy cases and be liberal in what we accept. Parameters ---------- datatype : str The data type of the column as specified in the ECSV header. subtype : str or None The subtype of the column, if applicable. This can include additional information like array shape or JSON serialization. name : str The name of the column, used for error messages. Returns ------- CSVNpTypeDtypeShape A named tuple containing: - `csv_np_type`: Numpy type string for the CSV column data. - `dtype`: Numpy dtype in the final column data. - `shape`: Shape of the final column data as a tuple of integers. Raises ------ ValueError If the `datatype` or `subtype` is not recognized or cannot be converted to a valid numpy dtype. InconsistentTableError If the `datatype` is not in the allowed ECSV datatypes and cannot be parsed as a numpy dtype. """ from astropy.io.ascii.core import InconsistentTableError from astropy.io.ascii.ecsv import ECSV_DATATYPES, InvalidEcsvDatatypeWarning csv_np_type = "str" if datatype == "string" else datatype dtype = csv_np_type shape = () if datatype not in ECSV_DATATYPES: msg = ( f"unexpected datatype {datatype!r} of column {name!r} " f"is not in allowed ECSV datatypes {ECSV_DATATYPES}." ) # Try being liberal on input if the `csv_np_type` (derived from ECSV # `datatype`) looks like a numpy dtype. In this case, parse the column as # string and then cast as `csv_np_type`. This allows for back-compatibility # with early versions of io.ascii.ecsv that wrote and read e.g. # datatype=datetime64. if is_numpy_dtype(csv_np_type): dtype = csv_np_type csv_np_type = "str" warnings.warn(msg, InvalidEcsvDatatypeWarning) else: # No joy, this is an exception raise InconsistentTableError(msg) if subtype and csv_np_type != "str": # Note: the "column .. failed to convert" bit is odd here but it is to match # the io.ascii.ecsv behavior. raise ValueError( f"column {name!r} failed to convert: " f'datatype of column {name!r} must be "string"' ) if subtype: # Subtype can be written like "int64[2,null]" and we want to split this # out to "int64" and [2, None]. if "[" in subtype: idx = subtype.index("[") dtype = subtype[:idx] shape = tuple(json.loads(subtype[idx:])) else: dtype = subtype # Map ECSV types to numpy dtypes dtype = {"json": "object", "string": "str"}.get(dtype, dtype) # Check if the subtype corresponds to a valid numpy dtype. This is required by # the astropy implementation, but not by the ECSV standard. The standard states # that an unknown subtype can be ignored, so that is what we do here (but with # a warning). if not is_numpy_dtype(dtype): warnings.warn( f"unexpected subtype {subtype!r} set for column " f"{name!r}, using dtype={csv_np_type!r} instead.", category=InvalidEcsvDatatypeWarning, ) dtype = csv_np_type return DerivedColumnProperties(csv_np_type, dtype, shape) def read_header( input_file: str | os.PathLike | io.BytesIO, encoding: str = "utf-8", ) -> ECSVHeader: """ Read and parse the header of an ECSV (Enhanced Character Separated Values) input. This function extracts and validates the ECSV header from the given input file, parses the YAML metadata, and constructs the corresponding ECSVHeader object containing column definitions and table metadata. Parameters ---------- input_file : str, os.PathLike, or io.BytesIO The path to the ECSV file or a file-like object containing the ECSV data. encoding : str, optional The encoding to use when reading the file. Default is 'utf-8'. Returns ------- ECSVHeader An object containing header information, including the number of header lines, number of empty lines, column attributes, table metadata, and delimiter. Raises ------ InconsistentTableError If the ECSV header is missing, malformed, or the YAML metadata cannot be parsed. ValueError If the delimiter specified in the header is not supported. Notes ----- The function expects the first non-blank comment line to be the ECSV version header, and only space and comma are allowed as delimiters in the ECSV format. """ from astropy.io.ascii.core import InconsistentTableError from astropy.io.ascii.ecsv import DELIMITERS from astropy.table import meta # Extract non-blank comment (header) lines with comment character stripped header_lines, n_header, n_empty, n_comment = get_header_lines( input_file, encoding=encoding ) # Validate that this is a ECSV file ecsv_header_re = r"""%ECSV [ ] (?P<major> \d+) \. (?P<minor> \d+) \.? (?P<bugfix> \d+)? $""" no_header_msg = ( 'ECSV header line like "# %ECSV <version>" not found as first line.' " This is required for a ECSV file." ) if not header_lines: raise InconsistentTableError(no_header_msg) match = re.match(ecsv_header_re, header_lines[0].strip(), re.VERBOSE) if not match: raise InconsistentTableError(no_header_msg) try: header = meta.get_header_from_yaml(header_lines) except meta.YamlParseError as e: raise InconsistentTableError("unable to parse yaml in meta header") from e table_meta = header.get("meta", None) delimiter = header.get("delimiter", " ") if delimiter not in DELIMITERS: raise ValueError( "only space and comma are allowed for delimiter in ECSV format" ) # Create list of columns from `header`. cols_attrs = [ColumnECSV(**col) for col in header["datatype"]] return ECSVHeader(n_header, n_empty, n_comment, cols_attrs, table_meta, delimiter) def read_data( input_file: str | os.PathLike | io.BytesIO, header: ECSVHeader, null_values: list[str], encoding: str = "utf-8", engine_name: str = "io.ascii", ) -> "Table": """ Read the data from an ECSV table using the specified engine. This function uses an engine-specific class to handle reading and converting the data according to the ECSV specification and the selected backend. Parameters ---------- input_file : str, os.PathLike, or io.BytesIO The path to the input file or a file-like object containing the ECSV data. header : ECSVHeader The parsed ECSV header containing column definitions and metadata. null_values : list of str List of string values to interpret as null/missing values in the data. encoding : str, optional The encoding to use when reading the file. Default is "utf-8". engine_name: str, optional The backend engine to use for reading the data. Default is "io.ascii". Built-in options are "pyarrow", "pandas", and "io.ascii". Returns ------- Table An Astropy Table containing the data read from the ECSV file. Raises ------ InconsistentTableError If the column names from the ECSV header do not match the column names in the data. """ from astropy.table import Table engine = ECSVEngine.engines[engine_name]() # Get the engine-specific kwargs for reading the CSV data. kwargs = engine.get_data_kwargs(header, null_values) data = Table.read( input_file, format=engine.format, delimiter=header.delimiter, encoding=encoding, **kwargs, ) # Ensure ECSV header names match the data column names. ecsv_header_names = [col.name for col in header.cols] if ecsv_header_names != data.colnames: from astropy.io.ascii.core import InconsistentTableError raise InconsistentTableError( f"column names from ECSV header {ecsv_header_names} do not " f"match names from header line of CSV data {data.colnames}" ) return data def get_str_vals( data: np.ndarray | np.ma.MaskedArray, ) -> tuple[list[str] | npt.NDArray[np.str_], npt.NDArray[np.bool_] | None]: """Get the string values and the mask if available. This assumes a 1-d input array of strings, possibly masked. This array comes from reading the ECSV data, which is always a 1-d array. This function is only called if that array is a numpy string array or a masked array of strings. For a masked array it converts the data to the equivalent Python representation (list of strings) and returns the mask as a separate array. A list of strings is required in this case because the subsequent ``process_*_data`` functions substitute (in-place) a new string with the appropriate JSON for an empty/masked fill value. In particular, if the original input consists solely of empty strings (which is legal), the numpy string array will be not be wide enough to hold the fill value. For regular numpy arrays it simply returns the original data as a numpy array. Parameters ---------- data : np.ndarray | np.ma.MaskedArray The input data array to extract string values from. Returns ------- str_vals : list[str] | npt.NDArray[np.str_] A list of strings or a 1D numpy array of strings representing the data. mask : npt.NDArray[np.bool_] | None A 1D numpy array of booleans indicating the mask, or None if not applicable. """ # For masked we need a list because for multidim the data under the mask is set # to a compatible value. if hasattr(data, "mask"): # TODO: for not NUMPY_LT_2_0, try changing this to: # str_vals = data.astype("T") str_vals = data.view(np.ndarray).tolist() mask = data.mask else: str_vals = data mask = None return str_vals, mask def convert_column( col: ColumnECSV, data_in: np.ndarray | np.ma.MaskedArray, ) -> np.ndarray | np.ma.MaskedArray: """ Convert column data from original CSV numpy type to specified output numpy dtype. This function handles both regular scalar columns and more complex columns such as: - Object dtype columns containing arbitrary Python objects serializable to JSON. - Variable-length array columns, where the last axis may vary in length. - Fixed-shape multidimensional columns. Depending on the column's dtype and shape, the function selects the appropriate processing routine to convert the data, including deserialization from JSON where necessary. For regular scalar columns, it casts the data to the target dtype if needed. Parameters ---------- col : ColumnECSV The column specification, including dtype, shape, and name. data_in : np.ndarray | np.ma.MaskedArray The input data array to be converted. Returns ------- np.ndarray | np.ma.MaskedArray The converted data array with the appropriate dtype and shape. Raises ------ ValueError If the data cannot be converted due to shape mismatch or invalid JSON content. """ try: if col.dtype == "object" or col.shape: # Handle three distinct column types where each row element is serialized to # JSON. In this case ``data_in`` is an ndarray or MaskedArray of # fixed-length string which are the JSON-encoded representation of the data. # See docstring in `get_str_vals` for explanation of the next step, which # has some subtlety. str_vals, mask = get_str_vals(data_in) if col.dtype == "object": # Any Python objects serializable to JSON process_func = process_object_data elif col.shape[-1] is None: # Variable length arrays with shape (n, m, ..., *) for fixed # n, m, .. and variable in last axis. process_func = process_variable_length_array_data else: # Multidim columns with consistent shape (n, m, ...). process_func = process_fixed_shape_multidim_data data_out, col_shape = process_func(col, str_vals, mask) # Regular scalar value column else: data_out = data_in # If we need to cast the data to a different dtype, do it now. if data_out.dtype != col.dtype: data_out = data_out.astype(col.dtype) col_shape = col.shape if data_out.shape[1:] != tuple(col_shape): raise ValueError("shape mismatch between value and column specifier") except json.JSONDecodeError: raise ValueError( f"column {col.name!r} failed to convert: column value is not valid JSON" ) except Exception as exc: raise ValueError(f"column {col.name!r} failed to convert: {exc}") from exc return data_out def process_object_data( col: ColumnECSV, str_vals: list[str] | npt.NDArray[np.str_], mask: npt.NDArray[np.bool_] | None, ) -> tuple[np.ndarray | np.ma.MaskedArray, tuple[int, ...]]: """ Handle object columns where each row element is a JSON-encoded object. The ECSV format only allows a 1-d column of object type. Example:: # %ECSV 1.0 # --- # datatype: # - {name: objects, datatype: string, subtype: json} # schema: astropy-2.0 objects "{""a"":1}" "{""b"":[2.5,null]}" true Parameters ---------- col : ColumnECSV The column specification, including dtype, shape, and name. str_vals : list[str] or 1-D ndarray[str] JSON-encoded string representations of the data. mask : 1-D ndarray[bool] or None Boolean mask array 1-D indicating invalid or missing values. If None, no masking is applied. Returns ------- data_out : numpy.ndarray or numpy.ma.MaskedArray An array of objects reconstructed from `str_vals`, with the same shape as `col`. If `mask` is provided, a masked array is returned with the mask applied. col_shape : tuple[int, ...] Expected shape of data_out, used in final sanity check of reading. """ if mask is not None: for idx in np.nonzero(mask)[0]: str_vals[idx] = "0" # could be "null" but io.ascii uses "0" col_vals = [json.loads(val) for val in str_vals] np_empty = np.empty if mask is None else np.ma.empty data_out = np_empty((len(col_vals),) + tuple(col.shape), dtype=object) data_out[...] = col_vals if mask is not None: data_out.mask = mask return data_out, col.shape def process_fixed_shape_multidim_data( col: ColumnECSV, str_vals: list[str] | npt.NDArray[np.str_], mask: npt.NDArray[np.bool_] | None, ) -> tuple[np.ndarray | np.ma.MaskedArray, tuple[int, ...]]: """ Handle fixed-shape multidimensional columns as JSON-encoded strings. Example:: # %ECSV 1.0 # --- # datatype: # - {name: array3x2, datatype: string, subtype: 'float64[3,2]'} # schema: astropy-2.0 array3x2 [[0.0,1.0],[2.0,3.0],[4.0,5.0]] [[6.0,7.0],[8.0,null],[10.0,11.0]] Parameters ---------- col : ColumnECSV The column specification, including dtype, shape, and name. str_vals : array-like of str Array of string representations of the data, typically JSON-encoded. mask : numpy.ndarray or None Boolean mask array indicating invalid or missing values. If None, no masking is applied. Returns ------- data_out : numpy.ndarray or numpy.ma.MaskedArray An array of objects reconstructed from `str_vals`, with the same shape as `col`. If `mask` is provided, a masked array is returned with the mask applied. col_shape : tuple[int, ...] Expected shape of data_out, used in final sanity check of reading. """ # Change empty (blank) values in original ECSV to something # like "[[null, null],[null,null]]" so subsequent JSON # decoding works. if mask is not None: all_none_arr = np.full(shape=col.shape, fill_value=None, dtype=object) fill_value = json.dumps(all_none_arr.tolist()) for idx in np.nonzero(mask)[0]: str_vals[idx] = fill_value col_vals = [json.loads(val) for val in str_vals] # Make a numpy object array of col_vals to look for None (masked values) arr_vals = np.array(col_vals, dtype=object) arr_vals_mask = arr_vals == None if np.any(arr_vals_mask): # Replace all the None with an appropriate fill value arr_vals[arr_vals_mask] = {"U": "", "S": b""}.get(col.dtype.kind, 0) # Finally make a MaskedArray with the filled data + mask data_out = np.ma.array(arr_vals.astype(col.dtype), mask=arr_vals_mask) else: data_out = arr_vals.astype(col.dtype) return data_out, col.shape def process_variable_length_array_data( col: ColumnECSV, str_vals: list[str] | npt.NDArray[np.str_], mask: npt.NDArray[np.bool_] | None, ) -> tuple[np.ndarray | np.ma.MaskedArray, tuple[int, ...]]: """ Handle variable length arrays with shape (n, m, ..., *) as JSON-encoded strings. Shape is fixed for n, m, .. and variable in last axis. The output is a 1-d object array with each row element being an ``np.ndarray`` or ``np.ma.masked_array`` of the appropriate shape. Example:: # %ECSV 1.0 # --- # datatype: # - {name: array_var, datatype: string, subtype: 'int64[null]'} # schema: astropy-2.0 array_var [1,2] [3,4,5,null,7] [8,9,10] Parameters ---------- col : ColumnECSV The column specification, including dtype, shape, and name. str_vals : list[str] or 1-D ndarray[str] JSON-encoded string representations of the data. mask : 1-D ndarray[bool] or None Boolean mask array 1-D indicating invalid or missing values. If None, no masking is applied. Returns ------- data_out : numpy.ndarray or numpy.ma.MaskedArray An array of objects reconstructed from `str_vals`, with the same shape as `col`. If `mask` is provided, a masked array is returned with the mask applied. col_shape : tuple[int, ...] Expected shape of data_out, used in final sanity check of reading. """ # Empty (blank) values in original ECSV are masked. Instead set the values # to "[]" indicating an empty list. This operation also unmasks the values. if mask is not None: fill_value = "[]" for idx in np.nonzero(mask)[0]: str_vals[idx] = fill_value # Remake as a 1-d object column of numpy ndarrays or # MaskedArray using the datatype specified in the ECSV file. col_vals = [] for str_val in str_vals: obj_val = json.loads(str_val) # list or nested lists try: arr_val = np.array(obj_val, dtype=col.dtype) except TypeError: # obj_val has entries that are inconsistent with # dtype. For a valid ECSV file the only possibility # is None values (indicating missing values). vals = np.array(obj_val, dtype=object) # Replace all the None with an appropriate fill value mask_vals = vals == None vals[mask_vals] = {"U": "", "S": b""}.get(col.dtype.kind, 0) arr_val = np.ma.array(vals.astype(col.dtype), mask=mask_vals) col_vals.append(arr_val) np_empty = np.empty if mask is None else np.ma.empty data_out = np_empty(len(col_vals), dtype=object) data_out[:] = col_vals if mask is not None: data_out.mask = mask return data_out, () def get_null_values_per_column( cols: list[ColumnECSV], table_meta: dict | None, null_values: list[str], ) -> list[tuple[str, str, str]]: """Get null and fill values for individual columns. For ECSV to handle the corner case of data that has been serialized using the serialize_method='data_mask' option, which writes the full data and mask directly, AND where that table includes a string column with zero-length string entries ("") which are valid data. Normally the super() method will set col.fill_value=('', '0') to replace blanks with a '0'. But for that corner case subset, instead do not do any filling. Parameters ---------- cols : list[ColumnECSV] List of ColumnECSV objects representing the columns in the ECSV file. table_meta : dict or None Metadata dictionary from the ECSV header, which may include serialized columns and other metadata. null_values : list[str] List of string values to interpret as null/missing values in every column. The upstream default from ``read_ecsv`` is [""] but no default is defined here. Returns ------- fill_values : list[tuple[str, str, str]] A list of tuples with (null_value, fill_value, column_name) for each column in `cols` that is not a MaskedColumn. If no fill values are needed, returns an empty list. """ if table_meta is None: table_meta = {} # Get the serialized columns spec or an empty dict if not present. serialized_columns: dict[str, SerializedColumn] = table_meta.get( "__serialized_columns__", {} ) # A serialized MaskedColumn column (via `serialize_method="data_mask"`) does not # have a fill value, so assemble a set of columns names to skip include the data and # the mask columns. For example: # - __serialized_columns__: # a: # __class__: astropy.table.column.MaskedColumn # data: !astropy.table.SerializedColumn {name: a} # mask: !astropy.table.SerializedColumn {name: a.mask} masked_col_names = set() for name, sc in serialized_columns.items(): if sc["__class__"] == "astropy.table.column.MaskedColumn": masked_col_names.add(name) masked_col_names.add(name + ".mask") fill_values = [] for col in cols: if col.name in masked_col_names: continue fill_value = "" if col.csv_np_type == "str" else "0" for null_value in null_values: fill_values.append((null_value, fill_value, col.name)) return fill_values def read_ecsv( input_file: str | os.PathLike | io.BytesIO | io.StringIO | Iterable[str], *, encoding: str = "utf-8", engine: str = "io.ascii", null_values: list[str] | None = None, ) -> "Table": """ Read an ECSV (Enhanced Character Separated Values) file and return an Astropy Table. Parameters ---------- input_file : str, os.PathLike, io.BytesIO, io.StringIO, Iterable[str] The ECSV input to read. This can be a file path, a file-like object, a string containing the file contents, or an iterable of strings representing lines of the file. Note that providing ``io.StringIO`` or an iterable of strings will be less memory efficient, as it will be converted to a bytes stream. encoding : str, optional The encoding to use when reading the file. Default is "utf-8". engine : str, optional The engine to use for reading the CSV data. Default is "io.ascii", which uses astropy to read the CSV data. Other built-in options are "pyarrow" and "pandas". The "pyarrow" engine is optimized for performance and can handle large datasets efficiently. The "pandas" engine uses the pandas CSV reader, which is also faster than the default "io.ascii" engine. null_values : list of str or None, optional List of string values to interpret as null/missing values. Default is [""]. The ECSV standard requires the null values are represented as empty strings in the CSV data, but this allows reading non-compliant ECSV files. A notable example are the Gaia source download files which are ECSV but use "null". Returns ------- table : astropy.table.Table The table read from the ECSV file. Raises ------ astropy.io.ascii.core.InconsistentTableError If the column names in the ECSV header do not match the column names in the CSV data. Notes ----- - The function handles various input types, including file paths, file-like objects, and in-memory strings or lists of strings. - Metadata and column attributes (such as unit, description, format, and meta) are transferred from the ECSV header to the resulting Table object. - Handles JSON-encoded data and ensures appropriate numpy dtypes for columns. """ from astropy.table import Table, serialize if null_values is None: null_values = [""] # Allow input types that are historically supported by io.ascii. These will not be # memory or speed efficient but will still work. if isinstance(input_file, io.StringIO): input_file = io.BytesIO(input_file.getvalue().encode(encoding)) elif isinstance(input_file, str) and "\n" in input_file: input_file = io.BytesIO(input_file.encode(encoding)) elif isinstance(input_file, (list, tuple)): # TODO: better way to check for an iterable of str? input_file = io.BytesIO("\n".join(input_file).encode(encoding)) # Read the ECSV header from the input. header = read_header(input_file, encoding=encoding) # Read the CSV data from the input starting at the line after the header. This # includes handling that is particular to the engine. data_raw = read_data( input_file, header, null_values=null_values, encoding=encoding, engine_name=engine, ) # Convert the column data to the appropriate numpy dtype. This is mostly concerned # with JSON-encoded data but also handles cases like pyarrow not supporting float16. data = {col.name: convert_column(col, data_raw[col.name]) for col in header.cols} # Create the Table object table = Table(data) # Transfer metadata from the ECSV header to the Table columns. for header_col in header.cols: col = table[header_col.name] for attr in ["unit", "description", "format", "meta"]: if (val := getattr(header_col, attr)) is not None: setattr(col.info, attr, val) # Add metadata to the table if header.table_meta: table.meta.update(header.table_meta) # Construct any mixin columns from the raw columns. table = serialize._construct_mixins_from_columns(table) return table # noqa: RET504 def write_ecsv(tbl, output, engine="io.ascii", **kwargs): """Thin wrapper around the ``io.ascii`` ECSV writer to write ECSV files. Parameters ---------- tbl : astropy.table.Table The table to write to ECSV format. output : str or os.PathLike or file-like object The output file path or file-like object to write the ECSV data to. engine : str, optional The engine to use for writing the CSV data. Default is "io.ascii", which uses astropy to write the CSV data. Currently this is the only option. **kwargs : dict, optional Additional keyword arguments passed to the ECSV writer. These can include options like ``delimiter``, ``encoding``, and others supported by the `astropy.io.ascii.Ecsv` writer. """ if engine != "io.ascii": raise ValueError( f"{engine=} is not a supported engine for writing, use 'io.ascii'" ) tbl.write(output, format="ascii.ecsv", **kwargs) def register_ecsv_table(): """ Register ECSV reader and writer with Unified I/O as a Table reader. """ from astropy.io import registry as io_registry from astropy.table import Table io_registry.register_reader("ecsv", Table, read_ecsv) io_registry.register_writer("ecsv", Table, write_ecsv)
ECSVEnginePandas
python
Lightning-AI__lightning
src/lightning/pytorch/strategies/xla.py
{ "start": 1816, "end": 13236 }
class ____(DDPStrategy): """Strategy for training multiple TPU devices using the :func:`torch_xla.distributed.xla_multiprocessing.spawn` method.""" strategy_name = "xla" def __init__( self, accelerator: Optional["pl.accelerators.Accelerator"] = None, parallel_devices: Optional[list[torch.device]] = None, checkpoint_io: Optional[Union[XLACheckpointIO, _WrappingCheckpointIO]] = None, precision_plugin: Optional[XLAPrecision] = None, debug: bool = False, sync_module_states: bool = True, **_: Any, ) -> None: if not _XLA_AVAILABLE: raise ModuleNotFoundError(str(_XLA_AVAILABLE)) super().__init__( accelerator=accelerator, parallel_devices=parallel_devices, cluster_environment=XLAEnvironment(), checkpoint_io=checkpoint_io, precision_plugin=precision_plugin, start_method="fork", ) self.debug = debug self._launched = False self._sync_module_states = sync_module_states @property @override def checkpoint_io(self) -> Union[XLACheckpointIO, _WrappingCheckpointIO]: plugin = self._checkpoint_io if plugin is not None: assert isinstance(plugin, (XLACheckpointIO, _WrappingCheckpointIO)) return plugin return XLACheckpointIO() @checkpoint_io.setter @override def checkpoint_io(self, io: Optional[CheckpointIO]) -> None: if io is not None and not isinstance(io, (XLACheckpointIO, _WrappingCheckpointIO)): raise TypeError(f"The XLA strategy can only work with the `XLACheckpointIO` plugin, found {io}") self._checkpoint_io = io @property @override def precision_plugin(self) -> XLAPrecision: plugin = self._precision_plugin if plugin is not None: assert isinstance(plugin, XLAPrecision) return plugin return XLAPrecision() @precision_plugin.setter @override def precision_plugin(self, precision_plugin: Optional[Precision]) -> None: if precision_plugin is not None and not isinstance(precision_plugin, XLAPrecision): raise TypeError(f"The XLA strategy can only work with the `XLAPrecision` plugin, found {precision_plugin}") self._precision_plugin = precision_plugin @property @override def root_device(self) -> torch.device: if not self._launched: raise RuntimeError("Accessing the XLA device before processes have spawned is not allowed.") import torch_xla.core.xla_model as xm return xm.xla_device() @property @override def global_rank(self) -> int: return super().global_rank if self._launched else 0 @property @override def local_rank(self) -> int: return super().local_rank if self._launched else 0 @property @override def node_rank(self) -> int: return super().node_rank if self._launched else 0 @property @override def world_size(self) -> int: return super().world_size if self._launched else 1 @override def _configure_launcher(self) -> None: self._launcher = _XLALauncher(self) @override def setup(self, trainer: "pl.Trainer") -> None: assert self.accelerator is not None self.accelerator.setup(trainer) if self.debug: os.environ["PT_XLA_DEBUG"] = "1" assert self.model is not None self.precision_plugin.convert_module(self.model) shared_params = find_shared_parameters(self.model) self.model_to_device() set_shared_parameters(self.model, shared_params) self.model = self._setup_model(self.model) if self._sync_module_states: if _XLA_GREATER_EQUAL_2_1: from torch_xla.core.xla_model import broadcast_master_param else: from torch_xla.experimental.pjrt import broadcast_master_param broadcast_master_param(self.model) if trainer.state.fn == TrainerFn.FITTING: self.setup_optimizers(trainer) self.setup_precision_plugin() if trainer.state.fn == TrainerFn.FITTING: _optimizers_to_device(self.optimizers, self.root_device) @override def _setup_model(self, model: Module) -> Module: # type: ignore return model @property @override def distributed_sampler_kwargs(self) -> dict[str, int]: return {"num_replicas": self.world_size, "rank": self.global_rank} @override def process_dataloader(self, dataloader: object) -> "MpDeviceLoader": from torch_xla.distributed.parallel_loader import MpDeviceLoader if isinstance(dataloader, MpDeviceLoader): # dataloader is already wrapped by MpDeviceLoader return dataloader dataloader = MpDeviceLoader(dataloader, self.root_device) # Mimic interface to torch.utils.data.DataLoader dataloader.dataset = dataloader._loader.dataset dataloader.batch_sampler = getattr(dataloader._loader, "batch_sampler", None) return dataloader @override def configure_ddp(self) -> None: pass @override def model_to_device(self) -> None: assert self.model is not None self.model = self.model.to(self.root_device) @override def barrier(self, name: Optional[str] = None, *args: Any, **kwargs: Any) -> None: if not self._launched: return import torch_xla.core.xla_model as xm if name is None: # `None` is not supported: "TypeError: _xla_rendezvous(): incompatible function arguments" name = "" xm.rendezvous(name) @override def broadcast(self, obj: TBroadcast, src: int = 0) -> TBroadcast: if not self._launched: return obj import torch_xla.core.xla_model as xm is_tensor = isinstance(obj, Tensor) if is_tensor: if obj.dim() == 0: obj = obj.unsqueeze(0) original_device = obj.device # XLA distributed requires that the data is on the XLA device obj = obj.to(self.root_device) else: # support for arbitrary pickle-ables buffer = io.BytesIO() torch.save(obj, buffer) obj = torch.tensor( # type: ignore[assignment] bytearray(buffer.getbuffer()), device=self.root_device, dtype=torch.float ) obj = [obj] xm.collective_broadcast(obj, root_ordinal=src) obj = obj[0] if not is_tensor: # this will preserve the dtype and device of any tensors buffer = io.BytesIO(obj.cpu().byte().numpy()) obj = torch.load(buffer) else: obj = obj.to(original_device) return obj @override def reduce( self, output: Union[Tensor, Any], group: Optional[Any] = None, reduce_op: Optional[Union[ReduceOp, str]] = "mean", ) -> Tensor: if not isinstance(output, Tensor): output = torch.tensor(output, device=self.root_device) invalid_reduce_op = isinstance(reduce_op, ReduceOp) and reduce_op != ReduceOp.SUM invalid_reduce_op_str = isinstance(reduce_op, str) and reduce_op.lower() not in ("sum", "mean", "avg") if invalid_reduce_op or invalid_reduce_op_str: raise ValueError( "Currently, the XLAStrategy only supports `sum`, `mean`, `avg` for the reduce operation, got:" f" {reduce_op}" ) import torch_xla.core.xla_model as xm output = xm.mesh_reduce("reduce", output, sum) if isinstance(reduce_op, str) and reduce_op.lower() in ("avg", "mean"): output = output / self.world_size return output @override def setup_environment(self) -> None: self._launched = True super().setup_environment() @override def setup_distributed(self) -> None: assert self.parallel_devices is not None if len(self.parallel_devices) == 1: # spawning only 1 device with PjRT is not supported: # https://github.com/Lightning-AI/pytorch-lightning/pull/17408#discussion_r1170671732 raise NotImplementedError( "The `XLAStrategy` does not support running on a single device with the PjRT runtime." " Try using all devices or the `SingleDeviceXLAStrategy` strategy" ) rank_zero_only.rank = self.global_rank @override def set_world_ranks(self) -> None: # accessing global_rank will initialize the XLA computation client. since this is called outside of the spawned # processes (by the accelerator connector), we cannot run the code that would normally be here. # instead it's done in `setup_distributed` pass @override def save_checkpoint( self, checkpoint: dict[str, Any], filepath: _PATH, storage_options: Optional[Any] = None ) -> None: import torch_xla.core.xla_model as xm # sync any pending lazy tensors on all ranks before saving to prevent potential collective hangs xm.mark_step() # save on global rank zero only super().save_checkpoint(checkpoint, filepath, storage_options=storage_options) @override def remove_checkpoint(self, filepath: _PATH) -> None: """Remove checkpoint filepath from the filesystem. Args: filepath: Path to checkpoint """ if self.local_rank == 0: self.checkpoint_io.remove_checkpoint(filepath) @override def all_gather(self, tensor: Tensor, group: Optional[Any] = None, sync_grads: bool = False) -> Tensor: """Function to gather a tensor from several distributed processes. Args: tensor: tensor to all-gather. group: unused. sync_grads: flag that allows users to synchronize gradients for the all-gather operation. Return: A tensor of shape (world_size, ...) """ if not self._launched: return tensor if not isinstance(tensor, Tensor): raise NotImplementedError( f"`{type(self).__name__}.all_gather` is only implemented for tensors. Given {tensor}" ) if tensor.dim() == 0: tensor = tensor.unsqueeze(0) original_device = tensor.device tensor = tensor.to(self.root_device) import torch_xla.core.functions as xf import torch_xla.core.xla_model as xm tensor = xf.all_gather(tensor) if sync_grads else xm.all_gather(tensor) tensor = tensor.to(original_device) return tensor @override def teardown(self) -> None: super().teardown() self._launched = False # after the Trainer finishes, we aren't inside the spawned region os.environ.pop("PT_XLA_DEBUG", None) @classmethod @override def register_strategies(cls, strategy_registry: _StrategyRegistry) -> None: strategy_registry.register("xla_debug", cls, description="XLA strategy with `debug` as True", debug=True) strategy_registry.register( cls.strategy_name, cls, description=cls.__name__, )
XLAStrategy
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-openvino-genai/llama_index/llms/openvino_genai/base.py
{ "start": 911, "end": 14237 }
class ____(CustomLLM): r""" OpenVINO GenAI LLM. Examples: `pip install llama-index-llms-openvino-genai` ```python from llama_index.llms.openvino_genai import OpenVINOgenAILLM llm = OpenVINOGenAILLM( model_path=model_path, device="CPU", ) response = llm.complete("What is the meaning of life?") print(str(response)) ``` """ model_path: str = Field( default=None, description=("The model path to use from local. "), ) system_prompt: str = Field( default="", description=( "The system prompt, containing any extra instructions or context. " "The model card on HuggingFace should specify if this is needed." ), ) query_wrapper_prompt: PromptTemplate = Field( default=PromptTemplate("{query_str}"), description=( "The query wrapper prompt, containing the query placeholder. " "The model card on HuggingFace should specify if this is needed. " "Should contain a `{query_str}` placeholder." ), ) device: str = Field( default="auto", description="The device to use. Defaults to 'auto'." ) is_chat_model: bool = Field( default=False, description=( LLMMetadata.model_fields["is_chat_model"].description + " Be sure to verify that you either pass an appropriate tokenizer " "that can convert prompts to properly formatted chat messages or a " "`messages_to_prompt` that does so." ), ) config: str = Field( default=None, description=("The LLM generation configurations."), ) _pip: Any = PrivateAttr() _tokenizer: Any = PrivateAttr() _streamer: Any = PrivateAttr() def __init__( self, model_path: str, config: Optional[dict] = {}, tokenizer: Optional[Any] = None, device: Optional[str] = "CPU", query_wrapper_prompt: Union[str, PromptTemplate] = "{query_str}", is_chat_model: Optional[bool] = False, callback_manager: Optional[CallbackManager] = None, system_prompt: str = "", messages_to_prompt: Optional[Callable[[Sequence[ChatMessage]], str]] = None, completion_to_prompt: Optional[Callable[[str], str]] = None, **kwargs: Any, ) -> None: class IterableStreamer(openvino_genai.StreamerBase): """ A custom streamer class for handling token streaming and detokenization with buffering. Attributes: tokenizer (Tokenizer): The tokenizer used for encoding and decoding tokens. tokens_cache (list): A buffer to accumulate tokens for detokenization. text_queue (Queue): A synchronized queue for storing decoded text chunks. print_len (int): The length of the printed text to manage incremental decoding. """ def __init__(self, tokenizer: Any) -> None: """ Initializes the IterableStreamer with the given tokenizer. Args: tokenizer (Tokenizer): The tokenizer to use for encoding and decoding tokens. """ super().__init__() self.tokenizer = tokenizer self.tokens_cache: list[int] = [] self.text_queue: Any = queue.Queue() self.print_len = 0 def __iter__(self) -> self: """ Returns the iterator object itself. """ return self def __next__(self) -> str: """ Returns the next value from the text queue. Returns: str: The next decoded text chunk. Raises: StopIteration: If there are no more elements in the queue. """ value = ( self.text_queue.get() ) # get() will be blocked until a token is available. if value is None: raise StopIteration return value def get_stop_flag(self) -> bool: """ Checks whether the generation process should be stopped. Returns: bool: Always returns False in this implementation. """ return False def put_word(self, word: Any) -> None: """ Puts a word into the text queue. Args: word (str): The word to put into the queue. """ self.text_queue.put(word) def put(self, token_id: int) -> bool: """ Processes a token and manages the decoding buffer. Adds decoded text to the queue. Args: token_id (int): The token_id to process. Returns: bool: True if generation should be stopped, False otherwise. """ self.tokens_cache.append(token_id) text = self.tokenizer.decode( self.tokens_cache, skip_special_tokens=True ) word = "" if len(text) > self.print_len and text[-1] == "\n": word = text[self.print_len :] self.tokens_cache = [] self.print_len = 0 elif len(text) >= 3 and text[-3:] == chr(65533): pass elif len(text) > self.print_len: word = text[self.print_len :] self.print_len = len(text) self.put_word(word) if self.get_stop_flag(): self.end() return True else: return False def end(self) -> None: """ Flushes residual tokens from the buffer and puts a None value in the queue to signal the end. """ text = self.tokenizer.decode( self.tokens_cache, skip_special_tokens=True ) if len(text) > self.print_len: word = text[self.print_len :] self.put_word(word) self.tokens_cache = [] self.print_len = 0 self.put_word(None) def reset(self) -> None: """ Resets the state. """ self.tokens_cache = [] self.text_queue = queue.Queue() self.print_len = 0 class ChunkStreamer(IterableStreamer): def __init__(self, tokenizer: Any, tokens_len: int = 4) -> None: super().__init__(tokenizer) self.tokens_len = tokens_len def put(self, token_id: int) -> bool: if (len(self.tokens_cache) + 1) % self.tokens_len != 0: self.tokens_cache.append(token_id) return False return super().put(token_id) """Initialize params.""" pipe = openvino_genai.LLMPipeline(model_path, device, config, **kwargs) config = pipe.get_generation_config() tokenizer = tokenizer or pipe.get_tokenizer() streamer = ChunkStreamer(tokenizer) if isinstance(query_wrapper_prompt, str): query_wrapper_prompt = PromptTemplate(query_wrapper_prompt) messages_to_prompt = messages_to_prompt or self._tokenizer_messages_to_prompt super().__init__( tokenizer=tokenizer, model_path=model_path, device=device, query_wrapper_prompt=query_wrapper_prompt, is_chat_model=is_chat_model, callback_manager=callback_manager, system_prompt=system_prompt, messages_to_prompt=messages_to_prompt, completion_to_prompt=completion_to_prompt, ) self._pipe = pipe self._tokenizer = tokenizer self._streamer = streamer self.config = config @classmethod def class_name(cls) -> str: return "OpenVINO_GenAI_LLM" @property def metadata(self) -> LLMMetadata: """LLM metadata.""" return LLMMetadata( model_name=self.model_path, is_chat_model=self.is_chat_model, ) def _tokenizer_messages_to_prompt(self, messages: Sequence[ChatMessage]) -> str: """Use the tokenizer to convert messages to prompt. Fallback to generic.""" if hasattr(self._tokenizer, "apply_chat_template"): messages_dict = [ {"role": message.role.value, "content": message.content} for message in messages ] return ( self._tokenizer.apply_chat_template( messages_dict, add_generation_prompt=True ) if isinstance(self._tokenizer, openvino_genai.Tokenizer) else self._tokenizer.apply_chat_template( messages_dict, tokenize=False, add_generation_prompt=True ) ) return generic_messages_to_prompt(messages) @llm_completion_callback() def complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponse: """Completion endpoint.""" full_prompt = prompt if not formatted: if self.query_wrapper_prompt: full_prompt = self.query_wrapper_prompt.format(query_str=prompt) if self.completion_to_prompt: full_prompt = self.completion_to_prompt(full_prompt) elif self.system_prompt: full_prompt = f"{self.system_prompt} {full_prompt}" if not isinstance(self._tokenizer, openvino_genai.Tokenizer): inputs = self._tokenizer( full_prompt, add_special_tokens=False, return_tensors="np" ) input_ids = inputs["input_ids"] attention_mask = inputs["attention_mask"] full_prompt = openvino_genai.TokenizedInputs( ov.Tensor(input_ids), ov.Tensor(attention_mask) ) tokens = self._pipe.generate(full_prompt, self.config, **kwargs) if not isinstance(self._tokenizer, openvino_genai.Tokenizer): completion_tokens = tokens[0][inputs["input_ids"].size(1) :] completion = self._tokenizer.decode( completion_tokens, skip_special_tokens=True ) else: completion = tokens return CompletionResponse(text=completion, raw={"model_output": tokens}) @llm_completion_callback() def stream_complete( self, prompt: str, formatted: bool = False, **kwargs: Any ) -> CompletionResponseGen: """Streaming completion endpoint.""" full_prompt = prompt if not formatted: if self.query_wrapper_prompt: full_prompt = self.query_wrapper_prompt.format(query_str=prompt) if self.system_prompt: full_prompt = f"{self.system_prompt} {full_prompt}" if not isinstance(self._tokenizer, openvino_genai.Tokenizer): inputs = self._tokenizer( full_prompt, add_special_tokens=False, return_tensors="np" ) input_ids = inputs["input_ids"] attention_mask = inputs["attention_mask"] full_prompt = openvino_genai.TokenizedInputs( ov.Tensor(input_ids), ov.Tensor(attention_mask) ) stream_complete = Event() def generate_and_signal_complete() -> None: """ Generation function for single thread. """ self._streamer.reset() self._pipe.generate(full_prompt, self.config, self._streamer, **kwargs) stream_complete.set() self._streamer.end() t1 = Thread(target=generate_and_signal_complete) t1.start() # create generator based off of streamer def gen() -> CompletionResponseGen: text = "" for x in self._streamer: text += x yield CompletionResponse(text=text, delta=x) return gen() @llm_chat_callback() def chat(self, messages: Sequence[ChatMessage], **kwargs: Any) -> ChatResponse: prompt = self.messages_to_prompt(messages) completion_response = self.complete(prompt, formatted=True, **kwargs) return completion_response_to_chat_response(completion_response) @llm_chat_callback() def stream_chat( self, messages: Sequence[ChatMessage], **kwargs: Any ) -> ChatResponseGen: prompt = self.messages_to_prompt(messages) completion_response = self.stream_complete(prompt, formatted=True, **kwargs) return stream_completion_response_to_chat_response(completion_response)
OpenVINOGenAILLM
python
pyqtgraph__pyqtgraph
pyqtgraph/examples/customPlot.py
{ "start": 852, "end": 2969 }
class ____(pg.TickSliderItem): def __init__(self, *args, **kwds): pg.TickSliderItem.__init__(self, *args, **kwds) self.all_ticks = {} self._range = [0,1] def setTicks(self, ticks): for tick, pos in self.listTicks(): self.removeTick(tick) for pos in ticks: tickItem = self.addTick(pos, movable=False, color="#333333") self.all_ticks[pos] = tickItem self.updateRange(None, self._range) def updateRange(self, vb, viewRange): origin = self.tickSize/2. length = self.length lengthIncludingPadding = length + self.tickSize + 2 self._range = viewRange for pos in self.all_ticks: tickValueIncludingPadding = (pos - viewRange[0]) / (viewRange[1] - viewRange[0]) tickValue = (tickValueIncludingPadding*lengthIncludingPadding - origin) / length # Convert from np.bool_ to bool for setVisible visible = bool(tickValue >= 0 and tickValue <= 1) tick = self.all_ticks[pos] tick.setVisible(visible) if visible: self.setTickValue(tick, tickValue) app = pg.mkQApp() axis = pg.DateAxisItem(orientation='bottom') vb = CustomViewBox() pw = pg.PlotWidget(viewBox=vb, axisItems={'bottom': axis}, enableMenu=False, title="PlotItem with DateAxisItem, custom ViewBox and markers on x axis<br>Menu disabled, mouse behavior changed: left-drag to zoom, right-click to reset zoom") dates = np.arange(8) * (3600*24*356) pw.plot(x=dates, y=[1,6,2,4,3,5,6,8], symbol='o') # Using allowAdd and allowRemove to limit user interaction tickViewer = CustomTickSliderItem(allowAdd=False, allowRemove=False) vb.sigXRangeChanged.connect(tickViewer.updateRange) pw.plotItem.layout.addItem(tickViewer, 4, 1) tickViewer.setTicks( [dates[0], dates[2], dates[-1]] ) pw.show() pw.setWindowTitle('pyqtgraph example: customPlot') r = pg.PolyLineROI([(0,0), (10, 10)]) pw.addItem(r) if __name__ == '__main__': pg.exec()
CustomTickSliderItem
python
keras-team__keras
keras/src/layers/core/einsum_dense_test.py
{ "start": 473, "end": 42804 }
class ____(testing.TestCase): @parameterized.named_parameters( { "testcase_name": "_1d_end_weight", "equation": "ab,b->a", "bias_axes": None, "input_shape": (2, 32), "output_shape": (), "expected_kernel_shape": (32,), "expected_bias_shape": None, "expected_output_shape": (2,), }, { "testcase_name": "_2d_middle_weight", "equation": "ab,bc->ac", "bias_axes": None, "input_shape": (2, 32), "output_shape": (64), "expected_kernel_shape": (32, 64), "expected_bias_shape": None, "expected_output_shape": (2, 64), }, { "testcase_name": "_3d_bert", "equation": "abc,cde->abde", "bias_axes": None, "input_shape": (2, 1, 2), "output_shape": (1, 3, 4), "expected_kernel_shape": (2, 3, 4), "expected_bias_shape": None, "expected_output_shape": (2, 1, 3, 4), }, { "testcase_name": "_3d_3_bias", "equation": "abc,cde->abde", "bias_axes": "e", "input_shape": (2, 1, 2), "output_shape": (1, 3, 4), "expected_kernel_shape": (2, 3, 4), "expected_bias_shape": (4,), "expected_output_shape": (2, 1, 3, 4), }, { "testcase_name": "_3d_2_bias", "equation": "abc,cde->abde", "bias_axes": "d", "input_shape": (2, 1, 2), "output_shape": (1, 3, 4), "expected_kernel_shape": (2, 3, 4), "expected_bias_shape": (3, 1), "expected_output_shape": (2, 1, 3, 4), }, { "testcase_name": "_3d_1_3_bias", "equation": "abc,cde->abde", "bias_axes": "be", "input_shape": (2, 7, 2), "output_shape": (7, 3, 4), "expected_kernel_shape": (2, 3, 4), "expected_bias_shape": (7, 1, 4), "expected_output_shape": (2, 7, 3, 4), }, { "testcase_name": "_3d_bert_projection", "equation": "BFNH,NHD->BFD", "bias_axes": None, "input_shape": (2, 1, 2, 3), "output_shape": (1, 4), "expected_kernel_shape": (2, 3, 4), "expected_bias_shape": None, "expected_output_shape": (2, 1, 4), }, { "testcase_name": "_2d_bert", "equation": "abc,cd->abd", "bias_axes": None, "input_shape": (2, 1, 2), "output_shape": (1, 4), "expected_kernel_shape": (2, 4), "expected_bias_shape": None, "expected_output_shape": (2, 1, 4), }, { "testcase_name": "_embedding_1d", "equation": "i,d->id", "bias_axes": None, "input_shape": (2,), "output_shape": (2,), "expected_kernel_shape": (2,), "expected_bias_shape": None, "expected_output_shape": (2, 2), }, { "testcase_name": "_xlnet_lm", "equation": "ibd,nd->ibn", "bias_axes": None, "input_shape": (2, 2, 1), "output_shape": (2, 2), "expected_kernel_shape": (2, 1), "expected_bias_shape": None, "expected_output_shape": (2, 2, 2), }, { "testcase_name": "_2d_precast", "equation": "...b,bc->...c", "bias_axes": None, "input_shape": (2, 32), "output_shape": (64,), "expected_kernel_shape": (32, 64), "expected_bias_shape": None, "expected_output_shape": (2, 64), }, { "testcase_name": "_2d_precast_elided_input_used_in_output", "equation": "...bc,bc->...b", "bias_axes": None, "input_shape": (2, 32, 64), "output_shape": (32,), "expected_kernel_shape": (32, 64), "expected_bias_shape": None, "expected_output_shape": (2, 32), }, { "testcase_name": "_2d_precast_multiple_elided_dims", "equation": "...b,bc->...c", "bias_axes": None, "input_shape": (2, 3, 32), "output_shape": (64,), "expected_kernel_shape": (32, 64), "expected_bias_shape": None, "expected_output_shape": (2, 3, 64), }, { "testcase_name": "_3d_precast", "equation": "...c,cde->...de", "bias_axes": None, "input_shape": (2, 1, 2), "output_shape": (3, 4), "expected_kernel_shape": (2, 3, 4), "expected_bias_shape": None, "expected_output_shape": (2, 1, 3, 4), }, { "testcase_name": "_3d_precast_3_bias", "equation": "...c,cde->...de", "bias_axes": "e", "input_shape": (2, 1, 2), "output_shape": (3, 4), "expected_kernel_shape": (2, 3, 4), "expected_bias_shape": (4,), "expected_output_shape": (2, 1, 3, 4), }, { "testcase_name": "_3d_precast_2_bias", "equation": "...c,cde->...de", "bias_axes": "d", "input_shape": (2, 1, 2), "output_shape": (3, 4), "expected_kernel_shape": (2, 3, 4), "expected_bias_shape": (3, 1), "expected_output_shape": (2, 1, 3, 4), }, { "testcase_name": "_3d_precast_2_3_bias", "equation": "...c,cde->...de", "bias_axes": "de", "input_shape": (2, 1, 2), "output_shape": (3, 4), "expected_kernel_shape": (2, 3, 4), "expected_bias_shape": (3, 4), "expected_output_shape": (2, 1, 3, 4), }, { "testcase_name": "_2d_postcast", "equation": "bc...,cd->bd...", "bias_axes": None, "input_shape": (2, 1, 2, 3), "output_shape": (4,), "expected_kernel_shape": (1, 4), "expected_bias_shape": None, "expected_output_shape": (2, 4, 2, 3), }, { "testcase_name": "_3d_postcast", "equation": "bc...,cde->bde...", "bias_axes": None, "input_shape": (2, 1, 2), "output_shape": (3, 4), "expected_kernel_shape": (1, 3, 4), "expected_bias_shape": None, "expected_output_shape": (2, 3, 4, 2), }, { "testcase_name": "_3d_postcast_1_bias", "equation": "bc...,cde->bde...", "bias_axes": "d", "input_shape": (2, 1, 2), "output_shape": (3, 4), "expected_kernel_shape": (1, 3, 4), "expected_bias_shape": (3, 1, 1), "expected_output_shape": (2, 3, 4, 2), }, { "testcase_name": "_3d_postcast_2_bias", "equation": "bc...,cde->bde...", "bias_axes": "e", "input_shape": (2, 1, 2), "output_shape": (3, 4), "expected_kernel_shape": (1, 3, 4), "expected_bias_shape": (4, 1), "expected_output_shape": (2, 3, 4, 2), }, { "testcase_name": "_3d_postcast_1_2_bias", "equation": "bc...,cde->bde...", "bias_axes": "de", "input_shape": (2, 1, 2), "output_shape": (3, 4), "expected_kernel_shape": (1, 3, 4), "expected_bias_shape": (3, 4, 1), "expected_output_shape": (2, 3, 4, 2), }, ) @pytest.mark.requires_trainable_backend def test_einsum_dense_basics( self, equation, bias_axes, input_shape, output_shape, expected_kernel_shape, expected_bias_shape, expected_output_shape, ): self.run_layer_test( layers.EinsumDense, init_kwargs={ "equation": equation, "output_shape": output_shape, "bias_axes": bias_axes, }, input_shape=input_shape, expected_output_shape=expected_output_shape, expected_num_trainable_weights=( 2 if expected_bias_shape is not None else 1 ), expected_num_non_trainable_weights=0, expected_num_seed_generators=0, expected_num_losses=0, supports_masking=False, ) layer = layers.EinsumDense( equation, output_shape=output_shape, bias_axes=bias_axes ) layer.build(input_shape) self.assertEqual(layer.kernel.shape, expected_kernel_shape) if expected_bias_shape is not None: self.assertEqual(layer.bias.shape, expected_bias_shape) def test_einsum_dense_constraints(self): layer = layers.EinsumDense( "abc,cde->abde", (1, 3, 4), kernel_constraint="non_neg" ) layer.build((2, 1, 2)) self.assertIsInstance(layer.kernel.constraint, constraints.NonNeg) layer = layers.EinsumDense( "ab,b->a", (1, 3, 4), bias_axes="a", bias_constraint="non_neg" ) layer.build((2, 1, 2)) self.assertIsInstance(layer.bias.constraint, constraints.NonNeg) @pytest.mark.requires_trainable_backend def test_enable_lora(self): layer = layers.EinsumDense( equation="ab,bcd->acd", output_shape=(8, 32), bias_axes=None, ) layer.build((None, 3)) layer.enable_lora(2) self.assertLen(layer.trainable_weights, 2) self.assertLen(layer.non_trainable_weights, 1) if backend.backend() == "torch": self.assertLen(layer.torch_params, 3) # Try eager call x = np.random.random((64, 3)) y = np.random.random((64, 8, 32)) _ = layer(x[:2]) init_lora_a_kernel_value = layer.lora_kernel_a.numpy() init_lora_b_kernel_value = layer.lora_kernel_b.numpy() # Try calling fit() model = models.Sequential( [ layer, ] ) model.compile(optimizer="sgd", loss="mse") model.fit(x, y, epochs=2) final_lora_a_kernel_value = layer.lora_kernel_a.numpy() final_lora_b_kernel_value = layer.lora_kernel_b.numpy() diff_a = np.max( np.abs(init_lora_a_kernel_value - final_lora_a_kernel_value) ) diff_b = np.max( np.abs(init_lora_b_kernel_value - final_lora_b_kernel_value) ) self.assertGreater(diff_a, 0.0) self.assertGreater(diff_b, 0.0) # Try saving and reloading the model temp_filepath = os.path.join(self.get_temp_dir(), "lora_model.keras") model.save(temp_filepath) new_model = saving.load_model(temp_filepath) self.assertTrue(new_model.layers[0].lora_enabled) self.assertAllClose(model.predict(x), new_model.predict(x)) # Try saving and reloading the model's weights only temp_filepath = os.path.join( self.get_temp_dir(), "lora_model.weights.h5" ) model.save_weights(temp_filepath) # Load the file into a fresh, non-lora model new_model = models.Sequential( [ layers.EinsumDense( equation="ab,bcd->acd", output_shape=(8, 32), bias_axes=None, ), ] ) new_model.build((None, 3)) new_model.load_weights(temp_filepath) self.assertAllClose(model.predict(x), new_model.predict(x)) # Try loading a normal checkpoint into a lora model new_model.save_weights(temp_filepath) model.load_weights(temp_filepath) self.assertAllClose(model.predict(x), new_model.predict(x)) @pytest.mark.requires_trainable_backend def test_enable_lora_with_alpha(self): # Use a simple equation that mimics a `Dense` layer behavior. equation = "ab,bc->ac" output_shape = 3 # This means the kernel shape will be (input_dim, 3). bias_axes = None # Create and build the `EinsumDense` layer # with an input shape (None, 2). layer = layers.EinsumDense( equation=equation, output_shape=output_shape, bias_axes=bias_axes ) # Build the layer with an input shape of (batch, 2). layer.build((None, 2)) # Set the base kernel weights to a known value. base_kernel = np.array( [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=np.float32 ) layer._kernel.assign(base_kernel) # Enable LoRA with `rank`=2 and a custom `lora_alpha`=3.0. layer.enable_lora(rank=2, lora_alpha=3.0) self.assertEqual(layer.lora_rank, 2) self.assertEqual(layer.lora_alpha, 3.0) # The expected shapes are: # `base_kernel`: (2, 3) # `lora_kernel_a`: (2, 2) and `lora_kernel_b`: (2, 3) a_val = np.array([[0.1, 0.2], [0.3, 0.4]], dtype=np.float32) b_val = np.array([[0.5, 0.6, 0.7], [0.8, 0.9, 1.0]], dtype=np.float32) layer.lora_kernel_a.assign(a_val) layer.lora_kernel_b.assign(b_val) # Compute expected effective kernel. # Scaling factor is `lora_alpha / lora_rank` = 3.0 / 2 = 1.5 expected_delta = 1.5 * np.matmul(a_val, b_val) expected_kernel = base_kernel + expected_delta # Verify that the effective kernel property returns the expected value. actual_kernel = ops.convert_to_numpy(layer.kernel) self.assertAllClose(actual_kernel, expected_kernel) @pytest.mark.requires_trainable_backend def test_lora_rank_argument(self): self.run_layer_test( layers.EinsumDense, init_kwargs={ "equation": "ab,bcd->acd", "output_shape": (8, 32), "bias_axes": None, "lora_rank": 2, }, input_shape=(2, 3), expected_output_shape=(2, 8, 32), expected_num_trainable_weights=2, expected_num_non_trainable_weights=1, expected_num_seed_generators=0, expected_num_losses=0, supports_masking=False, ) # Test quantization-related methods. @parameterized.named_parameters( ("int8", "int8", 1e-3), ("int4", "int4", 3e-3), ) def test_quantize_int(self, mode, error_threshold): layer = layers.EinsumDense( equation="ab,bcd->acd", output_shape=(8, 32), bias_axes="d", ) layer.build((None, 3)) x = np.random.random((2, 3)) y_float = layer(x) layer.quantize(mode) # Verify weights dtype self.assertEqual(backend.standardize_dtype(layer._kernel.dtype), "int8") self.assertEqual( backend.standardize_dtype(layer.kernel_scale.dtype), layer.variable_dtype, ) # Try eager call and verify output correctness y_quantized = layer(x) mse = ops.mean(ops.square(y_float - y_quantized)) self.assertLess(mse, error_threshold) # A weak correctness test # Try saving and reloading the model model = models.Sequential([layer]) temp_filepath = os.path.join( self.get_temp_dir(), "quantized_model.keras" ) model.save(temp_filepath) new_model = saving.load_model(temp_filepath) self.assertAllClose(model.predict(x), new_model.predict(x)) # Try saving and reloading the model's weights only temp_filepath = os.path.join( self.get_temp_dir(), "quantized_model.weights.h5" ) model.save_weights(temp_filepath) # Try building with quantized dtype policy layer = layers.EinsumDense( equation="abcde,afce->acdbf", # Test reduce and transpose output_shape=(2, 4, 8, 16), bias_axes="d", dtype=f"{mode}_from_mixed_bfloat16", ) layer.build((1, 8, 2, 4, 32)) self.assertEqual(backend.standardize_dtype(layer._kernel.dtype), "int8") self.assertEqual( backend.standardize_dtype(layer.kernel_scale.dtype), "float32" ) layer = layers.EinsumDense( equation="a,b->ab", # Test expand output_shape=(4,), dtype=f"{mode}_from_float32", ) layer.build((None,)) self.assertEqual(backend.standardize_dtype(layer._kernel.dtype), "int8") self.assertEqual( backend.standardize_dtype(layer.kernel_scale.dtype), "float32" ) layer = layers.EinsumDense( equation="ab,ab->a", # Test squeeze output_shape=(2,), dtype="int8_from_float32", ) layer.build((2, 4)) self.assertEqual(backend.standardize_dtype(layer._kernel.dtype), "int8") self.assertEqual( backend.standardize_dtype(layer.kernel_scale.dtype), "float32" ) @parameterized.named_parameters( ( "int8_btnh,nhd->btd", "int8", "btnh,nhd->btd", (None, 8), (1, 2, 2, 4), 1e-3, ), ( "int8_btd,ndh->btnh", "int8", "btd,ndh->btnh", (None, 2, 8), (1, 2, 4), 1e-3, ), ("int8_btd,df->btf", "int8", "btd,df->btf", (None, 4), (1, 2, 4), 1e-3), ( "int4_btnh,nhd->btd", "int4", "btnh,nhd->btd", (None, 8), (1, 2, 2, 4), 3e-3, ), ( "int4_btd,ndh->btnh", "int4", "btd,ndh->btnh", (None, 2, 8), (1, 2, 4), 3e-3, ), ( "int4_btd,df->btf", "int4", "btd,df->btf", (None, 4), (1, 2, 4), 3e-3, ), ) def test_quantize_with_specific_equations( self, quantization_mode, equation, output_shape, input_shape, error_threshold, ): layer = layers.EinsumDense(equation=equation, output_shape=output_shape) layer.build(input_shape) x = ops.random.uniform(input_shape) y_float = layer(x) layer.quantize(quantization_mode) y_quantized = layer(x) mse = ops.mean(ops.square(y_float - y_quantized)) self.assertLess(mse, error_threshold) # A weak correctness test @parameterized.named_parameters( ("int8", "int8"), ("float8", "float8"), ("int4", "int4"), ) def test_quantize_on_unbuilt_layer(self, mode): layer = layers.EinsumDense( equation="ab,bcd->acd", output_shape=(8, 32), bias_axes="d", ) with self.assertRaisesRegex( ValueError, "Cannot quantize a layer that isn't yet built." ): layer.quantize(mode) @parameterized.named_parameters( ("int8", "int8"), ("float8", "float8"), ("int4", "int4"), ) def test_quantize_on_subclass(self, mode): class MyEinsumDense(layers.EinsumDense): pass layer = MyEinsumDense( equation="ab,bcd->acd", output_shape=(8, 32), bias_axes="d", ) layer.build((None, 3)) with self.assertRaises(NotImplementedError): layer.quantize(mode) layer.quantize(mode, type_check=False) # No error @parameterized.named_parameters( ("int8", "int8"), ("float8", "float8"), ("int4", "int4"), ) def test_quantize_when_already_quantized(self, mode): layer = layers.EinsumDense( equation="ab,bcd->acd", output_shape=(8, 16), bias_axes="d", ) layer.build((None, 3)) layer.quantize(mode) for m in ["int8", "float8"]: with self.assertRaisesRegex( ValueError, "is already quantized with dtype_policy=" ): layer.quantize(m) layer = layers.EinsumDense( equation="ab,bcd->acd", output_shape=(8, 16), bias_axes="d", dtype=f"{mode}_from_float32", ) layer.build((None, 3)) for m in ["int8", "float8"]: with self.assertRaisesRegex( ValueError, "is already quantized with dtype_policy=" ): layer.quantize(m) @parameterized.named_parameters( ("int8", "int8_from_float32", 3), ("float8", "float8_from_float32", 8), ("int4", "int4_from_float32", 3), ) def test_quantize_by_setting_dtype_policy( self, policy, expected_num_variables ): layer = layers.EinsumDense( equation="ab,bcd->acd", output_shape=(8, 32), bias_axes="d", ) layer.build((None, 3)) layer.dtype_policy = policy self.assertLen(layer.variables, expected_num_variables) @parameterized.named_parameters( ("int7", "int7"), ("float7", "float7"), ("int3", "int3"), ) def test_quantize_invalid_mode(self, mode): layer = layers.EinsumDense( equation="ab,bcd->acd", output_shape=(8, 32), bias_axes="d", ) layer.build((None, 3)) x = np.random.random((1, 3)) # dtype_policy should not be altered by failed quantization original_dtype_policy = layer.dtype_policy # Test quantize with self.assertRaisesRegex(ValueError, "Invalid quantization mode."): layer.quantize(mode) self.assertEqual(layer.dtype_policy, original_dtype_policy) # Test quantized_build with self.assertRaisesRegex( NotImplementedError, "Invalid quantization mode." ): layer.quantized_build((None, 2), mode) self.assertEqual(layer.dtype_policy, original_dtype_policy) # Test quantized_call with self.assertRaisesRegex( NotImplementedError, "Invalid quantization mode." ): # Explicitly set quantization_mode layer._dtype_policy._quantization_mode = mode layer.quantized_call(x) self.assertEqual(layer.dtype_policy, original_dtype_policy) @parameterized.named_parameters( ("int8", "int8_from_mixed_bfloat16", 1, 2), ("float8", "float8_from_mixed_bfloat16", 8, 0), ("int4", "int4_from_mixed_bfloat16", 1, 2), ) @pytest.mark.requires_trainable_backend def test_quantize_dtype_argument( self, dtype, num_trainable_weights, num_non_trainable_weights ): self.run_layer_test( layers.EinsumDense, init_kwargs={ "equation": "ab,bcd->acd", "output_shape": (8, 32), "bias_axes": "d", "dtype": dtype, }, input_shape=(2, 3), expected_output_shape=(2, 8, 32), expected_num_trainable_weights=num_trainable_weights, expected_num_non_trainable_weights=num_non_trainable_weights, expected_num_seed_generators=0, expected_num_losses=0, supports_masking=False, ) @parameterized.named_parameters( ("int8_ab,bcd->acd", "int8", "ab,bcd->acd", (64, 3), (64, 8, 32)), ( "int8_btd,ndh->btnh", "int8", "btd,ndh->btnh", (1, 4, 32), (1, 4, 8, 16), ), ("int4_ab,bcd->acd", "int4", "ab,bcd->acd", (64, 3), (64, 8, 32)), ( "int4_btd,ndh->btnh", "int4", "btd,ndh->btnh", (1, 4, 32), (1, 4, 8, 16), ), ) @pytest.mark.requires_trainable_backend def test_quantize_lora_integration( self, quantization_mode, equation, input_shape, output_shape ): config = dict( equation=equation, output_shape=output_shape[1:], bias_axes=None ) layer = layers.EinsumDense(**config) layer.build(input_shape) layer.enable_lora(2) layer.quantize(quantization_mode) self.assertLen(layer.trainable_weights, 2) self.assertLen(layer.non_trainable_weights, 2) if backend.backend() == "torch": self.assertLen(layer.torch_params, 4) # Try calling fit() init_lora_a_kernel_value = layer.lora_kernel_a.numpy() init_lora_b_kernel_value = layer.lora_kernel_b.numpy() x = np.random.random(input_shape) y = np.random.random(output_shape) model = models.Sequential([layer]) model.compile(optimizer="sgd", loss="mse") model.fit(x, y, epochs=2) final_lora_a_kernel_value = layer.lora_kernel_a.numpy() final_lora_b_kernel_value = layer.lora_kernel_b.numpy() diff_a = np.max( np.abs(init_lora_a_kernel_value - final_lora_a_kernel_value) ) diff_b = np.max( np.abs(init_lora_b_kernel_value - final_lora_b_kernel_value) ) self.assertGreater(diff_a, 0.0) self.assertGreater(diff_b, 0.0) # Try saving and reloading the model temp_filepath = os.path.join( self.get_temp_dir(), "quantized_lora_model.keras" ) model.save(temp_filepath) new_model = saving.load_model(temp_filepath) self.assertTrue(new_model.layers[0].lora_enabled) self.assertAllClose(model.predict(x), new_model.predict(x), atol=0.5) # Try saving and reloading the model's weights only temp_filepath = os.path.join( self.get_temp_dir(), "quantized_lora_model.weights.h5" ) model.save_weights(temp_filepath) new_model = models.Sequential([layers.EinsumDense(**config)]) new_model.build(input_shape) new_model.quantize(quantization_mode) new_model.load_weights(temp_filepath) self.assertFalse(new_model.layers[0].lora_enabled) self.assertAllClose(model.predict(x), new_model.predict(x), atol=0.5) # Try loading a normal checkpoint into a lora model new_model.save_weights(temp_filepath) model.load_weights(temp_filepath) self.assertAllClose(model.predict(x), new_model.predict(x), atol=0.5) # Test export and TFSMLayer reloading when using tensorflow backend if backend.backend() == "tensorflow": import tensorflow as tf temp_filepath = os.path.join(self.get_temp_dir(), "exported_model") ref_input = tf.random.normal(input_shape) ref_output = model(ref_input) model.export(temp_filepath, format="tf_saved_model") reloaded_layer = export.TFSMLayer(temp_filepath) self.assertAllClose( reloaded_layer(ref_input), ref_output, atol=1e-7 ) self.assertLen(reloaded_layer.weights, len(model.weights)) self.assertLen( reloaded_layer.trainable_weights, len(model.trainable_weights) ) self.assertLen( reloaded_layer.non_trainable_weights, len(model.non_trainable_weights), ) @pytest.mark.requires_trainable_backend def test_quantize_float8(self): import ml_dtypes from keras.src import quantizers layer = layers.EinsumDense( "ab,bc->ac", output_shape=[32], bias_axes="c", ) layer.build((None, 16)) layer.quantize("float8") optimizer = optimizers.AdamW(learning_rate=0.1) optimizer.build(layer.trainable_variables) def loss_fn(x, dy): y = layer(x, training=True) loss = y * ops.cast(dy, y.dtype) return ops.sum(loss) if backend.backend() == "tensorflow": import tensorflow as tf @tf.function(jit_compile=True) def train_one_step(x, dy): with tf.GradientTape() as tape: loss = loss_fn(x, dy) grads = tape.gradient(loss, layer.trainable_variables) optimizer.apply(grads, layer.trainable_variables) elif backend.backend() == "jax": import jax def stateless_loss_fn(trainable_variables, x, dy): y = layer.stateless_call( trainable_variables, [], x, training=True )[0] loss = y * ops.cast(dy, y.dtype) return ops.sum(loss) grad_fn = jax.jit(jax.grad(stateless_loss_fn)) def train_one_step(x, dy): trainable_variables = [ v.value for v in layer.trainable_variables ] optimizer_variables = [v.value for v in optimizer.variables] grads = grad_fn(trainable_variables, x, dy) trainable_variables, optimizer_variables = ( optimizer.stateless_apply( optimizer_variables, grads, trainable_variables ) ) for variable, value in zip( layer.trainable_variables, trainable_variables ): variable.assign(value) for variable, value in zip( optimizer.variables, optimizer_variables ): variable.assign(value) elif backend.backend() == "torch": def train_one_step(x, dy): layer.zero_grad() loss = loss_fn(x, dy) loss.backward() grads = [v.value.grad for v in layer.trainable_variables] optimizer.apply(grads, layer.trainable_variables) scale_x, amax_history_x = ops.ones(()), ops.zeros((1024,)) scale_k, amax_history_k = ops.ones(()), ops.zeros((1024,)) scale_g, amax_history_g = ops.ones(()), ops.zeros((1024,)) e4m3_max = ops.cast( float(ml_dtypes.finfo("float8_e4m3fn").max), "float32" ) e5m2_max = ops.cast( float(ml_dtypes.finfo("float8_e5m2").max), "float32" ) for _ in range(3): x = random.normal((16, 16), dtype="float32") g = random.normal((16, 32), dtype="float32") k = ops.convert_to_tensor(layer._kernel) # Manually compute the expected amax history and scaling factors. amax_from_history_x = ops.max(amax_history_x) amax_from_history_k = ops.max(amax_history_k) amax_from_history_g = ops.max(amax_history_g) scale_x = quantizers.compute_float8_scale( amax_from_history_x, scale_x, e4m3_max ) scale_k = quantizers.compute_float8_scale( amax_from_history_k, scale_k, e4m3_max ) scale_g = quantizers.compute_float8_scale( amax_from_history_g, scale_g, e5m2_max ) amax_history_x = quantizers.compute_float8_amax_history( x, amax_history_x ) amax_history_k = quantizers.compute_float8_amax_history( k, amax_history_k ) amax_history_g = quantizers.compute_float8_amax_history( g, amax_history_g ) train_one_step(x, g) self.assertAllClose(layer.inputs_amax_history, amax_history_x) self.assertAllClose(layer.kernel_amax_history, amax_history_k) self.assertAllClose(layer.outputs_grad_amax_history, amax_history_g) self.assertAllClose(layer.inputs_scale, scale_x) self.assertAllClose(layer.kernel_scale, scale_k) self.assertAllClose(layer.outputs_grad_scale, scale_g) @pytest.mark.requires_trainable_backend def test_quantize_float8_fitting(self): config = dict( equation="ab,bcd->acd", output_shape=(8, 32), bias_axes="d", ) layer = layers.EinsumDense(**config) layer.build((None, 3)) layer.quantize("float8") self.assertLen(layer.trainable_weights, 8) self.assertLen(layer.non_trainable_weights, 0) # Try calling fit() x = np.random.random((64, 3)) y = np.random.random((64, 8, 32)) model = models.Sequential([layer]) model.compile(optimizer="sgd", loss="mse") model.fit(x, y, epochs=2) # Try saving and reloading the model temp_filepath = os.path.join( self.get_temp_dir(), "quantized_lora_model.keras" ) model.save(temp_filepath) new_model = saving.load_model(temp_filepath) self.assertAllClose(model.predict(x), new_model.predict(x)) # Try saving and reloading the model's weights only temp_filepath = os.path.join( self.get_temp_dir(), "quantized_lora_model.weights.h5" ) model.save_weights(temp_filepath) new_model = models.Sequential([layers.EinsumDense(**config)]) new_model.build((None, 3)) new_model.quantize("float8") new_model.load_weights(temp_filepath) self.assertAllClose(model.predict(x), new_model.predict(x)) # Test export and TFSMLayer reloading when using tensorflow backend if backend.backend() == "tensorflow": import tensorflow as tf temp_filepath = os.path.join(self.get_temp_dir(), "exported_model") ref_input = tf.random.normal((2, 3)) ref_output = model(ref_input) model.export(temp_filepath, format="tf_saved_model") reloaded_layer = export.TFSMLayer(temp_filepath) self.assertAllClose(reloaded_layer(ref_input), ref_output) self.assertLen(reloaded_layer.weights, len(model.weights)) self.assertLen( reloaded_layer.trainable_weights, len(model.trainable_weights) ) self.assertLen( reloaded_layer.non_trainable_weights, len(model.non_trainable_weights), ) def test_quantize_float8_inference(self): config = dict( equation="ab,bcd->acd", output_shape=(8, 32), bias_axes="d", ) layer = layers.EinsumDense(**config) layer.build((None, 3)) layer.quantize("float8") # Try calling with `training=False` and the result must match # `training=True` because there is no update. x = np.random.random((64, 3)) y_inference = layer(x, training=False) y_training = layer(x, training=True) self.assertAllClose(y_inference, y_training) def test_gptq_serialization(self): """Test that a GPTQ-quantized layer can be serialized and deserialized correctly.""" config = dict( equation="ab,bcd->acd", output_shape=(8, 32), bias_axes="d", ) layer = layers.EinsumDense(**config) layer.build((None, 3)) layer.quantize( "gptq", config=GPTQConfig( dataset=None, tokenizer=None, weight_bits=4, group_size=8 ), ) config = layer.get_config() new_layer = layers.EinsumDense.from_config(config) new_layer.build((None, 3)) self.assertEqual(new_layer.quantization_mode, "gptq") def test_int4_kernel_returns_unpacked_form(self): """Test that the `kernel` property returns the unpacked int4 kernel.""" layer = layers.EinsumDense( equation="ab,bc->ac", output_shape=(2,), ) layer.build((None, 2)) layer.quantize("int4") packed_kernel = layer._kernel self.assertAllClose( layer.kernel, quantizers.unpack_int4(packed_kernel, 2) ) def test_legacy_load_own_variables(self): # In previous versions, `load_own_variables` accepted a store with # numeric keys. float32_store = { "0": np.random.random((3, 8, 32)).astype("float32"), "1": np.random.random((32,)).astype("float32"), } int8_store = { "0": np.random.randint(-128, 127, size=(3, 8, 32), dtype="int8"), "1": np.random.random((32,)).astype("float32"), "2": np.random.random((1, 8, 32)).astype("float32"), } int4_store = { "0": np.random.randint(-128, 127, size=(2, 8, 32), dtype="int8"), "1": np.random.random((32,)).astype("float32"), "2": np.random.random((1, 8, 32)).astype("float32"), } float8_store = { "0": np.random.random((3, 8, 32)).astype("float32"), "1": np.random.random((32,)).astype("float32"), # inputs_scale. "2": np.random.random(()).astype("float32"), # inputs_amax_history. "3": np.random.random((1024,)).astype("float32"), # kernel_scale. "4": np.random.random(()).astype("float32"), # kernel_amax_history. "5": np.random.random((1024,)).astype("float32"), # outputs_grad_scale. "6": np.random.random(()).astype("float32"), # outputs_grad_amax_history. "7": np.random.random((1024,)).astype("float32"), } gptq_store = { # bias "0": np.random.random((32,)).astype("float32"), # quantized_kernel "1": np.random.randint(0, 16, size=(16, 24), dtype="uint8"), # kernel_scale. "2": np.random.random((32, 3)).astype("float32"), # kernel_zero "3": np.random.random((32, 3)).astype("uint8"), # g_idx "4": np.random.random((24,)).astype("float32"), } config = dict( equation="ab,bcd->acd", output_shape=(8, 32), bias_axes="d", ) # Test float32 layer. layer = layers.EinsumDense(**config) layer.build((None, 3)) layer.load_own_variables(float32_store) self.assertAllClose(layer._kernel, float32_store["0"]) self.assertAllClose(layer.bias, float32_store["1"]) # Test int8-quantized layer. layer = layers.EinsumDense(**config, dtype="int8_from_float32") layer.build((None, 3)) layer.load_own_variables(int8_store) self.assertAllClose(layer._kernel, int8_store["0"]) self.assertAllClose(layer.bias, int8_store["1"]) self.assertAllClose(layer.kernel_scale, int8_store["2"]) # Test int4-quantized layer. layer = layers.EinsumDense(**config, dtype="int4_from_float32") layer.build((None, 3)) layer.load_own_variables(int4_store) self.assertAllClose(layer._kernel, int4_store["0"]) self.assertAllClose(layer.bias, int4_store["1"]) self.assertAllClose(layer.kernel_scale, int4_store["2"]) # Test float8-quantized layer. layer = layers.EinsumDense(**config, dtype="float8_from_float32") layer.build((None, 3)) layer.load_own_variables(float8_store) self.assertAllClose(layer._kernel, float8_store["0"]) self.assertAllClose(layer.bias, float8_store["1"]) self.assertAllClose(layer.inputs_scale, float8_store["2"]) self.assertAllClose(layer.inputs_amax_history, float8_store["3"]) self.assertAllClose(layer.kernel_scale, float8_store["4"]) self.assertAllClose(layer.kernel_amax_history, float8_store["5"]) self.assertAllClose(layer.outputs_grad_scale, float8_store["6"]) self.assertAllClose(layer.outputs_grad_amax_history, float8_store["7"]) # Test gptq-quantized layer. layer = layers.EinsumDense(**config, dtype="gptq/4/8_from_float32") layer.build((None, 3)) layer.load_own_variables(gptq_store) self.assertTrue(layer.is_gptq_calibrated) self.assertAllClose(layer.bias, gptq_store["0"]) self.assertAllClose(layer.quantized_kernel, gptq_store["1"]) self.assertAllClose(layer.kernel_scale, gptq_store["2"]) self.assertAllClose(layer.kernel_zero, gptq_store["3"]) self.assertAllClose(layer.g_idx, gptq_store["4"]) def test_int4_gptq_kernel_returns_unpacked_form(self): """Test that the `kernel` property returns the unpacked int4 GPTQ kernel.""" layer = layers.EinsumDense( equation="ab,bc->ac", output_shape=(2,), ) layer.build((None, 2)) layer.quantize( "gptq", config=GPTQConfig( dataset=None, tokenizer=None, weight_bits=4, group_size=8 ), ) layer.is_gptq_calibrated = True # Bypass calibration check packed_kernel = layer.quantized_kernel self.assertAllClose( layer.kernel, quantizers.unpack_int4(packed_kernel, 2) ) def test_gptq_kernel_packing(self): """Validates that 4-bit GPTQ packing reduces the kernel size.""" config = dict( equation="ab,bcd->acd", output_shape=(8, 32), bias_axes="d", ) layer = layers.EinsumDense(**config) layer.build((None, 3)) original_kernel_params = ops.prod(layer._kernel.shape) layer.quantize( "gptq", config=GPTQConfig( dataset=None, tokenizer=None, weight_bits=4, group_size=8 ), ) quantized_kernel_params = ops.prod(layer.quantized_kernel.shape) self.assertEqual( quantized_kernel_params, original_kernel_params // 2, )
EinsumDenseTest
python
tensorflow__tensorflow
tensorflow/tools/proto_splitter/split_graph_def.py
{ "start": 5369, "end": 5786 }
class ____(split.ComposableSplitter): """A Splitter that's based on the size of the input proto.""" __slots__ = ("fn", "proto_size") def __init__(self, proto, proto_size, **kwargs): """Initializer.""" self.proto_size = proto_size super().__init__(proto, **kwargs) def build_chunks(self) -> int: """Splits the proto, and returns the size of the chunks created.""" return 0
SplitBasedOnSize
python
pytorch__pytorch
torch/jit/quantized.py
{ "start": 2025, "end": 2278 }
class ____(QuantizedRNNBase): def __init__(self, other, dtype): raise RuntimeError( "torch.jit.QuantizedLSTM is no longer supported. " "Please use the torch.ao.nn.quantized.dynamic.LSTM instead." )
QuantizedLSTM
python
dagster-io__dagster
python_modules/dagster-test/dagster_test/toys/input_managers.py
{ "start": 126, "end": 1143 }
class ____(IOManager): def __init__(self, base_dir=None): self.base_dir = os.getenv("DAGSTER_HOME") if base_dir is None else base_dir def _get_path(self, output_context): return os.path.join( # pyright: ignore[reportCallIssue] self.base_dir, # pyright: ignore[reportArgumentType] "storage", f"{output_context.step_key}_{output_context.name}.csv", ) def handle_output(self, context, obj: pd.DataFrame): file_path = self._get_path(context) os.makedirs(os.path.dirname(file_path), exist_ok=True) if obj is not None: obj.to_csv(file_path, index=False) def load_input(self, context) -> pd.DataFrame: return pd.read_csv(self._get_path(context.upstream_output)) @io_manager(config_schema={"base_dir": Field(Noneable(str), default_value=None, is_required=False)}) def pandas_io_manager(init_context): return PandasCsvIOManager(base_dir=init_context.resource_config["base_dir"])
PandasCsvIOManager
python
doocs__leetcode
solution/0800-0899/0851.Loud and Rich/Solution.py
{ "start": 0, "end": 532 }
class ____: def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]: def dfs(i: int): if ans[i] != -1: return ans[i] = i for j in g[i]: dfs(j) if quiet[ans[j]] < quiet[ans[i]]: ans[i] = ans[j] g = defaultdict(list) for a, b in richer: g[b].append(a) n = len(quiet) ans = [-1] * n for i in range(n): dfs(i) return ans
Solution
python
apache__airflow
airflow-core/tests/unit/api_fastapi/execution_api/versions/head/test_assets.py
{ "start": 2324, "end": 3506 }
class ____: def test_get_asset_by_uri(self, client, session): asset = AssetModel( name="test_get_asset_by_uri", uri="s3://bucket/key", group="asset", extra={"foo": "bar"}, ) asset_active = AssetActive.for_asset(asset) session.add_all([asset, asset_active]) session.commit() response = client.get("/execution/assets/by-uri", params={"uri": "s3://bucket/key"}) assert response.status_code == 200 assert response.json() == { "name": "test_get_asset_by_uri", "uri": "s3://bucket/key", "group": "asset", "extra": {"foo": "bar"}, } session.delete(asset) session.delete(asset_active) session.commit() def test_asset_uri_not_found(self, client): response = client.get("/execution/assets/by-uri", params={"uri": "non_existent"}) assert response.status_code == 404 assert response.json() == { "detail": { "message": "Asset with URI non_existent not found", "reason": "not_found", } }
TestGetAssetByUri
python
Pylons__pyramid
tests/test_asset.py
{ "start": 79, "end": 1517 }
class ____(unittest.TestCase): def _callFUT(self, spec, package_name='__main__'): from pyramid.resource import resolve_asset_spec return resolve_asset_spec(spec, package_name) def test_abspath(self): package_name, filename = self._callFUT(here, 'apackage') self.assertEqual(filename, here) self.assertEqual(package_name, None) def test_rel_spec(self): pkg = 'tests' path = 'test_asset.py' package_name, filename = self._callFUT(path, pkg) self.assertEqual(package_name, 'tests') self.assertEqual(filename, 'test_asset.py') def test_abs_spec(self): pkg = 'tests' path = 'pyramid.nottests:test_asset.py' package_name, filename = self._callFUT(path, pkg) self.assertEqual(package_name, 'pyramid.nottests') self.assertEqual(filename, 'test_asset.py') def test_package_name_is_None(self): pkg = None path = 'test_asset.py' package_name, filename = self._callFUT(path, pkg) self.assertEqual(package_name, None) self.assertEqual(filename, 'test_asset.py') def test_package_name_is_package_object(self): import tests pkg = tests path = 'test_asset.py' package_name, filename = self._callFUT(path, pkg) self.assertEqual(package_name, 'tests') self.assertEqual(filename, 'test_asset.py')
Test_resolve_asset_spec
python
allegroai__clearml
clearml/backend_api/services/v2_20/queues.py
{ "start": 57719, "end": 58671 }
class ____(Request): """ Gets the next task from the top of the queue (FIFO). The task entry is removed from the queue. :param queue: Queue id :type queue: str """ _service = "queues" _action = "get_next_task" _version = "2.20" _schema = { "definitions": {}, "properties": {"queue": {"description": "Queue id", "type": "string"}}, "required": ["queue"], "type": "object", } def __init__(self, queue: str, **kwargs: Any) -> None: super(GetNextTaskRequest, self).__init__(**kwargs) self.queue = queue @schema_property("queue") def queue(self) -> str: return self._property_queue @queue.setter def queue(self, value: str) -> None: if value is None: self._property_queue = None return self.assert_isinstance(value, "queue", six.string_types) self._property_queue = value
GetNextTaskRequest
python
pypa__virtualenv
src/virtualenv/discovery/builtin.py
{ "start": 7564, "end": 9581 }
class ____: def __init__(self, pos: int, path: Path, env: Mapping[str, str]) -> None: self.pos = pos self.path = path self.env = env def __repr__(self) -> str: content = f"discover PATH[{self.pos}]={self.path}" if self.env.get("_VIRTUALENV_DEBUG"): # this is the over the board debug content += " with =>" for file_path in self.path.iterdir(): try: if file_path.is_dir(): continue if IS_WIN: pathext = self.env.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(";") if not any(file_path.name.upper().endswith(ext) for ext in pathext): continue elif not (file_path.stat().st_mode & os.X_OK): continue except OSError: pass content += " " content += file_path.name return content def path_exe_finder(spec: PythonSpec) -> Callable[[Path], Generator[tuple[Path, bool], None, None]]: """Given a spec, return a function that can be called on a path to find all matching files in it.""" pat = spec.generate_re(windows=sys.platform == "win32") direct = spec.str_spec if sys.platform == "win32": direct = f"{direct}.exe" def path_exes(path: Path) -> Generator[tuple[Path, bool], None, None]: # 4. then maybe it's something exact on PATH - if it was direct lookup implementation no longer counts direct_path = path / direct if direct_path.exists(): yield direct_path, False # 5. or from the spec we can deduce if a name on path matches for exe in path.iterdir(): match = pat.fullmatch(exe.name) if match: # the implementation must match when we find “python[ver]” yield exe.absolute(), match["impl"] == "python" return path_exes
LazyPathDump
python
django__django
django/template/base.py
{ "start": 9475, "end": 11649 }
class ____: """ A lightweight Template lookalike used for template partials. Wraps nodelist as a partial, in order to be able to bind context. """ def __init__(self, nodelist, origin, name, source_start=None, source_end=None): self.nodelist = nodelist self.origin = origin self.name = name # If available (debug mode), the absolute character offsets in the # template.source correspond to the full partial region. self._source_start = source_start self._source_end = source_end def get_exception_info(self, exception, token): template = self.origin.loader.get_template(self.origin.template_name) return template.get_exception_info(exception, token) def find_partial_source(self, full_source): if ( self._source_start is not None and self._source_end is not None and 0 <= self._source_start <= self._source_end <= len(full_source) ): return full_source[self._source_start : self._source_end] return "" @property def source(self): template = self.origin.loader.get_template(self.origin.template_name) if not template.engine.debug: warnings.warn( "PartialTemplate.source is only available when template " "debugging is enabled.", RuntimeWarning, skip_file_prefixes=django_file_prefixes(), ) return self.find_partial_source(template.source) def _render(self, context): return self.nodelist.render(context) def render(self, context): with context.render_context.push_state(self): if context.template is None: with context.bind_template(self): context.template_name = self.name return self._render(context) else: return self._render(context) def linebreak_iter(template_source): yield 0 p = template_source.find("\n") while p >= 0: yield p + 1 p = template_source.find("\n", p + 1) yield len(template_source) + 1
PartialTemplate
python
pypa__warehouse
warehouse/accounts/forms.py
{ "start": 13615, "end": 13751 }
class ____: """A mixin to catch spammers. This field should always be blank""" confirm_form = wtforms.StringField()
HoneypotMixin
python
paramiko__paramiko
paramiko/sftp.py
{ "start": 3251, "end": 6471 }
class ____: def __init__(self): self.logger = util.get_logger("paramiko.sftp") self.sock = None self.ultra_debug = False # ...internals... def _send_version(self): m = Message() m.add_int(_VERSION) self._send_packet(CMD_INIT, m) t, data = self._read_packet() if t != CMD_VERSION: raise SFTPError("Incompatible sftp protocol") version = struct.unpack(">I", data[:4])[0] # if version != _VERSION: # raise SFTPError('Incompatible sftp protocol') return version def _send_server_version(self): # winscp will freak out if the server sends version info before the # client finishes sending INIT. t, data = self._read_packet() if t != CMD_INIT: raise SFTPError("Incompatible sftp protocol") version = struct.unpack(">I", data[:4])[0] # advertise that we support "check-file" extension_pairs = ["check-file", "md5,sha1"] msg = Message() msg.add_int(_VERSION) msg.add(*extension_pairs) self._send_packet(CMD_VERSION, msg) return version def _log(self, level, msg, *args): self.logger.log(level, msg, *args) def _write_all(self, out): while len(out) > 0: n = self.sock.send(out) if n <= 0: raise EOFError() if n == len(out): return out = out[n:] return def _read_all(self, n): out = bytes() while n > 0: if isinstance(self.sock, socket.socket): # sometimes sftp is used directly over a socket instead of # through a paramiko channel. in this case, check periodically # if the socket is closed. (for some reason, recv() won't ever # return or raise an exception, but calling select on a closed # socket will.) while True: read, write, err = select.select([self.sock], [], [], 0.1) if len(read) > 0: x = self.sock.recv(n) break else: x = self.sock.recv(n) if len(x) == 0: raise EOFError() out += x n -= len(x) return out def _send_packet(self, t, packet): packet = packet.asbytes() out = struct.pack(">I", len(packet) + 1) + byte_chr(t) + packet if self.ultra_debug: self._log(DEBUG, util.format_binary(out, "OUT: ")) self._write_all(out) def _read_packet(self): x = self._read_all(4) # most sftp servers won't accept packets larger than about 32k, so # anything with the high byte set (> 16MB) is just garbage. if byte_ord(x[0]): raise SFTPError("Garbage packet received") size = struct.unpack(">I", x)[0] data = self._read_all(size) if self.ultra_debug: self._log(DEBUG, util.format_binary(data, "IN: ")) if size > 0: t = byte_ord(data[0]) return t, data[1:] return 0, bytes()
BaseSFTP
python
matplotlib__matplotlib
galleries/examples/event_handling/pong_sgskip.py
{ "start": 3364, "end": 10453 }
class ____: def __init__(self, ax): # create the initial line self.ax = ax ax.xaxis.set_visible(False) ax.set_xlim(0, 7) ax.yaxis.set_visible(False) ax.set_ylim(-1, 1) pad_a_x = 0 pad_b_x = .50 pad_a_y = pad_b_y = .30 pad_b_x += 6.3 # pads pA, = self.ax.barh(pad_a_y, .2, height=.3, color='k', alpha=.5, edgecolor='b', lw=2, label="Player B", animated=True) pB, = self.ax.barh(pad_b_y, .2, height=.3, left=pad_b_x, color='k', alpha=.5, edgecolor='r', lw=2, label="Player A", animated=True) # distractors self.x = np.arange(0, 2.22*np.pi, 0.01) self.line, = self.ax.plot(self.x, np.sin(self.x), "r", animated=True, lw=4) self.line2, = self.ax.plot(self.x, np.cos(self.x), "g", animated=True, lw=4) self.line3, = self.ax.plot(self.x, np.cos(self.x), "g", animated=True, lw=4) self.line4, = self.ax.plot(self.x, np.cos(self.x), "r", animated=True, lw=4) # center line self.centerline, = self.ax.plot([3.5, 3.5], [1, -1], 'k', alpha=.5, animated=True, lw=8) # puck (s) self.puckdisp = self.ax.scatter([1], [1], label='_nolegend_', s=200, c='g', alpha=.9, animated=True) self.canvas = self.ax.figure.canvas self.background = None self.cnt = 0 self.distract = True self.res = 100.0 self.on = False self.inst = True # show instructions from the beginning self.pads = [Pad(pA, pad_a_x, pad_a_y), Pad(pB, pad_b_x, pad_b_y, 'r')] self.pucks = [] self.i = self.ax.annotate(instructions, (.5, 0.5), name='monospace', verticalalignment='center', horizontalalignment='center', multialignment='left', xycoords='axes fraction', animated=False) self.canvas.mpl_connect('key_press_event', self.on_key_press) def draw(self): draw_artist = self.ax.draw_artist if self.background is None: self.background = self.canvas.copy_from_bbox(self.ax.bbox) # restore the clean slate background self.canvas.restore_region(self.background) # show the distractors if self.distract: self.line.set_ydata(np.sin(self.x + self.cnt/self.res)) self.line2.set_ydata(np.cos(self.x - self.cnt/self.res)) self.line3.set_ydata(np.tan(self.x + self.cnt/self.res)) self.line4.set_ydata(np.tan(self.x - self.cnt/self.res)) draw_artist(self.line) draw_artist(self.line2) draw_artist(self.line3) draw_artist(self.line4) # pucks and pads if self.on: self.ax.draw_artist(self.centerline) for pad in self.pads: pad.disp.set_y(pad.y) pad.disp.set_x(pad.x) self.ax.draw_artist(pad.disp) for puck in self.pucks: if puck.update(self.pads): # we only get here if someone scored self.pads[0].disp.set_label(f" {self.pads[0].score}") self.pads[1].disp.set_label(f" {self.pads[1].score}") self.ax.legend(loc='center', framealpha=.2, facecolor='0.5', prop=FontProperties(size='xx-large', weight='bold')) self.background = None self.ax.figure.canvas.draw_idle() return puck.disp.set_offsets([[puck.x, puck.y]]) self.ax.draw_artist(puck.disp) # just redraw the Axes rectangle self.canvas.blit(self.ax.bbox) self.canvas.flush_events() if self.cnt == 50000: # just so we don't get carried away print("...and you've been playing for too long!!!") plt.close() self.cnt += 1 def on_key_press(self, event): if event.key == '3': self.res *= 5.0 if event.key == '4': self.res /= 5.0 if event.key == 'e': self.pads[0].y += .1 if self.pads[0].y > 1 - .3: self.pads[0].y = 1 - .3 if event.key == 'd': self.pads[0].y -= .1 if self.pads[0].y < -1: self.pads[0].y = -1 if event.key == 'i': self.pads[1].y += .1 if self.pads[1].y > 1 - .3: self.pads[1].y = 1 - .3 if event.key == 'k': self.pads[1].y -= .1 if self.pads[1].y < -1: self.pads[1].y = -1 if event.key == 'a': self.pucks.append(Puck(self.puckdisp, self.pads[randint(2)], self.ax.bbox)) if event.key == 'A' and len(self.pucks): self.pucks.pop() if event.key == ' ' and len(self.pucks): self.pucks[0]._reset(self.pads[randint(2)]) if event.key == '1': for p in self.pucks: p._slower() if event.key == '2': for p in self.pucks: p._faster() if event.key == 'n': self.distract = not self.distract if event.key == 'g': self.on = not self.on if event.key == 't': self.inst = not self.inst self.i.set_visible(not self.i.get_visible()) self.background = None self.canvas.draw_idle() if event.key == 'q': plt.close() fig, ax = plt.subplots() canvas = ax.figure.canvas animation = Game(ax) # disable the default key bindings if fig.canvas.manager.key_press_handler_id is not None: canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id) # reset the blitting background on redraw def on_redraw(event): animation.background = None # bootstrap after the first draw def start_anim(event): canvas.mpl_disconnect(start_anim.cid) start_anim.timer.add_callback(animation.draw) start_anim.timer.start() canvas.mpl_connect('draw_event', on_redraw) start_anim.cid = canvas.mpl_connect('draw_event', start_anim) start_anim.timer = animation.canvas.new_timer(interval=1) tstart = time.time() plt.show() print('FPS: %f' % (animation.cnt/(time.time() - tstart))) # # %% # .. tags:: # # interactivity: event-handling # purpose: fun
Game
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataproc.py
{ "start": 66237, "end": 68974 }
class ____(GoogleCloudBaseOperator): """ Creates new workflow template. :param project_id: Optional. The ID of the Google Cloud project the cluster belongs to. :param region: Required. The Cloud Dataproc region in which to handle the request. :param template: The Dataproc workflow template to create. If a dict is provided, it must be of the same form as the protobuf message WorkflowTemplate. :param retry: A retry object used to retry requests. If ``None`` is specified, requests will not be retried. :param timeout: The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. :param metadata: Additional metadata that is provided to the method. """ template_fields: Sequence[str] = ("region", "template", "gcp_conn_id") template_fields_renderers = {"template": "json"} operator_extra_links = (DataprocWorkflowTemplateLink(),) def __init__( self, *, template: dict, region: str, project_id: str = PROVIDE_PROJECT_ID, retry: Retry | _MethodDefault = DEFAULT, timeout: float | None = None, metadata: Sequence[tuple[str, str]] = (), gcp_conn_id: str = "google_cloud_default", impersonation_chain: str | Sequence[str] | None = None, **kwargs, ): super().__init__(**kwargs) self.region = region self.template = template self.project_id = project_id self.retry = retry self.timeout = timeout self.metadata = metadata self.gcp_conn_id = gcp_conn_id self.impersonation_chain = impersonation_chain def execute(self, context: Context): hook = DataprocHook(gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain) self.log.info("Creating template") try: workflow = hook.create_workflow_template( region=self.region, template=self.template, project_id=self.project_id, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) self.log.info("Workflow %s created", workflow.name) except AlreadyExists: self.log.info("Workflow with given id already exists") project_id = self.project_id or hook.project_id if project_id: DataprocWorkflowTemplateLink.persist( context=context, workflow_template_id=self.template["id"], region=self.region, project_id=project_id, )
DataprocCreateWorkflowTemplateOperator
python
scipy__scipy
scipy/signal/tests/test_spectral.py
{ "start": 34476, "end": 36628 }
class ____: def test_average_all_segments(self): x = np.random.randn(1024) fs = 1.0 window = ('tukey', 0.25) nperseg = 16 noverlap = 2 f, _, P = spectrogram(x, fs, window, nperseg, noverlap) fw, Pw = welch(x, fs, window, nperseg, noverlap) assert_allclose(f, fw) assert_allclose(np.mean(P, axis=-1), Pw) def test_window_external(self): x = np.random.randn(1024) fs = 1.0 window = ('tukey', 0.25) nperseg = 16 noverlap = 2 f, _, P = spectrogram(x, fs, window, nperseg, noverlap) win = signal.get_window(('tukey', 0.25), 16) fe, _, Pe = spectrogram(x, fs, win, nperseg=None, noverlap=2) assert_array_equal(fe.shape, (9,)) # because win length used as nperseg assert_array_equal(Pe.shape, (9,73)) assert_raises(ValueError, spectrogram, x, fs, win, nperseg=8) # because nperseg != win.shape[-1] win_err = signal.get_window(('tukey', 0.25), 2048) assert_raises(ValueError, spectrogram, x, fs, win_err, nperseg=None) # win longer than signal def test_short_data(self): x = np.random.randn(1024) fs = 1.0 #for string-like window, input signal length < nperseg value gives #UserWarning, sets nperseg to x.shape[-1] f, _, p = spectrogram(x, fs, window=('tukey',0.25)) # default nperseg with warnings.catch_warnings(): warnings.filterwarnings( "ignore", "nperseg = 1025 is greater than input length = 1024, " "using nperseg = 1024", UserWarning, ) f1, _, p1 = spectrogram(x, fs, window=('tukey',0.25), nperseg=1025) # user-specified nperseg f2, _, p2 = spectrogram(x, fs, nperseg=256) # to compare w/default f3, _, p3 = spectrogram(x, fs, nperseg=1024) # compare w/user-spec'd assert_allclose(f, f2) assert_allclose(p, p2) assert_allclose(f1, f3) assert_allclose(p1, p3)
TestSpectrogram
python
scipy__scipy
benchmarks/benchmarks/special.py
{ "start": 470, "end": 705 }
class ____(Benchmark): def setup(self, *args): self.rand = np.random.rand(100000) def time_real(self, offset): erf(self.rand + offset) time_real.params = [0.0, 2.0] time_real.param_names = ['offset']
Erf
python
aio-libs__aiohttp
aiohttp/payload.py
{ "start": 33497, "end": 33849 }
class ____(IOBasePayload): _value: io.BufferedIOBase # _autoclose = False (inherited) - Has buffered file handle that needs explicit closing def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: self._set_or_restore_start_position() return self._value.read().decode(encoding, errors)
BufferedReaderPayload
python
mlflow__mlflow
mlflow/tracing/processor/otel.py
{ "start": 626, "end": 3488 }
class ____(OtelMetricsMixin, BatchSpanProcessor): """ SpanProcessor implementation to export MLflow traces to a OpenTelemetry collector. Extending OpenTelemetry BatchSpanProcessor to add some custom hooks to be executed when a span is started or ended (before exporting). """ def __init__(self, span_exporter: SpanExporter, export_metrics: bool) -> None: super().__init__(span_exporter) self._export_metrics = export_metrics # In opentelemetry-sdk 1.34.0, the `span_exporter` field was removed from the # `BatchSpanProcessor` class. # https://github.com/open-telemetry/opentelemetry-python/issues/4616 # # The `span_exporter` field was restored as a property in 1.34.1 # https://github.com/open-telemetry/opentelemetry-python/pull/4621 # # We use a try-except block to maintain compatibility with both versions. try: self.span_exporter = span_exporter except AttributeError: pass # Only register traces with trace manager when NOT in dual export mode # In dual export mode, MLflow span processors handle trace registration self._should_register_traces = not MLFLOW_TRACE_ENABLE_OTLP_DUAL_EXPORT.get() if self._should_register_traces: self._trace_manager = InMemoryTraceManager.get_instance() def on_start(self, span: OTelReadableSpan, parent_context=None): if self._should_register_traces: if not span.parent: trace_info = self._create_trace_info(span) trace_id = trace_info.trace_id self._trace_manager.register_trace(span.context.trace_id, trace_info) else: trace_id = self._trace_manager.get_mlflow_trace_id_from_otel_id( span.context.trace_id ) self._trace_manager.register_span(create_mlflow_span(span, trace_id)) super().on_start(span, parent_context) def on_end(self, span: OTelReadableSpan): if self._export_metrics: self.record_metrics_for_span(span) if self._should_register_traces and not span.parent: self._trace_manager.pop_trace(span.context.trace_id) super().on_end(span) def _create_trace_info(self, span: OTelReadableSpan) -> TraceInfo: """Create a TraceInfo object from an OpenTelemetry span.""" return TraceInfo( trace_id=generate_trace_id_v3(span), trace_location=TraceLocation.from_experiment_id(None), request_time=span.start_time // 1_000_000, # nanosecond to millisecond execution_duration=None, state=TraceState.IN_PROGRESS, trace_metadata={TRACE_SCHEMA_VERSION_KEY: str(TRACE_SCHEMA_VERSION)}, tags={}, )
OtelSpanProcessor
python
python-poetry__poetry
src/poetry/console/commands/self/show/plugins.py
{ "start": 301, "end": 1063 }
class ____: package: Package plugins: list[metadata.EntryPoint] = dataclasses.field(default_factory=list) application_plugins: list[metadata.EntryPoint] = dataclasses.field( default_factory=list ) def append(self, entry_point: metadata.EntryPoint) -> None: from poetry.plugins.application_plugin import ApplicationPlugin from poetry.plugins.plugin import Plugin group = entry_point.group if group == ApplicationPlugin.group: self.application_plugins.append(entry_point) elif group == Plugin.group: self.plugins.append(entry_point) else: name = entry_point.name raise ValueError(f"Unknown plugin group ({group}) for {name}")
PluginPackage
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vector_index.py
{ "start": 8466, "end": 8671 }
class ____(_QuantizerConfigUpdate): enabled: Optional[bool] rescoreLimit: Optional[int] bits: Optional[int] @staticmethod def quantizer_name() -> str: return "rq"
_RQConfigUpdate
python
numba__numba
numba/core/ir.py
{ "start": 9650, "end": 10536 }
class ____(EqualityCheckMixin, AbstractRHS): """ Base class for all IR instructions. """ def list_vars(self): """ List the variables used (read or written) by the instruction. """ raise NotImplementedError def _rec_list_vars(self, val): """ A recursive helper used to implement list_vars() in subclasses. """ if isinstance(val, Var): return [val] elif isinstance(val, Inst): return val.list_vars() elif isinstance(val, (list, tuple)): lst = [] for v in val: lst.extend(self._rec_list_vars(v)) return lst elif isinstance(val, dict): lst = [] for v in val.values(): lst.extend(self._rec_list_vars(v)) return lst else: return []
Inst
python
django__django
tests/admin_views/models.py
{ "start": 17010, "end": 17194 }
class ____(models.Model): name = models.CharField(max_length=20) album = models.ForeignKey(Album, on_delete=models.RESTRICT) def __str__(self): return self.name
Song
python
django__django
tests/model_fields/test_booleanfield.py
{ "start": 252, "end": 4213 }
class ____(TestCase): def _test_get_prep_value(self, f): self.assertIs(f.get_prep_value(True), True) self.assertIs(f.get_prep_value("1"), True) self.assertIs(f.get_prep_value(1), True) self.assertIs(f.get_prep_value(False), False) self.assertIs(f.get_prep_value("0"), False) self.assertIs(f.get_prep_value(0), False) self.assertIsNone(f.get_prep_value(None)) def _test_to_python(self, f): self.assertIs(f.to_python(1), True) self.assertIs(f.to_python(0), False) def test_booleanfield_get_prep_value(self): self._test_get_prep_value(models.BooleanField()) def test_nullbooleanfield_get_prep_value(self): self._test_get_prep_value(models.BooleanField(null=True)) def test_booleanfield_to_python(self): self._test_to_python(models.BooleanField()) def test_nullbooleanfield_to_python(self): self._test_to_python(models.BooleanField(null=True)) def test_booleanfield_choices_blank(self): """ BooleanField with choices and defaults doesn't generate a formfield with the blank option (#9640, #10549). """ choices = [(1, "Si"), (2, "No")] f = models.BooleanField(choices=choices, default=1, null=False) self.assertEqual(f.formfield().choices, choices) def test_booleanfield_choices_blank_desired(self): """ BooleanField with choices and no default should generated a formfield with the blank option. """ choices = [(1, "Si"), (2, "No")] f = models.BooleanField(choices=choices) self.assertEqual(f.formfield().choices, [("", "---------")] + choices) def test_nullbooleanfield_formfield(self): f = models.BooleanField(null=True) self.assertIsInstance(f.formfield(), forms.NullBooleanField) def test_return_type(self): b = BooleanModel.objects.create(bfield=True) b.refresh_from_db() self.assertIs(b.bfield, True) b2 = BooleanModel.objects.create(bfield=False) b2.refresh_from_db() self.assertIs(b2.bfield, False) b3 = NullBooleanModel.objects.create(nbfield=True) b3.refresh_from_db() self.assertIs(b3.nbfield, True) b4 = NullBooleanModel.objects.create(nbfield=False) b4.refresh_from_db() self.assertIs(b4.nbfield, False) def test_select_related(self): """ Boolean fields retrieved via select_related() should return booleans. """ bmt = BooleanModel.objects.create(bfield=True) bmf = BooleanModel.objects.create(bfield=False) nbmt = NullBooleanModel.objects.create(nbfield=True) nbmf = NullBooleanModel.objects.create(nbfield=False) m1 = FksToBooleans.objects.create(bf=bmt, nbf=nbmt) m2 = FksToBooleans.objects.create(bf=bmf, nbf=nbmf) # select_related('fk_field_name') ma = FksToBooleans.objects.select_related("bf").get(pk=m1.id) self.assertIs(ma.bf.bfield, True) self.assertIs(ma.nbf.nbfield, True) # select_related() mb = FksToBooleans.objects.select_related().get(pk=m1.id) mc = FksToBooleans.objects.select_related().get(pk=m2.id) self.assertIs(mb.bf.bfield, True) self.assertIs(mb.nbf.nbfield, True) self.assertIs(mc.bf.bfield, False) self.assertIs(mc.nbf.nbfield, False) def test_null_default(self): """ A BooleanField defaults to None, which isn't a valid value (#15124). """ boolean_field = BooleanModel._meta.get_field("bfield") self.assertFalse(boolean_field.has_default()) b = BooleanModel() self.assertIsNone(b.bfield) with transaction.atomic(): with self.assertRaises(IntegrityError): b.save() nb = NullBooleanModel() self.assertIsNone(nb.nbfield) nb.save() # no error
BooleanFieldTests
python
PyCQA__pylint
tests/functional/a/alternative/alternative_union_syntax.py
{ "start": 782, "end": 986 }
class ____(int): pass Alias2 = CustomCls | str var2 = CustomCls(1) | int(2) # Check typing.NamedTuple CustomNamedTuple = typing.NamedTuple( "CustomNamedTuple", [("my_var", int | str)])
CustomCls
python
pandas-dev__pandas
pandas/tests/extension/array_with_attr/array.py
{ "start": 378, "end": 702 }
class ____(ExtensionDtype): type = float name = "float_attr" na_value = np.nan def construct_array_type(self) -> type_t[FloatAttrArray]: """ Return the array type associated with this dtype. Returns ------- type """ return FloatAttrArray
FloatAttrDtype
python
openai__openai-python
src/openai/types/beta/assistant_stream_event.py
{ "start": 3750, "end": 3907 }
class ____(BaseModel): data: RunStep """Represents a step in execution of a run.""" event: Literal["thread.run.step.created"]
ThreadRunStepCreated
python
ipython__ipython
IPython/core/display.py
{ "start": 8548, "end": 12783 }
class ____: """An object that wraps data to be displayed.""" _read_flags = 'r' _show_mem_addr = False metadata = None def __init__(self, data=None, url=None, filename=None, metadata=None): """Create a display object given raw data. When this object is returned by an expression or passed to the display function, it will result in the data being displayed in the frontend. The MIME type of the data should match the subclasses used, so the Png subclass should be used for 'image/png' data. If the data is a URL, the data will first be downloaded and then displayed. Parameters ---------- data : unicode, str or bytes The raw data or a URL or file to load the data from url : unicode A URL to download the data from. filename : unicode Path to a local file to load the data from. metadata : dict Dict of metadata associated to be the object when displayed """ if isinstance(data, (Path, PurePath)): data = str(data) if data is not None and isinstance(data, str): if data.startswith('http') and url is None: url = data filename = None data = None elif _safe_exists(data) and filename is None: url = None filename = data data = None self.url = url self.filename = filename # because of @data.setter methods in # subclasses ensure url and filename are set # before assigning to self.data self.data = data if metadata is not None: self.metadata = metadata elif self.metadata is None: self.metadata = {} self.reload() self._check_data() def __repr__(self): if not self._show_mem_addr: cls = self.__class__ r = "<%s.%s object>" % (cls.__module__, cls.__name__) else: r = super(DisplayObject, self).__repr__() return r def _check_data(self): """Override in subclasses if there's something to check.""" pass def _data_and_metadata(self): """shortcut for returning metadata with shape information, if defined""" if self.metadata: return self.data, deepcopy(self.metadata) else: return self.data def reload(self): """Reload the raw data from file or URL.""" if self.filename is not None: encoding = None if "b" in self._read_flags else "utf-8" with open(self.filename, self._read_flags, encoding=encoding) as f: self.data = f.read() elif self.url is not None: # Deferred import from urllib.request import urlopen response = urlopen(self.url) data = response.read() # extract encoding from header, if there is one: encoding = None if 'content-type' in response.headers: for sub in response.headers['content-type'].split(';'): sub = sub.strip() if sub.startswith('charset'): encoding = sub.split('=')[-1].strip() break if 'content-encoding' in response.headers: # TODO: do deflate? if 'gzip' in response.headers['content-encoding']: import gzip from io import BytesIO # assume utf-8 if encoding is not specified with gzip.open( BytesIO(data), "rt", encoding=encoding or "utf-8" ) as fp: encoding = None data = fp.read() # decode data, if an encoding was specified # We only touch self.data once since # subclasses such as SVG have @data.setter methods # that transform self.data into ... well svg. if encoding: self.data = data.decode(encoding, 'replace') else: self.data = data
DisplayObject
python
Textualize__textual
docs/examples/how-to/layout03.py
{ "start": 530, "end": 712 }
class ____(Screen): def compose(self) -> ComposeResult: yield Header(id="Header") yield Footer(id="Footer") yield ColumnsContainer(id="Columns")
TweetScreen
python
sqlalchemy__sqlalchemy
test/orm/declarative/test_clsregistry.py
{ "start": 902, "end": 947 }
class ____: parent = "some_parent"
MockProp
python
django__django
tests/apps/tests.py
{ "start": 15545, "end": 19535 }
class ____(SimpleTestCase): """Unit tests for AppConfig class.""" def test_path_set_explicitly(self): """If subclass sets path as class attr, no module attributes needed.""" class MyAppConfig(AppConfig): path = "foo" ac = MyAppConfig("label", Stub()) self.assertEqual(ac.path, "foo") def test_explicit_path_overrides(self): """If path set as class attr, overrides __path__ and __file__.""" class MyAppConfig(AppConfig): path = "foo" ac = MyAppConfig("label", Stub(__path__=["a"], __file__="b/__init__.py")) self.assertEqual(ac.path, "foo") def test_dunder_path(self): """ If single element in __path__, use it (in preference to __file__). """ ac = AppConfig("label", Stub(__path__=["a"], __file__="b/__init__.py")) self.assertEqual(ac.path, "a") def test_no_dunder_path_fallback_to_dunder_file(self): """If there is no __path__ attr, use __file__.""" ac = AppConfig("label", Stub(__file__="b/__init__.py")) self.assertEqual(ac.path, "b") def test_empty_dunder_path_fallback_to_dunder_file(self): """If the __path__ attr is empty, use __file__ if set.""" ac = AppConfig("label", Stub(__path__=[], __file__="b/__init__.py")) self.assertEqual(ac.path, "b") def test_multiple_dunder_path_fallback_to_dunder_file(self): """If the __path__ attr is length>1, use __file__ if set.""" ac = AppConfig("label", Stub(__path__=["a", "b"], __file__="c/__init__.py")) self.assertEqual(ac.path, "c") def test_no_dunder_path_or_dunder_file(self): """If there is no __path__ or __file__, raise ImproperlyConfigured.""" with self.assertRaises(ImproperlyConfigured): AppConfig("label", Stub()) def test_empty_dunder_path_no_dunder_file(self): """If the __path__ attr is empty and there is no __file__, raise.""" with self.assertRaises(ImproperlyConfigured): AppConfig("label", Stub(__path__=[])) def test_multiple_dunder_path_no_dunder_file(self): """If the __path__ attr is length>1 and there is no __file__, raise.""" with self.assertRaises(ImproperlyConfigured): AppConfig("label", Stub(__path__=["a", "b"])) def test_duplicate_dunder_path_no_dunder_file(self): """ If the __path__ attr contains duplicate paths and there is no __file__, they duplicates should be deduplicated (#25246). """ ac = AppConfig("label", Stub(__path__=["a", "a"])) self.assertEqual(ac.path, "a") def test_repr(self): ac = AppConfig("label", Stub(__path__=["a"])) self.assertEqual(repr(ac), "<AppConfig: label>") def test_invalid_label(self): class MyAppConfig(AppConfig): label = "invalid.label" msg = "The app label 'invalid.label' is not a valid Python identifier." with self.assertRaisesMessage(ImproperlyConfigured, msg): MyAppConfig("test_app", Stub()) @override_settings( INSTALLED_APPS=["apps.apps.ModelPKAppsConfig"], DEFAULT_AUTO_FIELD="django.db.models.SmallAutoField", ) def test_app_default_auto_field(self): apps_config = apps.get_app_config("apps") self.assertEqual( apps_config.default_auto_field, "django.db.models.BigAutoField", ) self.assertIs(apps_config._is_default_auto_field_overridden, True) @override_settings( INSTALLED_APPS=["apps.apps.PlainAppsConfig"], DEFAULT_AUTO_FIELD="django.db.models.SmallAutoField", ) def test_default_auto_field_setting(self): apps_config = apps.get_app_config("apps") self.assertEqual( apps_config.default_auto_field, "django.db.models.SmallAutoField", ) self.assertIs(apps_config._is_default_auto_field_overridden, False)
AppConfigTests
python
django__django
tests/annotations/models.py
{ "start": 1129, "end": 1632 }
class ____(models.Model): # The order of these fields matter, do not change. Certain backends # rely on field ordering to perform database conversions, and this # model helps to test that. first_name = models.CharField(max_length=20) manager = models.BooleanField(default=False) last_name = models.CharField(max_length=20) store = models.ForeignKey(Store, models.CASCADE) age = models.IntegerField() salary = models.DecimalField(max_digits=8, decimal_places=2)
Employee
python
numba__numba
numba/cuda/cudadecl.py
{ "start": 1040, "end": 1879 }
class ____(CallableTemplate): def generic(self): def typer(shape, dtype): # Only integer literals and tuples of integer literals are valid # shapes if isinstance(shape, types.Integer): if not isinstance(shape, types.IntegerLiteral): return None elif isinstance(shape, (types.Tuple, types.UniTuple)): if any([not isinstance(s, types.IntegerLiteral) for s in shape]): return None else: return None ndim = parse_shape(shape) nb_dtype = parse_dtype(dtype) if nb_dtype is not None and ndim is not None: return types.Array(dtype=nb_dtype, ndim=ndim, layout='C') return typer @register
Cuda_array_decl
python
django__django
tests/invalid_models_tests/test_ordinary_fields.py
{ "start": 3082, "end": 15833 }
class ____(TestCase): def test_valid_field(self): class Model(models.Model): field = models.CharField( max_length=255, choices=[ ("1", "item1"), ("2", "item2"), ], db_index=True, ) field = Model._meta.get_field("field") self.assertEqual(field.check(), []) def test_missing_max_length(self): class Model(models.Model): field = models.CharField() field = Model._meta.get_field("field") expected = ( [] if connection.features.supports_unlimited_charfield else [ Error( "CharFields must define a 'max_length' attribute.", obj=field, id="fields.E120", ), ] ) self.assertEqual(field.check(), expected) def test_negative_max_length(self): class Model(models.Model): field = models.CharField(max_length=-1) field = Model._meta.get_field("field") self.assertEqual( field.check(), [ Error( "'max_length' must be a positive integer.", obj=field, id="fields.E121", ), ], ) def test_bad_max_length_value(self): class Model(models.Model): field = models.CharField(max_length="bad") field = Model._meta.get_field("field") self.assertEqual( field.check(), [ Error( "'max_length' must be a positive integer.", obj=field, id="fields.E121", ), ], ) def test_str_max_length_value(self): class Model(models.Model): field = models.CharField(max_length="20") field = Model._meta.get_field("field") self.assertEqual( field.check(), [ Error( "'max_length' must be a positive integer.", obj=field, id="fields.E121", ), ], ) def test_str_max_length_type(self): class Model(models.Model): field = models.CharField(max_length=True) field = Model._meta.get_field("field") self.assertEqual( field.check(), [ Error( "'max_length' must be a positive integer.", obj=field, id="fields.E121", ), ], ) def test_non_iterable_choices(self): class Model(models.Model): field = models.CharField(max_length=10, choices="bad") field = Model._meta.get_field("field") self.assertEqual( field.check(), [ Error( "'choices' must be a mapping (e.g. a dictionary) or an " "ordered iterable (e.g. a list or tuple, but not a set).", obj=field, id="fields.E004", ), ], ) def test_non_iterable_choices_two_letters(self): """Two letters isn't a valid choice pair.""" class Model(models.Model): field = models.CharField(max_length=10, choices=["ab"]) field = Model._meta.get_field("field") self.assertEqual( field.check(), [ Error( "'choices' must be a mapping of actual values to human readable " "names or an iterable containing (actual value, human readable " "name) tuples.", obj=field, id="fields.E005", ), ], ) def test_iterable_of_iterable_choices(self): class ThingItem: def __init__(self, value, display): self.value = value self.display = display def __iter__(self): return iter((self.value, self.display)) def __len__(self): return 2 class Things: def __iter__(self): return iter((ThingItem(1, 2), ThingItem(3, 4))) class ThingWithIterableChoices(models.Model): thing = models.CharField(max_length=100, blank=True, choices=Things()) self.assertEqual(ThingWithIterableChoices._meta.get_field("thing").check(), []) def test_choices_containing_non_pairs(self): class Model(models.Model): field = models.CharField(max_length=10, choices=[(1, 2, 3), (1, 2, 3)]) class Model2(models.Model): field = models.IntegerField(choices=[0]) for model in (Model, Model2): with self.subTest(model.__name__): field = model._meta.get_field("field") self.assertEqual( field.check(), [ Error( "'choices' must be a mapping of actual values to human " "readable names or an iterable containing (actual value, " "human readable name) tuples.", obj=field, id="fields.E005", ), ], ) def test_choices_containing_lazy(self): class Model(models.Model): field = models.CharField( max_length=10, choices=[["1", _("1")], ["2", _("2")]] ) self.assertEqual(Model._meta.get_field("field").check(), []) def test_lazy_choices(self): class Model(models.Model): field = models.CharField( max_length=10, choices=lazy(lambda: [[1, "1"], [2, "2"]], tuple)() ) self.assertEqual(Model._meta.get_field("field").check(), []) def test_choices_named_group(self): class Model(models.Model): field = models.CharField( max_length=10, choices=[ ["knights", [["L", "Lancelot"], ["G", "Galahad"]]], ["wizards", [["T", "Tim the Enchanter"]]], ["R", "Random character"], ], ) self.assertEqual(Model._meta.get_field("field").check(), []) def test_choices_named_group_non_pairs(self): class Model(models.Model): field = models.CharField( max_length=10, choices=[["knights", [["L", "Lancelot", "Du Lac"]]]], ) field = Model._meta.get_field("field") self.assertEqual( field.check(), [ Error( "'choices' must be a mapping of actual values to human readable " "names or an iterable containing (actual value, human readable " "name) tuples.", obj=field, id="fields.E005", ), ], ) def test_choices_named_group_bad_structure(self): class Model(models.Model): field = models.CharField( max_length=10, choices=[ [ "knights", [ ["Noble", [["G", "Galahad"]]], ["Combative", [["L", "Lancelot"]]], ], ], ], ) field = Model._meta.get_field("field") self.assertEqual( field.check(), [ Error( "'choices' must be a mapping of actual values to human readable " "names or an iterable containing (actual value, human readable " "name) tuples.", obj=field, id="fields.E005", ), ], ) def test_choices_named_group_lazy(self): class Model(models.Model): field = models.CharField( max_length=10, choices=[ [_("knights"), [["L", _("Lancelot")], ["G", _("Galahad")]]], ["R", _("Random character")], ], ) self.assertEqual(Model._meta.get_field("field").check(), []) def test_choices_in_max_length(self): class Model(models.Model): field = models.CharField( max_length=2, choices=[("ABC", "Value Too Long!"), ("OK", "Good")], ) group = models.CharField( max_length=2, choices=[ ("Nested", [("OK", "Good"), ("Longer", "Longer")]), ("Grouped", [("Bad", "Bad")]), ], ) for name, choice_max_length in (("field", 3), ("group", 6)): with self.subTest(name): field = Model._meta.get_field(name) self.assertEqual( field.check(), [ Error( "'max_length' is too small to fit the longest value " "in 'choices' (%d characters)." % choice_max_length, obj=field, id="fields.E009", ), ], ) def test_bad_db_index_value(self): class Model(models.Model): field = models.CharField(max_length=10, db_index="bad") field = Model._meta.get_field("field") self.assertEqual( field.check(), [ Error( "'db_index' must be None, True or False.", obj=field, id="fields.E006", ), ], ) def test_bad_validators(self): class Model(models.Model): field = models.CharField(max_length=10, validators=[True]) field = Model._meta.get_field("field") self.assertEqual( field.check(), [ Error( "All 'validators' must be callable.", hint=( "validators[0] (True) isn't a function or instance of a " "validator class." ), obj=field, id="fields.E008", ), ], ) @unittest.skipUnless(connection.vendor == "mysql", "Test valid only for MySQL") def test_too_long_char_field_under_mysql(self): from django.db.backends.mysql.validation import DatabaseValidation class Model(models.Model): field = models.CharField(unique=True, max_length=256) field = Model._meta.get_field("field") validator = DatabaseValidation(connection=connection) self.assertEqual( validator.check_field(field), [ DjangoWarning( "%s may not allow unique CharFields to have a max_length > " "255." % connection.display_name, hint=( "See: https://docs.djangoproject.com/en/%s/ref/databases/" "#mysql-character-fields" % get_docs_version() ), obj=field, id="mysql.W003", ) ], ) def test_db_collation(self): class Model(models.Model): field = models.CharField(max_length=100, db_collation="anything") field = Model._meta.get_field("field") error = Error( "%s does not support a database collation on CharFields." % connection.display_name, id="fields.E190", obj=field, ) expected = ( [] if connection.features.supports_collation_on_charfield else [error] ) self.assertEqual(field.check(databases=self.databases), expected) def test_db_collation_required_db_features(self): class Model(models.Model): field = models.CharField(max_length=100, db_collation="anything") class Meta: required_db_features = {"supports_collation_on_charfield"} field = Model._meta.get_field("field") self.assertEqual(field.check(databases=self.databases), []) @isolate_apps("invalid_models_tests")
CharFieldTests
python
pandas-dev__pandas
pandas/tests/scalar/test_nat.py
{ "start": 495, "end": 19025 }
class ____: def test_repr(self): assert repr(NaT) == "NaT" def test_str(self): assert str(NaT) == "NaT" def test_isoformat(self): assert NaT.isoformat() == "NaT" @pytest.mark.parametrize( "nat,idx", [ (Timestamp("NaT"), DatetimeArray), (Timedelta("NaT"), TimedeltaArray), (Period("NaT", freq="M"), PeriodArray), ], ) def test_nat_fields(nat, idx): for field in idx._field_ops: # weekday is a property of DTI, but a method # on NaT/Timestamp for compat with datetime if field == "weekday": continue result = getattr(NaT, field) assert np.isnan(result) result = getattr(nat, field) assert np.isnan(result) for field in idx._bool_ops: result = getattr(NaT, field) assert result is False result = getattr(nat, field) assert result is False def test_nat_vector_field_access(): idx = DatetimeIndex(["1/1/2000", None, None, "1/4/2000"]) for field in DatetimeArray._field_ops: # weekday is a property of DTI, but a method # on NaT/Timestamp for compat with datetime if field == "weekday": continue result = getattr(idx, field) expected = Index([getattr(x, field) for x in idx]) tm.assert_index_equal(result, expected) ser = Series(idx) for field in DatetimeArray._field_ops: # weekday is a property of DTI, but a method # on NaT/Timestamp for compat with datetime if field == "weekday": continue result = getattr(ser.dt, field) expected = [getattr(x, field) for x in idx] tm.assert_series_equal(result, Series(expected)) for field in DatetimeArray._bool_ops: result = getattr(ser.dt, field) expected = [getattr(x, field) for x in idx] tm.assert_series_equal(result, Series(expected)) @pytest.mark.parametrize("klass", [Timestamp, Timedelta, Period]) @pytest.mark.parametrize( "value", [None, np.nan, iNaT, float("nan"), NaT, "NaT", "nat", "", "NAT"] ) def test_identity(klass, value): assert klass(value) is NaT @pytest.mark.parametrize("klass", [Timestamp, Timedelta]) @pytest.mark.parametrize("method", ["round", "floor", "ceil"]) @pytest.mark.parametrize("freq", ["s", "5s", "min", "5min", "h", "5h"]) def test_round_nat(klass, method, freq): # see gh-14940 ts = klass("nat") round_method = getattr(ts, method) assert round_method(freq) is ts @pytest.mark.parametrize( "method", [ "astimezone", "combine", "ctime", "dst", "fromordinal", "fromtimestamp", "fromisocalendar", "isocalendar", "strftime", "strptime", "time", "timestamp", "timetuple", "timetz", "toordinal", "tzname", "utcfromtimestamp", "utcnow", "utcoffset", "utctimetuple", ], ) def test_nat_methods_raise(method): # see gh-9513, gh-17329 msg = f"NaTType does not support {method}" with pytest.raises(ValueError, match=msg): getattr(NaT, method)() @pytest.mark.parametrize("method", ["weekday", "isoweekday"]) def test_nat_methods_nan(method): # see gh-9513, gh-17329 assert np.isnan(getattr(NaT, method)()) @pytest.mark.parametrize( "method", ["date", "now", "replace", "today", "tz_convert", "tz_localize"] ) def test_nat_methods_nat(method): # see gh-8254, gh-9513, gh-17329 assert getattr(NaT, method)() is NaT @pytest.mark.parametrize( "get_nat", [lambda x: NaT, lambda x: Timedelta(x), lambda x: Timestamp(x)] ) def test_nat_iso_format(get_nat): # see gh-12300 assert get_nat("NaT").isoformat() == "NaT" assert get_nat("NaT").isoformat(timespec="nanoseconds") == "NaT" @pytest.mark.parametrize( "klass,expected", [ (Timestamp, ["normalize", "to_julian_date", "to_period", "unit"]), ( Timedelta, [ "components", "resolution_string", "to_pytimedelta", "to_timedelta64", "unit", "view", ], ), ], ) def test_missing_public_nat_methods(klass, expected): # see gh-17327 # # NaT should have *most* of the Timestamp and Timedelta methods. # Here, we check which public methods NaT does not have. We # ignore any missing private methods. nat_names = dir(NaT) klass_names = dir(klass) missing = [x for x in klass_names if x not in nat_names and not x.startswith("_")] missing.sort() assert missing == expected def _get_overlap_public_nat_methods(klass, as_tuple=False): """ Get overlapping public methods between NaT and another class. Parameters ---------- klass : type The class to compare with NaT as_tuple : bool, default False Whether to return a list of tuples of the form (klass, method). Returns ------- overlap : list """ nat_names = dir(NaT) klass_names = dir(klass) overlap = [ x for x in nat_names if x in klass_names and not x.startswith("_") and callable(getattr(klass, x)) ] # Timestamp takes precedence over Timedelta in terms of overlap. if klass is Timedelta: ts_names = dir(Timestamp) overlap = [x for x in overlap if x not in ts_names] if as_tuple: overlap = [(klass, method) for method in overlap] overlap.sort() return overlap @pytest.mark.parametrize( "klass,expected", [ ( Timestamp, [ "as_unit", "astimezone", "ceil", "combine", "ctime", "date", "day_name", "dst", "floor", "fromisocalendar", "fromisoformat", "fromordinal", "fromtimestamp", "isocalendar", "isoformat", "isoweekday", "month_name", "now", "replace", "round", "strftime", "strptime", "time", "timestamp", "timetuple", "timetz", "to_datetime64", "to_numpy", "to_pydatetime", "today", "toordinal", "tz_convert", "tz_localize", "tzname", "utcfromtimestamp", "utcnow", "utcoffset", "utctimetuple", "weekday", ], ), (Timedelta, ["total_seconds"]), ], ) def test_overlap_public_nat_methods(klass, expected): # see gh-17327 # # NaT should have *most* of the Timestamp and Timedelta methods. # In case when Timestamp, Timedelta, and NaT are overlap, the overlap # is considered to be with Timestamp and NaT, not Timedelta. assert _get_overlap_public_nat_methods(klass) == expected @pytest.mark.parametrize( "compare", ( _get_overlap_public_nat_methods(Timestamp, True) + _get_overlap_public_nat_methods(Timedelta, True) ), ids=lambda x: f"{x[0].__name__}.{x[1]}", ) def test_nat_doc_strings(compare): # see gh-17327 # # The docstrings for overlapping methods should match. klass, method = compare klass_doc = getattr(klass, method).__doc__ if klass == Timestamp and method == "isoformat": pytest.skip( "Ignore differences with Timestamp.isoformat() as they're intentional" ) if method == "to_numpy": # GH#44460 can return either dt64 or td64 depending on dtype, # different docstring is intentional pytest.skip(f"different docstring for {method} is intentional") nat_doc = getattr(NaT, method).__doc__ assert klass_doc == nat_doc _ops = { "left_plus_right": lambda a, b: a + b, "right_plus_left": lambda a, b: b + a, "left_minus_right": lambda a, b: a - b, "right_minus_left": lambda a, b: b - a, "left_times_right": lambda a, b: a * b, "right_times_left": lambda a, b: b * a, "left_div_right": lambda a, b: a / b, "right_div_left": lambda a, b: b / a, } @pytest.mark.parametrize("op_name", list(_ops.keys())) @pytest.mark.parametrize( "value,val_type", [ (2, "scalar"), (1.5, "floating"), (np.nan, "floating"), ("foo", "str"), (timedelta(3600), "timedelta"), (Timedelta("5s"), "timedelta"), (datetime(2014, 1, 1), "timestamp"), (Timestamp("2014-01-01"), "timestamp"), (Timestamp("2014-01-01", tz="UTC"), "timestamp"), (Timestamp("2014-01-01", tz="US/Eastern"), "timestamp"), (datetime(2014, 1, 1).astimezone(zoneinfo.ZoneInfo("Asia/Tokyo")), "timestamp"), ], ) def test_nat_arithmetic_scalar(op_name, value, val_type): # see gh-6873 invalid_ops = { "scalar": {"right_div_left"}, "floating": { "right_div_left", "left_minus_right", "right_minus_left", "left_plus_right", "right_plus_left", }, "str": set(_ops.keys()), "timedelta": {"left_times_right", "right_times_left"}, "timestamp": { "left_times_right", "right_times_left", "left_div_right", "right_div_left", }, } op = _ops[op_name] if op_name in invalid_ops.get(val_type, set()): if ( val_type == "timedelta" and "times" in op_name and isinstance(value, Timedelta) ): typs = "(Timedelta|NaTType)" msg = rf"unsupported operand type\(s\) for \*: '{typs}' and '{typs}'" elif val_type == "str": # un-specific check here because the message comes from str # and varies by method msg = "|".join( [ "can only concatenate str", "unsupported operand type", "can't multiply sequence", "Can't convert 'NaTType'", "must be str, not NaTType", ] ) else: msg = "unsupported operand type" with pytest.raises(TypeError, match=msg): op(NaT, value) else: if val_type == "timedelta" and "div" in op_name: expected = np.nan else: expected = NaT assert op(NaT, value) is expected @pytest.mark.parametrize( "val,expected", [(np.nan, NaT), (NaT, np.nan), (np.timedelta64("NaT"), np.nan)] ) def test_nat_rfloordiv_timedelta(val, expected): # see gh-#18846 # # See also test_timedelta.TestTimedeltaArithmetic.test_floordiv td = Timedelta(hours=3, minutes=4) assert td // val is expected @pytest.mark.parametrize( "op_name", ["left_plus_right", "right_plus_left", "left_minus_right", "right_minus_left"], ) @pytest.mark.parametrize( "value", [ DatetimeIndex(["2011-01-01", "2011-01-02"], dtype="M8[ns]", name="x"), DatetimeIndex( ["2011-01-01", "2011-01-02"], dtype="M8[ns, US/Eastern]", name="x" ), DatetimeArray._from_sequence(["2011-01-01", "2011-01-02"], dtype="M8[ns]"), DatetimeArray._from_sequence( ["2011-01-01", "2011-01-02"], dtype=DatetimeTZDtype(tz="US/Pacific") ), TimedeltaIndex(["1 day", "2 day"], name="x"), ], ) def test_nat_arithmetic_index(op_name, value): # see gh-11718 exp_name = "x" exp_data = [NaT] * 2 if value.dtype.kind == "M" and "plus" in op_name: expected = DatetimeIndex(exp_data, tz=value.tz, name=exp_name) else: expected = TimedeltaIndex(exp_data, name=exp_name) expected = expected.as_unit(value.unit) if not isinstance(value, Index): expected = expected.array op = _ops[op_name] result = op(NaT, value) tm.assert_equal(result, expected) @pytest.mark.parametrize( "op_name", ["left_plus_right", "right_plus_left", "left_minus_right", "right_minus_left"], ) @pytest.mark.parametrize("box", [TimedeltaIndex, Series, TimedeltaArray._from_sequence]) def test_nat_arithmetic_td64_vector(op_name, box): # see gh-19124 vec = box(["1 day", "2 day"], dtype="timedelta64[ns]") box_nat = box([NaT, NaT], dtype="timedelta64[ns]") tm.assert_equal(_ops[op_name](vec, NaT), box_nat) @pytest.mark.parametrize( "dtype,op,out_dtype", [ ("datetime64[ns]", operator.add, "datetime64[ns]"), ("datetime64[ns]", roperator.radd, "datetime64[ns]"), ("datetime64[ns]", operator.sub, "timedelta64[ns]"), ("datetime64[ns]", roperator.rsub, "timedelta64[ns]"), ("timedelta64[ns]", operator.add, "datetime64[ns]"), ("timedelta64[ns]", roperator.radd, "datetime64[ns]"), ("timedelta64[ns]", operator.sub, "datetime64[ns]"), ("timedelta64[ns]", roperator.rsub, "timedelta64[ns]"), ], ) def test_nat_arithmetic_ndarray(dtype, op, out_dtype): other = np.arange(10).astype(dtype) result = op(NaT, other) expected = np.empty(other.shape, dtype=out_dtype) expected.fill("NaT") tm.assert_numpy_array_equal(result, expected) def test_nat_pinned_docstrings(): # see gh-17327 assert NaT.ctime.__doc__ == Timestamp.ctime.__doc__ def test_to_numpy_alias(): # GH 24653: alias .to_numpy() for scalars expected = NaT.to_datetime64() result = NaT.to_numpy() assert isna(expected) and isna(result) # GH#44460 result = NaT.to_numpy("M8[s]") assert isinstance(result, np.datetime64) assert result.dtype == "M8[s]" result = NaT.to_numpy("m8[ns]") assert isinstance(result, np.timedelta64) assert result.dtype == "m8[ns]" result = NaT.to_numpy("m8[s]") assert isinstance(result, np.timedelta64) assert result.dtype == "m8[s]" with pytest.raises(ValueError, match="NaT.to_numpy dtype must be a "): NaT.to_numpy(np.int64) @pytest.mark.parametrize( "other", [ Timedelta(0), Timedelta(0).to_pytimedelta(), Timedelta(0).to_timedelta64(), Timestamp(0), Timestamp(0).to_pydatetime(), Timestamp(0).to_datetime64(), Timestamp(0).tz_localize("UTC"), NaT, ], ) def test_nat_comparisons(compare_operators_no_eq_ne, other): # GH 26039 opname = compare_operators_no_eq_ne assert getattr(NaT, opname)(other) is False op = getattr(operator, opname.strip("_")) assert op(NaT, other) is False assert op(other, NaT) is False @pytest.mark.parametrize("other_and_type", [("foo", "str"), (2, "int"), (2.0, "float")]) @pytest.mark.parametrize( "symbol_and_op", [("<=", operator.le), ("<", operator.lt), (">=", operator.ge), (">", operator.gt)], ) def test_nat_comparisons_invalid(other_and_type, symbol_and_op): # GH#35585 other, other_type = other_and_type symbol, op = symbol_and_op assert not NaT == other assert not other == NaT assert NaT != other assert other != NaT msg = f"'{symbol}' not supported between instances of 'NaTType' and '{other_type}'" with pytest.raises(TypeError, match=msg): op(NaT, other) msg = f"'{symbol}' not supported between instances of '{other_type}' and 'NaTType'" with pytest.raises(TypeError, match=msg): op(other, NaT) @pytest.mark.parametrize( "other", [ np.array(["foo"] * 2, dtype=object), np.array([2, 3], dtype="int64"), np.array([2.0, 3.5], dtype="float64"), ], ids=["str", "int", "float"], ) def test_nat_comparisons_invalid_ndarray(other): # GH#40722 expected = np.array([False, False]) result = NaT == other tm.assert_numpy_array_equal(result, expected) result = other == NaT tm.assert_numpy_array_equal(result, expected) expected = np.array([True, True]) result = NaT != other tm.assert_numpy_array_equal(result, expected) result = other != NaT tm.assert_numpy_array_equal(result, expected) for symbol, op in [ ("<=", operator.le), ("<", operator.lt), (">=", operator.ge), (">", operator.gt), ]: msg = f"'{symbol}' not supported between" with pytest.raises(TypeError, match=msg): op(NaT, other) if other.dtype == np.dtype("object"): # uses the reverse operator, so symbol changes msg = None with pytest.raises(TypeError, match=msg): op(other, NaT) def test_compare_date(fixed_now_ts): # GH#39151 comparing NaT with date object is deprecated # See also: tests.scalar.timestamps.test_comparisons::test_compare_date dt = fixed_now_ts.to_pydatetime().date() msg = "Cannot compare NaT with datetime.date object" for left, right in [(NaT, dt), (dt, NaT)]: assert not left == right assert left != right with pytest.raises(TypeError, match=msg): left < right with pytest.raises(TypeError, match=msg): left <= right with pytest.raises(TypeError, match=msg): left > right with pytest.raises(TypeError, match=msg): left >= right @pytest.mark.parametrize( "obj", [ offsets.YearEnd(2), offsets.YearBegin(2), offsets.MonthBegin(1), offsets.MonthEnd(2), offsets.MonthEnd(12), offsets.Day(2), offsets.Day(5), offsets.Hour(24), offsets.Hour(3), offsets.Minute(), np.timedelta64(3, "h"), np.timedelta64(4, "h"), np.timedelta64(3200, "s"), np.timedelta64(3600, "s"), np.timedelta64(3600 * 24, "s"), np.timedelta64(2, "D"), np.timedelta64(365, "D"), timedelta(-2), timedelta(365), timedelta(minutes=120), timedelta(days=4, minutes=180), timedelta(hours=23), timedelta(hours=23, minutes=30), timedelta(hours=48), ], ) def test_nat_addsub_tdlike_scalar(obj): assert NaT + obj is NaT assert obj + NaT is NaT assert NaT - obj is NaT def test_pickle(): # GH#4606 p = tm.round_trip_pickle(NaT) assert p is NaT
TestNaTFormatting
python
PrefectHQ__prefect
src/integrations/prefect-redis/prefect_redis/messaging.py
{ "start": 9559, "end": 22356 }
class ____(_Consumer): """ Consumer implementation for Redis Streams with DLQ support. """ def __init__( self, topic: str, name: Optional[str] = None, group: Optional[str] = None, block: Optional[timedelta] = None, min_idle_time: Optional[timedelta] = None, should_process_pending_messages: Optional[bool] = None, starting_message_id: Optional[str] = None, automatically_acknowledge: Optional[bool] = None, max_retries: Optional[int] = None, trim_every: Optional[timedelta] = None, read_batch_size: Optional[int] = 1, ): settings = RedisMessagingConsumerSettings() self.name = name or topic self.stream = topic # Use topic as stream name self.group = group or topic # Use topic as default group name self.block = block if block is not None else settings.block self.min_idle_time = ( min_idle_time if min_idle_time is not None else settings.min_idle_time ) self.should_process_pending_messages = ( should_process_pending_messages if should_process_pending_messages is not None else settings.should_process_pending_messages ) self.starting_message_id = ( starting_message_id if starting_message_id is not None else settings.starting_message_id ) self.automatically_acknowledge = ( automatically_acknowledge if automatically_acknowledge is not None else settings.automatically_acknowledge ) self.trim_every = trim_every if trim_every is not None else settings.trim_every self.subscription = Subscription( max_retries=max_retries if max_retries is not None else settings.max_retries ) self._retry_counts: dict[str, int] = {} self._last_trimmed: Optional[float] = None self._read_batch_size: Optional[int] = read_batch_size async def _ensure_stream_and_group(self, redis_client: Redis) -> None: """Ensure the stream and consumer group exist.""" try: # Create consumer group and stream if they don't exist await redis_client.xgroup_create( self.stream, self.group, id=self.starting_message_id, mkstream=True ) except ResponseError as e: if "BUSYGROUP Consumer Group name already exists" not in str(e): raise logger.debug("Consumer group already exists: %s", e) async def process_pending_messages( self, handler: MessageHandler, redis_client: Redis, message_batch_size: int, start_id: str = "0-0", ): acker = partial(redis_client.xack, self.stream, self.group) while True: result = await redis_client.xautoclaim( name=self.stream, groupname=self.group, consumername=self.name, min_idle_time=int(self.min_idle_time.total_seconds() * 1000), start_id=start_id, count=message_batch_size, ) next_start_id, claimed_messages = result[0], result[1] if not claimed_messages: break for message_id, message in claimed_messages: await self._handle_message(message_id, message, handler, acker) start_id = next_start_id async def run(self, handler: MessageHandler) -> None: redis_client: Redis = get_async_redis_client() # Ensure stream and group exist before processing messages await self._ensure_stream_and_group(redis_client) # Process messages while True: if self.should_process_pending_messages: try: await self.process_pending_messages( handler, redis_client, self._read_batch_size ) except StopConsumer: return # Read new messages try: stream_entries = await redis_client.xreadgroup( groupname=self.group, consumername=self.name, streams={self.stream: ">"}, count=self._read_batch_size, block=int(self.block.total_seconds() * 1000), ) except ResponseError as e: logger.error(f"Failed to read from stream: {e}") raise if not stream_entries: await self._trim_stream_if_necessary() continue acker = partial(redis_client.xack, self.stream, self.group) for _, messages in stream_entries: for message_id, message in messages: try: await self._handle_message(message_id, message, handler, acker) except StopConsumer: return async def _handle_message( self, message_id: bytes, message: dict[str, Any], handler: MessageHandler, acker: Callable[..., Awaitable[int]], ): redis_stream_message = RedisStreamsMessage( data=message["data"], attributes=orjson.loads(message["attributes"]), acker=cast(Callable[[], Awaitable[None]], partial(acker, message_id)), ) msg_id_str = ( message_id.decode() if isinstance(message_id, bytes) else message_id ) try: await handler(redis_stream_message) if self.automatically_acknowledge: await redis_stream_message.acknowledge() except StopConsumer as e: if not e.ack: await self._on_message_failure(redis_stream_message, msg_id_str) else: if self.automatically_acknowledge: await redis_stream_message.acknowledge() raise except Exception: await self._on_message_failure(redis_stream_message, msg_id_str) finally: await self._trim_stream_if_necessary() async def _on_message_failure(self, msg: RedisStreamsMessage, msg_id_str: str): current_count = self._retry_counts.get(msg_id_str, 0) + 1 self._retry_counts[msg_id_str] = current_count if current_count > self.subscription.max_retries: # Move to DLQ await self._send_to_dlq(msg, current_count) # Acknowledge so it's no longer pending await msg.acknowledge() else: # Leave it pending. xautoclaim will re-claim it next time. pass async def _send_to_dlq(self, msg: RedisStreamsMessage, retry_count: int): """Store failed messages in Redis instead of filesystem""" redis_client: Redis = get_async_redis_client() # Convert data to a string if bytes data_str = msg.data.decode() if isinstance(msg.data, bytes) else msg.data dlq_message = { "data": data_str, "attributes": msg.attributes, "retry_count": retry_count, "timestamp": str(asyncio.get_event_loop().time()), "message_id": str(uuid.uuid4().hex), } # Store in Redis as a hash message_id = f"dlq:{uuid.uuid4().hex}" await redis_client.hset(message_id, mapping={"data": json.dumps(dlq_message)}) # Add to a Redis set for easy retrieval await redis_client.sadd(self.subscription.dlq_key, message_id) async def _trim_stream_if_necessary(self) -> None: now = time.monotonic() if self._last_trimmed is None: self._last_trimmed = now if now - self._last_trimmed > self.trim_every.total_seconds(): await _trim_stream_to_lowest_delivered_id(self.stream) await _cleanup_empty_consumer_groups(self.stream) self._last_trimmed = now @asynccontextmanager async def ephemeral_subscription( topic: str, source: Optional[str] = None, group: Optional[str] = None ) -> AsyncGenerator[dict[str, Any], None]: source = source or topic group_name = group or f"ephemeral-{socket.gethostname()}-{uuid.uuid4().hex}" redis_client: Redis = get_async_redis_client() await redis_client.xgroup_create(source, group_name, id="0", mkstream=True) try: # Return only the arguments that the Consumer expects. yield {"topic": topic, "name": topic, "group": group_name} finally: await redis_client.xgroup_destroy(source, group_name) @asynccontextmanager async def break_topic(): from unittest import mock publishing_mock = mock.AsyncMock(side_effect=ValueError("oops")) with mock.patch( "redis.asyncio.client.Redis.xadd", publishing_mock, ): yield async def _trim_stream_to_lowest_delivered_id(stream_name: str) -> None: """ Trims a Redis stream by removing all messages that have been delivered to and acknowledged by all consumer groups. This function finds the lowest last-delivered-id across all consumer groups and trims the stream up to that point, as we know all consumers have processed those messages. Consumer groups with all consumers idle beyond the configured threshold are excluded from the trimming calculation to prevent inactive groups from blocking stream trimming. Args: stream_name: The name of the Redis stream to trim """ redis_client: Redis = get_async_redis_client() settings = RedisMessagingConsumerSettings() idle_threshold_ms = int(settings.trim_idle_threshold.total_seconds() * 1000) # Get information about all consumer groups for this stream groups = await redis_client.xinfo_groups(stream_name) if not groups: logger.debug(f"No consumer groups found for stream {stream_name}") return # Find the lowest last-delivered-id across all active groups group_ids = [] for group in groups: if group["last-delivered-id"] == "0-0": # Skip groups that haven't consumed anything continue # Check if this group has any active (non-idle) consumers try: consumers = await redis_client.xinfo_consumers(stream_name, group["name"]) if consumers and all( consumer["idle"] > idle_threshold_ms for consumer in consumers ): # All consumers in this group are idle beyond threshold logger.debug( f"Skipping idle consumer group '{group['name']}' " f"(all {len(consumers)} consumers idle > {idle_threshold_ms}ms)" ) continue except Exception as e: # If we can't check consumer idle times, include the group to be safe logger.debug(f"Unable to check consumers for group '{group['name']}': {e}") group_ids.append(group["last-delivered-id"]) if not group_ids: logger.debug(f"No active consumer groups found for stream {stream_name}") return lowest_id = min(group_ids) if lowest_id == "0-0": logger.debug(f"No messages have been delivered in stream {stream_name}") return # Trim the stream up to (but not including) the lowest ID # XTRIM with MINID removes all entries with IDs strictly lower than the given ID await redis_client.xtrim(stream_name, minid=lowest_id, approximate=False) async def _cleanup_empty_consumer_groups(stream_name: str) -> None: """ Removes consumer groups that have no active consumers. Consumer groups with no consumers are considered abandoned and can safely be deleted to prevent them from blocking stream trimming operations. Args: stream_name: The name of the Redis stream to clean up groups for """ redis_client: Redis = get_async_redis_client() try: groups = await redis_client.xinfo_groups(stream_name) except Exception as e: logger.debug(f"Unable to get consumer groups for stream {stream_name}: {e}") return for group in groups: try: consumers = await redis_client.xinfo_consumers(stream_name, group["name"]) if not consumers and group["name"].startswith("ephemeral"): # No consumers in this group - it's abandoned logger.debug(f"Deleting empty consumer group '{group['name']}'") await redis_client.xgroup_destroy(stream_name, group["name"]) except Exception as e: # If we can't check or delete, just continue logger.debug(f"Unable to cleanup group '{group['name']}': {e}")
Consumer
python
pennersr__django-allauth
allauth/socialaccount/providers/google/provider.py
{ "start": 1675, "end": 3543 }
class ____(OAuth2Provider): id = "google" name = "Google" account_class = GoogleAccount oauth2_adapter_class = GoogleOAuth2Adapter supports_token_authentication = True def get_default_scope(self): scope = [Scope.PROFILE] if QUERY_EMAIL: scope.append(Scope.EMAIL) return scope def get_auth_params_from_request(self, request, action): ret = super().get_auth_params_from_request(request, action) if action == AuthAction.REAUTHENTICATE: ret["prompt"] = "select_account consent" return ret def extract_uid(self, data): if "sub" in data: return data["sub"] return data["id"] def extract_common_fields(self, data): return dict( email=data.get("email"), last_name=data.get("family_name"), first_name=data.get("given_name"), ) def extract_email_addresses(self, data): ret = [] email = data.get("email") if email: verified = bool(data.get("email_verified") or data.get("verified_email")) ret.append(EmailAddress(email=email, verified=verified, primary=True)) return ret def verify_token(self, request, token): from allauth.socialaccount.providers.google import views credential = token.get("id_token") if not credential: raise get_adapter().validation_error("invalid_token") try: identity_data = views._verify_and_decode( app=self.app, credential=credential ) except (OAuth2Error, requests.RequestException) as e: raise get_adapter().validation_error("invalid_token") from e login = self.sociallogin_from_response(request, identity_data) return login provider_classes = [GoogleProvider]
GoogleProvider
python
run-llama__llama_index
llama-index-integrations/embeddings/llama-index-embeddings-anyscale/llama_index/embeddings/anyscale/base.py
{ "start": 3059, "end": 10566 }
class ____(BaseEmbedding): """ Anyscale class for embeddings. Args: model (str): Model for embedding. Defaults to "thenlper/gte-large" """ additional_kwargs: Dict[str, Any] = Field( default_factory=dict, description="Additional kwargs for the OpenAI API." ) api_key: str = Field(description="The Anyscale API key.") api_base: str = Field(description="The base URL for Anyscale API.") api_version: str = Field(description="The version for OpenAI API.") max_retries: int = Field(default=10, description="Maximum number of retries.", ge=0) timeout: float = Field(default=60.0, description="Timeout for each request.", ge=0) default_headers: Optional[Dict[str, str]] = Field( default=None, description="The default headers for API requests." ) reuse_client: bool = Field( default=True, description=( "Reuse the Anyscale client between requests. When doing anything with large " "volumes of async API calls, setting this to false can improve stability." ), ) _query_engine: Optional[str] = PrivateAttr() _text_engine: Optional[str] = PrivateAttr() _client: Optional[OpenAI] = PrivateAttr() _aclient: Optional[AsyncOpenAI] = PrivateAttr() _http_client: Optional[httpx.Client] = PrivateAttr() def __init__( self, model: str = DEFAULT_MODEL, embed_batch_size: int = DEFAULT_EMBED_BATCH_SIZE, additional_kwargs: Optional[Dict[str, Any]] = None, api_key: Optional[str] = None, api_base: Optional[str] = DEFAULT_API_BASE, api_version: Optional[str] = None, max_retries: int = 10, timeout: float = 60.0, reuse_client: bool = True, callback_manager: Optional[CallbackManager] = None, default_headers: Optional[Dict[str, str]] = None, http_client: Optional[httpx.Client] = None, **kwargs: Any, ) -> None: additional_kwargs = additional_kwargs or {} api_key, api_base, api_version = resolve_anyscale_credentials( api_key=api_key, api_base=api_base, api_version=api_version, ) if "model_name" in kwargs: model_name = kwargs.pop("model_name") else: model_name = model super().__init__( embed_batch_size=embed_batch_size, callback_manager=callback_manager, model_name=model_name, additional_kwargs=additional_kwargs, api_key=api_key, api_base=api_base, api_version=api_version, max_retries=max_retries, reuse_client=reuse_client, timeout=timeout, default_headers=default_headers, **kwargs, ) self._query_engine = model_name self._text_engine = model_name self._client = None self._aclient = None self._http_client = http_client def _get_client(self) -> OpenAI: if not self.reuse_client: return OpenAI(**self._get_credential_kwargs()) if self._client is None: self._client = OpenAI(**self._get_credential_kwargs()) return self._client def _get_aclient(self) -> AsyncOpenAI: if not self.reuse_client: return AsyncOpenAI(**self._get_credential_kwargs()) if self._aclient is None: self._aclient = AsyncOpenAI(**self._get_credential_kwargs()) return self._aclient def _create_retry_decorator(self): """Create a retry decorator using the instance's max_retries.""" return create_retry_decorator( max_retries=self.max_retries, random_exponential=True, stop_after_delay_seconds=60, min_seconds=1, max_seconds=20, ) @classmethod def class_name(cls) -> str: return "AnyscaleEmbedding" def _get_credential_kwargs(self) -> Dict[str, Any]: return { "api_key": self.api_key, "base_url": self.api_base, "max_retries": self.max_retries, "timeout": self.timeout, "default_headers": self.default_headers, "http_client": self._http_client, } def _get_query_embedding(self, query: str) -> List[float]: """Get query embedding.""" client = self._get_client() retry_decorator = self._create_retry_decorator() @retry_decorator def _retryable_get_embedding(): return get_embedding( client, query, engine=self._query_engine, **self.additional_kwargs, ) return _retryable_get_embedding() async def _aget_query_embedding(self, query: str) -> List[float]: """The asynchronous version of _get_query_embedding.""" aclient = self._get_aclient() retry_decorator = self._create_retry_decorator() @retry_decorator async def _retryable_aget_embedding(): return await aget_embedding( aclient, query, engine=self._query_engine, **self.additional_kwargs, ) return await _retryable_aget_embedding() def _get_text_embedding(self, text: str) -> List[float]: """Get text embedding.""" client = self._get_client() retry_decorator = self._create_retry_decorator() @retry_decorator def _retryable_get_embedding(): return get_embedding( client, text, engine=self._text_engine, **self.additional_kwargs, ) return _retryable_get_embedding() async def _aget_text_embedding(self, text: str) -> List[float]: """Asynchronously get text embedding.""" aclient = self._get_aclient() retry_decorator = self._create_retry_decorator() @retry_decorator async def _retryable_aget_embedding(): return await aget_embedding( aclient, text, engine=self._text_engine, **self.additional_kwargs, ) return await _retryable_aget_embedding() def _get_text_embeddings(self, texts: List[str]) -> List[List[float]]: """ Get text embeddings. By default, this is a wrapper around _get_text_embedding. Can be overridden for batch queries. """ client = self._get_client() retry_decorator = self._create_retry_decorator() @retry_decorator def _retryable_get_embeddings(): return get_embeddings( client, texts, engine=self._text_engine, **self.additional_kwargs, ) return _retryable_get_embeddings() async def _aget_text_embeddings(self, texts: List[str]) -> List[List[float]]: """Asynchronously get text embeddings.""" aclient = self._get_aclient() retry_decorator = self._create_retry_decorator() @retry_decorator async def _retryable_aget_embeddings(): return await aget_embeddings( aclient, texts, engine=self._text_engine, **self.additional_kwargs, ) return await _retryable_aget_embeddings()
AnyscaleEmbedding
python
django-import-export__django-import-export
import_export/formats/base_formats.py
{ "start": 4745, "end": 7976 }
class ____(TablibFormat): TABLIB_MODULE = "tablib.formats._xlsx" CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" def create_dataset(self, in_stream): """ Create dataset from first sheet. """ from io import BytesIO import openpyxl # 'data_only' means values are read from formula cells, not the formula itself xlsx_book = openpyxl.load_workbook( BytesIO(in_stream), read_only=True, data_only=True ) dataset = tablib.Dataset() sheet = xlsx_book.active # obtain generator rows = sheet.rows dataset.headers = [cell.value for cell in next(rows)] ignore_blanks = getattr( settings, "IMPORT_EXPORT_IMPORT_IGNORE_BLANK_LINES", False ) for row in rows: row_values = [cell.value for cell in row] if ignore_blanks: # do not add empty rows to dataset if not all(value is None for value in row_values): dataset.append(row_values) else: dataset.append(row_values) return dataset def export_data(self, dataset, **kwargs): from openpyxl.utils.exceptions import IllegalCharacterError # #1698 temporary catch for deprecation warning in openpyxl # this catch block must be removed when openpyxl updated with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) try: return super().export_data(dataset, **kwargs) except IllegalCharacterError as e: if ( getattr( settings, "IMPORT_EXPORT_ESCAPE_ILLEGAL_CHARS_ON_EXPORT", False ) is True ): self._escape_illegal_chars(dataset) return super().export_data(dataset, **kwargs) logger.exception(e) # not raising original error due to reflected xss risk raise ValueError(_("export failed due to IllegalCharacterError")) def _escape_illegal_chars(self, dataset): from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE def _do_escape(cell): if type(cell) is str: cell = ILLEGAL_CHARACTERS_RE.sub("\N{REPLACEMENT CHARACTER}", cell) return cell for r in dataset: row = dataset.lpop() row = [_do_escape(cell) for cell in row] dataset.append(row) #: These are the default formats for import and export. Whether they can be #: used or not is depending on their implementation in the tablib library. DEFAULT_FORMATS = [ fmt for fmt in ( CSV, XLS, XLSX, TSV, ODS, JSON, YAML, HTML, ) if fmt.is_available() ] #: These are the formats which support different data types (such as datetime #: and numbers) for which `coerce_to_string` is to be set false dynamically. BINARY_FORMATS = [ fmt for fmt in ( XLS, XLSX, ODS, ) if fmt.is_available() ]
XLSX
python
pypa__warehouse
tests/unit/email/test_init.py
{ "start": 38243, "end": 41470 }
class ____: @pytest.mark.parametrize("verified", [True, False]) def test_send_account_recovery_initiated_email( self, pyramid_request, pyramid_config, monkeypatch, verified ): stub_user = pretend.stub( id="id", username="username", name="", email="email@example.com", primary_email=pretend.stub(email="email@example.com", verified=verified), ) stub_email = pretend.stub(id="id", email="email@example.com", verified=False) subject_renderer = pyramid_config.testing_add_renderer( "email/account-recovery-initiated/subject.txt" ) subject_renderer.string_response = "Email Subject" body_renderer = pyramid_config.testing_add_renderer( "email/account-recovery-initiated/body.txt" ) body_renderer.string_response = "Email Body" html_renderer = pyramid_config.testing_add_renderer( "email/account-recovery-initiated/body.html" ) html_renderer.string_response = "Email HTML Body" send_email = pretend.stub( delay=pretend.call_recorder(lambda *args, **kwargs: None) ) pyramid_request.task = pretend.call_recorder(lambda *args, **kwargs: send_email) monkeypatch.setattr(email, "send_email", send_email) pyramid_request.db = pretend.stub( query=lambda a: pretend.stub( filter=lambda *a: pretend.stub( one=lambda: pretend.stub(user_id=stub_user.id) ) ), ) pyramid_request.user = stub_user pyramid_request.registry.settings = {"mail.sender": "noreply@example.com"} result = email.send_account_recovery_initiated_email( pyramid_request, (stub_user, stub_email), project_name="project", support_issue_link="https://github.com/pypi/support/issues/666", token="deadbeef", ) assert result == { "project_name": "project", "support_issue_link": "https://github.com/pypi/support/issues/666", "token": "deadbeef", "user": stub_user, } assert pyramid_request.task.calls == [pretend.call(send_email)] assert send_email.delay.calls == [ pretend.call( f"{stub_user.username} <{stub_user.email}>", { "sender": "support@pypi.org", "subject": "Email Subject", "body_text": "Email Body", "body_html": ( "<html>\n<head></head>\n" "<body><p>Email HTML Body</p></body>\n</html>\n" ), }, { "tag": "account:email:sent", "user_id": stub_user.id, "additional": { "from_": "support@pypi.org", "to": stub_user.email, "subject": "Email Subject", "redact_ip": False, }, }, ) ]
TestAccountRecoveryInitiatedEmail
python
urllib3__urllib3
src/urllib3/contrib/socks.py
{ "start": 5709, "end": 7547 }
class ____(PoolManager): """ A version of the urllib3 ProxyManager that routes connections via the defined SOCKS proxy. """ pool_classes_by_scheme = { "http": SOCKSHTTPConnectionPool, "https": SOCKSHTTPSConnectionPool, } def __init__( self, proxy_url: str, username: str | None = None, password: str | None = None, num_pools: int = 10, headers: typing.Mapping[str, str] | None = None, **connection_pool_kw: typing.Any, ): parsed = parse_url(proxy_url) if username is None and password is None and parsed.auth is not None: split = parsed.auth.split(":") if len(split) == 2: username, password = split if parsed.scheme == "socks5": socks_version = socks.PROXY_TYPE_SOCKS5 rdns = False elif parsed.scheme == "socks5h": socks_version = socks.PROXY_TYPE_SOCKS5 rdns = True elif parsed.scheme == "socks4": socks_version = socks.PROXY_TYPE_SOCKS4 rdns = False elif parsed.scheme == "socks4a": socks_version = socks.PROXY_TYPE_SOCKS4 rdns = True else: raise ValueError(f"Unable to determine SOCKS version from {proxy_url}") self.proxy_url = proxy_url socks_options = { "socks_version": socks_version, "proxy_host": parsed.host, "proxy_port": parsed.port, "username": username, "password": password, "rdns": rdns, } connection_pool_kw["_socks_options"] = socks_options super().__init__(num_pools, headers, **connection_pool_kw) self.pool_classes_by_scheme = SOCKSProxyManager.pool_classes_by_scheme
SOCKSProxyManager
python
getsentry__sentry
tests/sentry/replays/lib/test_event_linking.py
{ "start": 152, "end": 897 }
class ____(ReplaysSnubaTestCase): def test_event_link_types(self) -> None: replay_id = uuid.uuid4().hex for level in ["debug", "info", "warning", "error", "fatal"]: event = self.store_event( data={ "level": level, "message": "testing", "contexts": {"replay": {"replay_id": replay_id}}, }, project_id=self.project.id, ) stored = transform_event_for_linking_payload(replay_id, event) # make sure snuba 200s which means that the payload was successfully written to clickhouse # (method will raise if it doesnt) self.store_replays(stored)
TestEventLink
python
pytorch__pytorch
test/distributed/elastic/rendezvous/out_of_tree_rendezvous_test.py
{ "start": 415, "end": 1238 }
class ____(unittest.TestCase): def test_out_of_tree_handler_loading(self): current_path = str(pathlib.Path(__file__).parent.resolve()) rdvz._register_out_of_tree_handlers() registry_dict = rdvz.rendezvous_handler_registry._registry # test backend should not be registered as a backend self.assertFalse(BACKEND_NAME in registry_dict) # Including testbackend in python path sys.path.append(current_path + TEST_PACKAGE_PATH) # Registering the out of tree handlers again rdvz._register_out_of_tree_handlers() # test backend should be registered as a backend self.assertTrue(BACKEND_NAME in registry_dict) # Removing testbackend from python path sys.path.remove(current_path + TEST_PACKAGE_PATH)
OutOfTreeRendezvousTest
python
walkccc__LeetCode
solutions/1980. Find Unique Binary String/1980-2.py
{ "start": 0, "end": 159 }
class ____: def findDifferentBinaryString(self, nums: list[str]) -> str: return ''.join('1' if num[i] == '0' else '0' for i, num in enumerate(nums))
Solution
python
ansible__ansible
lib/ansible/modules/group.py
{ "start": 21422, "end": 23747 }
class ____(BusyBoxGroup): platform = 'Linux' distribution = 'Alpine' def main(): module = AnsibleModule( argument_spec=dict( state=dict(type='str', default='present', choices=['absent', 'present']), name=dict(type='str', required=True), force=dict(type='bool', default=False), gid=dict(type='int'), system=dict(type='bool', default=False), local=dict(type='bool', default=False), non_unique=dict(type='bool', default=False), gid_min=dict(type='int'), gid_max=dict(type='int'), ), supports_check_mode=True, required_if=[ ['non_unique', True, ['gid']], ], ) if module.params['force'] and module.params['local']: module.fail_json(msg='force is not a valid option for local, force=True and local=True are mutually exclusive') group = Group(module) module.debug('Group instantiated - platform %s' % group.platform) if group.distribution: module.debug('Group instantiated - distribution %s' % group.distribution) rc = None out = '' err = '' result = {} result['name'] = group.name result['state'] = group.state if group.state == 'absent': if group.group_exists(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = group.group_del() if rc != 0: module.fail_json(name=group.name, msg=err) elif group.state == 'present': if not group.group_exists(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = group.group_add(gid=group.gid, system=group.system) else: (rc, out, err) = group.group_mod(gid=group.gid) if rc is not None and rc != 0: module.fail_json(name=group.name, msg=err) if rc is None: result['changed'] = False else: result['changed'] = True if out: result['stdout'] = out if err: result['stderr'] = err if group.group_exists(): info = group.group_info() result['system'] = group.system result['gid'] = info[2] module.exit_json(**result) if __name__ == '__main__': main()
AlpineGroup
python
networkx__networkx
networkx/classes/tests/test_reportviews.py
{ "start": 31940, "end": 32198 }
class ____(TestDegreeView): GRAPH = nx.DiGraph dview = nx.reportviews.DiDegreeView def test_repr(self): dv = self.G.degree() rep = "DiDegreeView({0: 1, 1: 3, 2: 2, 3: 3, 4: 2, 5: 1})" assert repr(dv) == rep
TestDiDegreeView
python
getsentry__sentry
src/sentry/models/dashboard.py
{ "start": 13578, "end": 14192 }
class ____(Model): """ A tombstone to indicate that a pre-built dashboard has been replaced or deleted for an organization. """ __relocation_scope__ = RelocationScope.Organization slug = SentrySlugField(max_length=255, db_index=False) organization = FlexibleForeignKey("sentry.Organization") date_added = models.DateTimeField(default=timezone.now) class Meta: app_label = "sentry" db_table = "sentry_dashboardtombstone" unique_together = (("organization", "slug"),) __repr__ = sane_repr("organization", "slug") @region_silo_model
DashboardTombstone
python
joke2k__faker
tests/providers/test_currency.py
{ "start": 16363, "end": 16788 }
class ____: """Test nl_NL currency provider""" num_samples = 100 @classmethod def setup_class(cls): from faker.providers.currency.el_GR import Provider as ElGrCurrencyProvider cls.provider = ElGrCurrencyProvider def test_pricetag(self, faker, num_samples): for _ in range(num_samples): pricetag = faker.pricetag() assert isinstance(pricetag, str)
TestElGr
python
openai__openai-python
src/openai/types/realtime/realtime_mcp_approval_request_param.py
{ "start": 231, "end": 717 }
class ____(TypedDict, total=False): id: Required[str] """The unique ID of the approval request.""" arguments: Required[str] """A JSON string of arguments for the tool.""" name: Required[str] """The name of the tool to run.""" server_label: Required[str] """The label of the MCP server making the request.""" type: Required[Literal["mcp_approval_request"]] """The type of the item. Always `mcp_approval_request`."""
RealtimeMcpApprovalRequestParam
python
openai__openai-python
tests/api_resources/test_embeddings.py
{ "start": 2378, "end": 4555 }
class ____: parametrize = pytest.mark.parametrize( "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] ) @parametrize async def test_method_create(self, async_client: AsyncOpenAI) -> None: embedding = await async_client.embeddings.create( input="The quick brown fox jumped over the lazy dog", model="text-embedding-3-small", ) assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) @parametrize async def test_method_create_with_all_params(self, async_client: AsyncOpenAI) -> None: embedding = await async_client.embeddings.create( input="The quick brown fox jumped over the lazy dog", model="text-embedding-3-small", dimensions=1, encoding_format="float", user="user-1234", ) assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) @parametrize async def test_raw_response_create(self, async_client: AsyncOpenAI) -> None: response = await async_client.embeddings.with_raw_response.create( input="The quick brown fox jumped over the lazy dog", model="text-embedding-3-small", ) assert response.is_closed is True assert response.http_request.headers.get("X-Stainless-Lang") == "python" embedding = response.parse() assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) @parametrize async def test_streaming_response_create(self, async_client: AsyncOpenAI) -> None: async with async_client.embeddings.with_streaming_response.create( input="The quick brown fox jumped over the lazy dog", model="text-embedding-3-small", ) as response: assert not response.is_closed assert response.http_request.headers.get("X-Stainless-Lang") == "python" embedding = await response.parse() assert_matches_type(CreateEmbeddingResponse, embedding, path=["response"]) assert cast(Any, response.is_closed) is True
TestAsyncEmbeddings
python
django__django
django/db/backends/mysql/creation.py
{ "start": 144, "end": 4052 }
class ____(BaseDatabaseCreation): def sql_table_creation_suffix(self): suffix = [] test_settings = self.connection.settings_dict["TEST"] if test_settings["CHARSET"]: suffix.append("CHARACTER SET %s" % test_settings["CHARSET"]) if test_settings["COLLATION"]: suffix.append("COLLATE %s" % test_settings["COLLATION"]) return " ".join(suffix) def _execute_create_test_db(self, cursor, parameters, keepdb=False): try: super()._execute_create_test_db(cursor, parameters, keepdb) except Exception as e: if len(e.args) < 1 or e.args[0] != 1007: # All errors except "database exists" (1007) cancel tests. self.log("Got an error creating the test database: %s" % e) sys.exit(2) else: raise def _clone_test_db(self, suffix, verbosity, keepdb=False): source_database_name = self.connection.settings_dict["NAME"] target_database_name = self.get_test_db_clone_settings(suffix)["NAME"] test_db_params = { "dbname": self.connection.ops.quote_name(target_database_name), "suffix": self.sql_table_creation_suffix(), } with self._nodb_cursor() as cursor: try: self._execute_create_test_db(cursor, test_db_params, keepdb) except Exception: if keepdb: # If the database should be kept, skip everything else. return try: if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % ( self._get_database_display_str( verbosity, target_database_name ), ) ) cursor.execute("DROP DATABASE %(dbname)s" % test_db_params) self._execute_create_test_db(cursor, test_db_params, keepdb) except Exception as e: self.log("Got an error recreating the test database: %s" % e) sys.exit(2) self._clone_db(source_database_name, target_database_name) def _clone_db(self, source_database_name, target_database_name): cmd_args, cmd_env = DatabaseClient.settings_to_cmd_args_env( self.connection.settings_dict, [] ) dump_cmd = [ "mysqldump", *cmd_args[1:-1], "--routines", "--events", source_database_name, ] dump_env = load_env = {**os.environ, **cmd_env} if cmd_env else None load_cmd = cmd_args load_cmd[-1] = target_database_name with ( subprocess.Popen( dump_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=dump_env ) as dump_proc, subprocess.Popen( load_cmd, stdin=dump_proc.stdout, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=load_env, ) as load_proc, ): # Allow dump_proc to receive a SIGPIPE if the load process exits. dump_proc.stdout.close() dump_err = dump_proc.stderr.read().decode(errors="replace") load_err = load_proc.stderr.read().decode(errors="replace") if dump_proc.returncode != 0: self.log( f"Got an error on mysqldump when cloning the test database: {dump_err}" ) sys.exit(dump_proc.returncode) if load_proc.returncode != 0: self.log(f"Got an error cloning the test database: {load_err}") sys.exit(load_proc.returncode)
DatabaseCreation
python
crytic__slither
slither/detectors/attributes/unimplemented_interface.py
{ "start": 433, "end": 5741 }
class ____(AbstractDetector): """ Unimplemented interface detector """ ARGUMENT = "missing-inheritance" HELP = "Missing inheritance" IMPACT = DetectorClassification.INFORMATIONAL CONFIDENCE = DetectorClassification.HIGH WIKI = "https://github.com/crytic/slither/wiki/Detector-Documentation#missing-inheritance" WIKI_TITLE = "Missing inheritance" WIKI_DESCRIPTION = "Detect missing inheritance." # region wiki_exploit_scenario WIKI_EXPLOIT_SCENARIO = """ ```solidity interface ISomething { function f1() external returns(uint); } contract Something { function f1() external returns(uint){ return 42; } } ``` `Something` should inherit from `ISomething`. """ # endregion wiki_exploit_scenario WIKI_RECOMMENDATION = "Inherit from the missing interface or contract." @staticmethod def detect_unimplemented_interface( contract: Contract, interfaces: List[Contract] ) -> List[Contract]: """ Detects if contract intends to implement one of the interfaces but does not explicitly do so by deriving from it :param contract: The contract to check :param interfaces: List of all the interfaces :return: Interfaces likely intended to implement by the contract """ intended_interfaces: List[Contract] = [] sigs_contract = {f.full_name for f in contract.functions_entry_points} if not sigs_contract: return intended_interfaces for interface in interfaces: # If contract already inherits from interface, skip that interface if interface in contract.inheritance: continue sigs_interface = {f.full_name for f in interface.functions_entry_points} # Contract should implement all the functions of the intended interface if not sigs_interface.issubset(sigs_contract): continue # A parent contract inherited should not implement a superset of intended interface # This is because in the following: # interface ERC20_interface: # - balanceOf(uint) -> uint # - transfer(address, address) -> bool # contract ForeignToken: # - balanceOf(uint) -> uint # contract MyERC20Implementation is ERC20_interface # # We do not want MyERC20Implementation to be declared as missing ForeignToken interface intended_interface_is_subset_parent = False for parent in contract.inheritance: sigs_parent = {f.full_name for f in parent.functions_entry_points} if sigs_interface.issubset(sigs_parent): intended_interface_is_subset_parent = True break if not intended_interface_is_subset_parent: # Should not be a subset of an earlier determined intended_interface or derive from it intended_interface_is_subset_intended = False for intended_interface in list(intended_interfaces): sigs_intended_interface = { f.full_name for f in intended_interface.functions_entry_points } if ( sigs_interface.issubset(sigs_intended_interface) or interface in intended_interface.inheritance ): intended_interface_is_subset_intended = True break # If superset of an earlier determined intended_interface or derives from it, # remove the intended_interface if ( sigs_intended_interface.issubset(sigs_interface) or intended_interface in interface.inheritance ): intended_interfaces.remove(intended_interface) if not intended_interface_is_subset_intended: intended_interfaces.append(interface) return intended_interfaces def _detect(self) -> List[Output]: """Detect unimplemented interfaces Returns: list: {'contract'} """ # Collect all the interfaces # Here interface can be "interface" from solidity, or contracts with only functions declaration # Skip interfaces without functions interfaces = [ contract for contract in self.compilation_unit.contracts if contract.is_signature_only() and any(not f.is_constructor_variables for f in contract.functions) ] # Check derived contracts for missing interface implementations results = [] for contract in self.compilation_unit.contracts_derived: # Skip interfaces if contract in interfaces: continue intended_interfaces = self.detect_unimplemented_interface(contract, interfaces) for interface in intended_interfaces: info: DETECTOR_INFO = [contract, " should inherit from ", interface, "\n"] res = self.generate_result(info) results.append(res) return results
MissingInheritance
python
streamlit__streamlit
lib/streamlit/components/v1/custom_component.py
{ "start": 1885, "end": 9196 }
class ____(BaseCustomComponent): """A Custom Component declaration.""" def __call__( self, *args: Any, default: Any = None, key: str | None = None, on_change: WidgetCallback | None = None, tab_index: int | None = None, **kwargs: Any, ) -> Any: """An alias for create_instance.""" return self.create_instance( *args, default=default, key=key, on_change=on_change, tab_index=tab_index, **kwargs, ) @gather_metrics("create_instance") def create_instance( self, *args: Any, default: Any = None, key: str | None = None, on_change: WidgetCallback | None = None, tab_index: int | None = None, **kwargs: Any, ) -> Any: """Create a new instance of the component. Parameters ---------- *args Must be empty; all args must be named. (This parameter exists to enforce correct use of the function.) default: any or None The default return value for the component. This is returned when the component's frontend hasn't yet specified a value with `setComponentValue`. key: str or None If not None, this is the user key we use to generate the component's "widget ID". on_change: WidgetCallback or None An optional callback invoked when the widget's value changes. No arguments are passed to it. tab_index : int, optional Specifies the tab order of the iframe containing the component. Possible values are: - ``None`` (default): Browser default behavior. - ``-1``: Removes the iframe from the natural tab order, but it can still be focused programmatically. - ``0`` or positive integer: Includes the iframe in the natural tab order. **kwargs Keyword args to pass to the component. Returns ------- any or None The component's widget value. """ if len(args) > 0: raise MarshallComponentException(f"Argument '{args[0]}' needs a label") # Validate tab_index according to web specifications if tab_index is not None and not ( isinstance(tab_index, int) and not isinstance(tab_index, bool) and tab_index >= -1 ): raise StreamlitAPIException( "tab_index must be None, -1, or a non-negative integer." ) try: import pyarrow # noqa: F401, ICN001 from streamlit.components.v1 import component_arrow except ImportError: raise StreamlitAPIException( """To use Custom Components in Streamlit, you need to install PyArrow. To do so locally: `pip install pyarrow` And if you're using Streamlit Cloud, add "pyarrow" to your requirements.txt.""" ) check_cache_replay_rules() # In addition to the custom kwargs passed to the component, we also # send the special 'default' and 'key' params to the component # frontend. all_args = dict(kwargs, default=default, key=key) json_args = {} special_args = [] for arg_name, arg_val in all_args.items(): if is_bytes_like(arg_val): bytes_arg = SpecialArg() bytes_arg.key = arg_name bytes_arg.bytes = to_bytes(arg_val) special_args.append(bytes_arg) elif is_dataframe_like(arg_val): dataframe_arg = SpecialArg() dataframe_arg.key = arg_name component_arrow.marshall(dataframe_arg.arrow_dataframe.data, arg_val) special_args.append(dataframe_arg) else: json_args[arg_name] = arg_val try: serialized_json_args = json.dumps(json_args) except Exception as ex: raise MarshallComponentException( "Could not convert component args to JSON", ex ) def marshall_component(dg: DeltaGenerator, element: Element) -> Any: element.component_instance.component_name = self.name element.component_instance.form_id = current_form_id(dg) if self.url is not None: element.component_instance.url = self.url if tab_index is not None: element.component_instance.tab_index = tab_index element.component_instance.json_args = serialized_json_args element.component_instance.special_args.extend(special_args) computed_id = compute_and_register_element_id( "component_instance", user_key=key, # Ensure that the component identity is kept stable when key is provided, # Only the name and url are whitelisted to result in a new identity # if they are changed. key_as_main_identity={"name", "url"}, dg=dg, name=self.name, url=self.url, json_args=serialized_json_args, special_args=special_args, ) element.component_instance.id = computed_id def deserialize_component(ui_value: Any) -> Any: # ui_value is an object from json, an ArrowTable proto, or a bytearray return ui_value component_state = register_widget( element.component_instance.id, deserializer=deserialize_component, serializer=lambda x: x, ctx=get_script_run_ctx(), on_change_handler=on_change, value_type="json_value", ) widget_value = component_state.value if widget_value is None: widget_value = default elif isinstance(widget_value, ArrowTableProto): widget_value = component_arrow.arrow_proto_to_dataframe(widget_value) return widget_value # We currently only support writing to st._main, but this will change # when we settle on an improved API in a post-layout world. dg = get_dg_singleton_instance().main_dg element = Element() return_value = marshall_component(dg, element) dg._enqueue("component_instance", element.component_instance) return return_value def __eq__(self, other: object) -> bool: """Equality operator.""" return ( isinstance(other, CustomComponent) and self.name == other.name and self.path == other.path and self.url == other.url and self.module_name == other.module_name ) __hash__ = BaseCustomComponent.__hash__ def __ne__(self, other: object) -> bool: """Inequality operator.""" # we have to use "not X == Y"" here because if we use "X != Y" # we call __ne__ again and end up in recursion return not self == other def __str__(self) -> str: return f"'{self.name}': {self.path if self.path is not None else self.url}"
CustomComponent
python
facebookresearch__faiss
tests/test_swig_wrapper.py
{ "start": 5111, "end": 5813 }
class ____(unittest.TestCase): def test_exception(self): index = faiss.IndexFlatL2(10) a = np.zeros((5, 10), dtype='float32') b = np.zeros(5, dtype='int64') # an unsupported operation for IndexFlat self.assertRaises( RuntimeError, index.add_with_ids, a, b ) # assert 'add_with_ids not implemented' in str(e) def test_exception_2(self): self.assertRaises( RuntimeError, faiss.index_factory, 12, 'IVF256,Flat,PQ8' ) # assert 'could not parse' in str(e) @unittest.skipIf(faiss.swig_version() < 0x040000, "swig < 4 does not support Doxygen comments")
TestException
python
xlwings__xlwings
xlwings/constants.py
{ "start": 62918, "end": 63083 }
class ____: xlComments = -4144 # from enum XlFindLookIn xlFormulas = -4123 # from enum XlFindLookIn xlValues = -4163 # from enum XlFindLookIn
FindLookIn
python
getsentry__sentry
tests/sentry/grouping/test_enhancer_dart_flutter_native.py
{ "start": 237, "end": 894 }
class ____(TestCase): """Common setup and helpers shared by native-platform tests.""" PLATFORM = "native" def setUp(self) -> None: super().setUp() # Load the default enhancement rules that include Dart/Flutter logic. self.enhancements = ENHANCEMENT_BASES["all-platforms:2023-01-11"] def apply_rules(self, frame: dict[str, str]) -> dict[str, Any]: """Apply enhancement rules to a single frame and return the processed frame.""" frames = [frame] self.enhancements.apply_category_and_updated_in_app_to_frames(frames, self.PLATFORM, {}) return frames[0]
_BaseNativeDartFlutterEnhancerTest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/metadata/source_code.py
{ "start": 1428, "end": 1797 }
class ____(DagsterModel): """Represents a source location which points at a URL, for example in source control. """ url: str label: Optional[str] = None @property def source(self) -> str: return self.url CodeReference: TypeAlias = Union[LocalFileCodeReference, UrlCodeReference] @public @beta @whitelist_for_serdes
UrlCodeReference
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 8177, "end": 13144 }
class ____(Exception): """ Internal wrapper around IndexError so that IndexErrors raised inside parse actions aren't misinterpreted as IndexErrors raised inside ParserElement parseImpl methods. """ def __init__(self, msg: str, exc: BaseException) -> None: self.msg: str = msg self.exc: BaseException = exc _trim_arity_call_line: traceback.StackSummary = None # type: ignore[assignment] pa_call_line_synth = () def _trim_arity(func, max_limit=3): """decorator to trim function calls to match the arity of the target""" global _trim_arity_call_line, pa_call_line_synth if func in _single_arg_builtins: return lambda s, l, t: func(t) limit = 0 found_arity = False # synthesize what would be returned by traceback.extract_stack at the call to # user's parse action 'func', so that we don't incur call penalty at parse time # fmt: off LINE_DIFF = 9 # IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND # THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!! _trim_arity_call_line = _trim_arity_call_line or traceback.extract_stack(limit=2)[-1] pa_call_line_synth = pa_call_line_synth or (_trim_arity_call_line[0], _trim_arity_call_line[1] + LINE_DIFF) def wrapper(*args): nonlocal found_arity, limit if found_arity: return func(*args[limit:]) while 1: try: ret = func(*args[limit:]) found_arity = True return ret except TypeError as te: # re-raise TypeErrors if they did not come from our arity testing if found_arity: raise else: tb = te.__traceback__ frames = traceback.extract_tb(tb, limit=2) frame_summary = frames[-1] trim_arity_type_error = ( [frame_summary[:2]][-1][:2] == pa_call_line_synth ) del tb if trim_arity_type_error: if limit < max_limit: limit += 1 continue raise except IndexError as ie: # wrap IndexErrors inside a _ParseActionIndexError raise _ParseActionIndexError( "IndexError raised in parse action", ie ).with_traceback(None) # fmt: on # copy func name to wrapper for sensible debug output # (can't use functools.wraps, since that messes with function signature) func_name = getattr(func, "__name__", getattr(func, "__class__").__name__) wrapper.__name__ = func_name wrapper.__doc__ = func.__doc__ return wrapper def condition_as_parse_action( fn: ParseCondition, message: typing.Optional[str] = None, fatal: bool = False ) -> ParseAction: """ Function to convert a simple predicate function that returns ``True`` or ``False`` into a parse action. Can be used in places when a parse action is required and :meth:`ParserElement.add_condition` cannot be used (such as when adding a condition to an operator level in :class:`infix_notation`). Optional keyword arguments: :param message: define a custom message to be used in the raised exception :param fatal: if ``True``, will raise :class:`ParseFatalException` to stop parsing immediately; otherwise will raise :class:`ParseException` """ msg = message if message is not None else "failed user-defined condition" exc_type = ParseFatalException if fatal else ParseException fn = _trim_arity(fn) @wraps(fn) def pa(s, l, t): if not bool(fn(s, l, t)): raise exc_type(s, l, msg) return pa def _default_start_debug_action( instring: str, loc: int, expr: ParserElement, cache_hit: bool = False ): cache_hit_str = "*" if cache_hit else "" print( ( f"{cache_hit_str}Match {expr} at loc {loc}({lineno(loc, instring)},{col(loc, instring)})\n" f" {line(loc, instring)}\n" f" {'^':>{col(loc, instring)}}" ) ) def _default_success_debug_action( instring: str, startloc: int, endloc: int, expr: ParserElement, toks: ParseResults, cache_hit: bool = False, ): cache_hit_str = "*" if cache_hit else "" print(f"{cache_hit_str}Matched {expr} -> {toks.as_list()}") def _default_exception_debug_action( instring: str, loc: int, expr: ParserElement, exc: Exception, cache_hit: bool = False, ): cache_hit_str = "*" if cache_hit else "" print(f"{cache_hit_str}Match {expr} failed, {type(exc).__name__} raised: {exc}") def null_debug_action(*args): """'Do-nothing' debug action, to suppress debugging output during parsing."""
_ParseActionIndexError
python
getsentry__sentry-python
sentry_sdk/transport.py
{ "start": 20915, "end": 30185 }
class ____(BaseHttpTransport): if TYPE_CHECKING: _pool: Union[PoolManager, ProxyManager] def _get_pool_options(self): # type: (Self) -> Dict[str, Any] num_pools = self.options.get("_experiments", {}).get("transport_num_pools") options = { "num_pools": 2 if num_pools is None else int(num_pools), "cert_reqs": "CERT_REQUIRED", "timeout": urllib3.Timeout(total=self.TIMEOUT), } socket_options = None # type: Optional[List[Tuple[int, int, int | bytes]]] if self.options["socket_options"] is not None: socket_options = self.options["socket_options"] if self.options["keep_alive"]: if socket_options is None: socket_options = [] used_options = {(o[0], o[1]) for o in socket_options} for default_option in KEEP_ALIVE_SOCKET_OPTIONS: if (default_option[0], default_option[1]) not in used_options: socket_options.append(default_option) if socket_options is not None: options["socket_options"] = socket_options options["ca_certs"] = ( self.options["ca_certs"] # User-provided bundle from the SDK init or os.environ.get("SSL_CERT_FILE") or os.environ.get("REQUESTS_CA_BUNDLE") or certifi.where() ) options["cert_file"] = self.options["cert_file"] or os.environ.get( "CLIENT_CERT_FILE" ) options["key_file"] = self.options["key_file"] or os.environ.get( "CLIENT_KEY_FILE" ) return options def _make_pool(self): # type: (Self) -> Union[PoolManager, ProxyManager] if self.parsed_dsn is None: raise ValueError("Cannot create HTTP-based transport without valid DSN") proxy = None no_proxy = self._in_no_proxy(self.parsed_dsn) # try HTTPS first https_proxy = self.options["https_proxy"] if self.parsed_dsn.scheme == "https" and (https_proxy != ""): proxy = https_proxy or (not no_proxy and getproxies().get("https")) # maybe fallback to HTTP proxy http_proxy = self.options["http_proxy"] if not proxy and (http_proxy != ""): proxy = http_proxy or (not no_proxy and getproxies().get("http")) opts = self._get_pool_options() if proxy: proxy_headers = self.options["proxy_headers"] if proxy_headers: opts["proxy_headers"] = proxy_headers if proxy.startswith("socks"): use_socks_proxy = True try: # Check if PySocks dependency is available from urllib3.contrib.socks import SOCKSProxyManager except ImportError: use_socks_proxy = False logger.warning( "You have configured a SOCKS proxy (%s) but support for SOCKS proxies is not installed. Disabling proxy support. Please add `PySocks` (or `urllib3` with the `[socks]` extra) to your dependencies.", proxy, ) if use_socks_proxy: return SOCKSProxyManager(proxy, **opts) else: return urllib3.PoolManager(**opts) else: return urllib3.ProxyManager(proxy, **opts) else: return urllib3.PoolManager(**opts) def _request( self, method, endpoint_type, body, headers, ): # type: (Self, str, EndpointType, Any, Mapping[str, str]) -> urllib3.BaseHTTPResponse return self._pool.request( method, self._auth.get_api_url(endpoint_type), body=body, headers=headers, ) try: import httpcore import h2 # noqa: F401 except ImportError: # Sorry, no Http2Transport for you class Http2Transport(HttpTransport): def __init__(self, options): # type: (Self, Dict[str, Any]) -> None super().__init__(options) logger.warning( "You tried to use HTTP2Transport but don't have httpcore[http2] installed. Falling back to HTTPTransport." ) else: class Http2Transport(BaseHttpTransport): # type: ignore """The HTTP2 transport based on httpcore.""" TIMEOUT = 15 if TYPE_CHECKING: _pool: Union[ httpcore.SOCKSProxy, httpcore.HTTPProxy, httpcore.ConnectionPool ] def _get_header_value(self, response, header): # type: (Self, httpcore.Response, str) -> Optional[str] return next( ( val.decode("ascii") for key, val in response.headers if key.decode("ascii").lower() == header ), None, ) def _request( self, method, endpoint_type, body, headers, ): # type: (Self, str, EndpointType, Any, Mapping[str, str]) -> httpcore.Response response = self._pool.request( method, self._auth.get_api_url(endpoint_type), content=body, headers=headers, # type: ignore extensions={ "timeout": { "pool": self.TIMEOUT, "connect": self.TIMEOUT, "write": self.TIMEOUT, "read": self.TIMEOUT, } }, ) return response def _get_pool_options(self): # type: (Self) -> Dict[str, Any] options = { "http2": self.parsed_dsn is not None and self.parsed_dsn.scheme == "https", "retries": 3, } # type: Dict[str, Any] socket_options = ( self.options["socket_options"] if self.options["socket_options"] is not None else [] ) used_options = {(o[0], o[1]) for o in socket_options} for default_option in KEEP_ALIVE_SOCKET_OPTIONS: if (default_option[0], default_option[1]) not in used_options: socket_options.append(default_option) options["socket_options"] = socket_options ssl_context = ssl.create_default_context() ssl_context.load_verify_locations( self.options["ca_certs"] # User-provided bundle from the SDK init or os.environ.get("SSL_CERT_FILE") or os.environ.get("REQUESTS_CA_BUNDLE") or certifi.where() ) cert_file = self.options["cert_file"] or os.environ.get("CLIENT_CERT_FILE") key_file = self.options["key_file"] or os.environ.get("CLIENT_KEY_FILE") if cert_file is not None: ssl_context.load_cert_chain(cert_file, key_file) options["ssl_context"] = ssl_context return options def _make_pool(self): # type: (Self) -> Union[httpcore.SOCKSProxy, httpcore.HTTPProxy, httpcore.ConnectionPool] if self.parsed_dsn is None: raise ValueError("Cannot create HTTP-based transport without valid DSN") proxy = None no_proxy = self._in_no_proxy(self.parsed_dsn) # try HTTPS first https_proxy = self.options["https_proxy"] if self.parsed_dsn.scheme == "https" and (https_proxy != ""): proxy = https_proxy or (not no_proxy and getproxies().get("https")) # maybe fallback to HTTP proxy http_proxy = self.options["http_proxy"] if not proxy and (http_proxy != ""): proxy = http_proxy or (not no_proxy and getproxies().get("http")) opts = self._get_pool_options() if proxy: proxy_headers = self.options["proxy_headers"] if proxy_headers: opts["proxy_headers"] = proxy_headers if proxy.startswith("socks"): try: if "socket_options" in opts: socket_options = opts.pop("socket_options") if socket_options: logger.warning( "You have defined socket_options but using a SOCKS proxy which doesn't support these. We'll ignore socket_options." ) return httpcore.SOCKSProxy(proxy_url=proxy, **opts) except RuntimeError: logger.warning( "You have configured a SOCKS proxy (%s) but support for SOCKS proxies is not installed. Disabling proxy support.", proxy, ) else: return httpcore.HTTPProxy(proxy_url=proxy, **opts) return httpcore.ConnectionPool(**opts)
HttpTransport
python
patrick-kidger__equinox
equinox/_doc_utils.py
{ "start": 183, "end": 1443 }
class ____(type): def __new__(mcs, obj, string): out = super().__new__(mcs, string, (), {}) # prevent the custom typing repr from doing the wrong thing out.__module__ = "builtins" return out def __init__(cls, obj, string): cls.obj = obj cls.string = string def __repr__(cls): return cls.string def __call__(cls, *args, **kwargs): return cls.obj(*args, **kwargs) _T = TypeVar("_T") def doc_repr(obj: _T, string: str) -> _T: if TYPE_CHECKING: return obj else: if hasattr(typing, "GENERATING_DOCUMENTATION"): return WithRepr(obj, string) else: return obj def doc_remove_args(*args): def doc_remove_args_impl(fn): if hasattr(typing, "GENERATING_DOCUMENTATION"): sig = inspect.signature(fn) new_params = [] for param in sig.parameters.values(): if param.name not in args: new_params.append(param) sig = sig.replace(parameters=new_params) # Force-set it when doing `doc_remove_args(filter_jit(...))`. object.__setattr__(fn, "__signature__", sig) return fn return doc_remove_args_impl
WithRepr
python
astropy__astropy
astropy/cosmology/_src/tests/parameter/test_parameter.py
{ "start": 6981, "end": 15709 }
class ____(ParameterTestMixin): """ Test `astropy.cosmology.Parameter` directly. Adds a lot of specific tests that wouldn't be covered by the per-cosmology tests. """ def setup_class(self): theparam = Parameter( default=15, doc="Description of example parameter.", unit=u.m, equivalencies=u.mass_energy(), ) @dataclass_decorator class Example1(Cosmology): param: Parameter = theparam.clone() @property def is_flat(self) -> bool: return super().is_flat() # with validator @dataclass_decorator class Example2(Example1): param: Parameter = theparam.clone(default=15 * u.m) @param.validator def param(self, param, value): return value.to(u.km) # attributes self.classes = {"Example1": Example1, "Example2": Example2} def teardown_class(self): for cls in self.classes.values(): _COSMOLOGY_CLASSES.pop(cls.__qualname__, None) @pytest.fixture(scope="class", params=["Example1", "Example2"]) def cosmo_cls(self, request): """Cosmology class.""" return self.classes[request.param] @pytest.fixture(scope="class") def cosmo(self, cosmo_cls): """Cosmology instance""" return cosmo_cls() @pytest.fixture(scope="class") def param(self, cosmo_cls): """Get Parameter 'param' from cosmology class.""" return cosmo_cls.parameters["param"] @pytest.fixture(scope="class") def param_cls(self, param): """Get Parameter class from cosmology class.""" return type(param) # ============================================================== def test_Parameter_instance_attributes(self, param): """Test :class:`astropy.cosmology.Parameter` attributes from init.""" super().test_Parameter_instance_attributes(param) # property assert param.__doc__ == "Description of example parameter." # custom from init assert param.unit == u.m assert param.equivalencies == u.mass_energy() assert param.derived == np.False_ # custom from set_name assert param.name == "param" def test_Parameter_fvalidate(self, cosmo, param): """Test :attr:`astropy.cosmology.Parameter.fvalidate`.""" super().test_Parameter_fvalidate(param) value = param.fvalidate(cosmo, param, 1000 * u.m) assert value == 1 * u.km def test_Parameter_name(self, param): """Test :attr:`astropy.cosmology.Parameter.name`.""" super().test_Parameter_name(param) assert param.name == "param" def test_Parameter_unit(self, param): """Test :attr:`astropy.cosmology.Parameter.unit`.""" super().test_Parameter_unit(param) assert param.unit == u.m def test_Parameter_equivalencies(self, param): """Test :attr:`astropy.cosmology.Parameter.equivalencies`.""" super().test_Parameter_equivalencies(param) assert param.equivalencies == u.mass_energy() def test_Parameter_derived(self, cosmo_cls, param): """Test :attr:`astropy.cosmology.Parameter.derived`.""" super().test_Parameter_derived(cosmo_cls, param) assert param.derived is False # ------------------------------------------- # descriptor methods def test_Parameter_descriptor_get(self, cosmo_cls, cosmo, param): """Test :meth:`astropy.cosmology.Parameter.__get__`.""" super().test_Parameter_descriptor_get(cosmo_cls, cosmo, param) # from instance value = getattr(cosmo, param.name) assert value == 15 * u.m # ------------------------------------------- # validation def test_Parameter_validator(self, param): """Test :meth:`astropy.cosmology.Parameter.validator`.""" for k in _REGISTRY_FVALIDATORS: newparam = param.validator(k) assert newparam.fvalidate == _REGISTRY_FVALIDATORS[k] # error for non-registered str with pytest.raises(ValueError, match="`fvalidate`, if str"): Parameter(fvalidate="NOT REGISTERED") # error if wrong type with pytest.raises(TypeError, match="`fvalidate` must be a function or"): Parameter(fvalidate=object()) def test_Parameter_validate(self, cosmo, param): """Test :meth:`astropy.cosmology.Parameter.validate`.""" value = param.validate(cosmo, 1000 * u.m) # whether has custom validator if param.fvalidate is _REGISTRY_FVALIDATORS["default"]: assert value.unit == u.m assert value.value == 1000 else: assert value.unit == u.km assert value.value == 1 def test_Parameter_register_validator(self, param_cls): """Test :meth:`astropy.cosmology.Parameter.register_validator`.""" # already registered with pytest.raises(KeyError, match="validator 'default' already"): param_cls.register_validator("default", None) # validator not None def notnonefunc(x): return x try: validator = param_cls.register_validator("newvalidator", notnonefunc) assert validator is notnonefunc finally: _REGISTRY_FVALIDATORS.pop("newvalidator", None) # used as decorator try: @param_cls.register_validator("newvalidator") def func(cosmology, param, value): return value assert _REGISTRY_FVALIDATORS["newvalidator"] is func finally: _REGISTRY_FVALIDATORS.pop("newvalidator", None) # ------------------------------------------- def test_Parameter_clone(self, param): """Test :meth:`astropy.cosmology.Parameter.clone`.""" # this implicitly relies on `__eq__` testing properly. Which is tested. # basic test that nothing changes assert param.clone() == param assert param.clone() is not param # but it's not a 'singleton' # passing kwargs will change stuff newparam = param.clone(unit="km/(yr sr)") assert newparam.unit == u.km / u.yr / u.sr assert param.unit != u.km / u.yr / u.sr # original is unchanged # expected failure for not-an-argument with pytest.raises(TypeError): param.clone(not_a_valid_parameter=True) # ------------------------------------------- def test_Parameter_equality(self): """Test Parameter equality. Determined from the processed initialization args (including defaults). """ p1 = Parameter(unit="km / (s Mpc)") p2 = Parameter(unit="km / (s Mpc)") assert p1 == p2 # not equal parameters p3 = Parameter(unit="km / s") assert p3 != p1 # misc assert p1 != 2 # show doesn't error # ------------------------------------------- def test_Parameter_repr(self, cosmo_cls, param): """Test Parameter repr.""" r = repr(param) assert "Parameter(" in r for subs in ( "derived=False", 'unit=Unit("m")', 'equivalencies=[(Unit("kg"), Unit("J")', "doc='Description of example parameter.'", ): assert subs in r, subs # `fvalidate` is a little tricker b/c one of them is custom! if param.fvalidate in _REGISTRY_FVALIDATORS.values(): # not custom assert "fvalidate='default'" in r else: assert "fvalidate=<" in r # Some function, don't care about details. def test_Parameter_repr_roundtrip(self, param): """Test ``eval(repr(Parameter))`` can round trip to ``Parameter``.""" P = Parameter(doc="A description of this parameter.", derived=True) NP = eval(repr(P)) # Evaluate string representation back into a param. assert P == NP # ======================================================================== def test_make_from_Parameter(self, cosmo_cls, clean_registry): """Test the parameter creation process. Uses ``__set__``.""" @dataclass_decorator class Example(cosmo_cls): param: Parameter = Parameter(unit=u.eV, equivalencies=u.mass_energy()) @property def is_flat(self) -> bool: return super().is_flat() assert Example(1).param == 1 * u.eV assert Example(1 * u.eV).param == 1 * u.eV assert Example(1 * u.J).param == (1 * u.J).to(u.eV) assert Example(1 * u.kg).param == (1 * u.kg).to(u.eV, u.mass_energy())
TestParameter
python
pennersr__django-allauth
allauth/socialaccount/providers/__init__.py
{ "start": 162, "end": 2047 }
class ____: def __init__(self): self.provider_map = OrderedDict() self.loaded = False def get_class_list(self): self.load() return list(self.provider_map.values()) def register(self, cls): self.provider_map[cls.id] = cls def get_class(self, id): return self.provider_map.get(id) def as_choices(self): self.load() for provider_cls in self.provider_map.values(): yield (provider_cls.id, provider_cls.name) def load(self): # TODO: Providers register with the provider registry when # loaded. Here, we build the URLs for all registered providers. So, we # really need to be sure all providers did register, which is why we're # forcefully importing the `provider` modules here. The overall # mechanism is way to magical and depends on the import order et al, so # all of this really needs to be revisited. if not self.loaded: for app_config in apps.get_app_configs(): try: module_name = app_config.name + ".provider" provider_module = importlib.import_module(module_name) except ImportError as e: if e.name != module_name: raise else: provider_settings = getattr(settings, "SOCIALACCOUNT_PROVIDERS", {}) for cls in getattr(provider_module, "provider_classes", []): provider_class = provider_settings.get(cls.id, {}).get( "provider_class" ) if provider_class: cls = import_attribute(provider_class) self.register(cls) self.loaded = True registry = ProviderRegistry()
ProviderRegistry
python
huggingface__transformers
src/transformers/models/deberta/modeling_deberta.py
{ "start": 44436, "end": 47698 }
class ____(DebertaPreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.deberta = DebertaModel(config) self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @auto_docstring def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, start_positions: Optional[torch.Tensor] = None, end_positions: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[tuple, QuestionAnsweringModelOutput]: return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.deberta( input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = outputs[0] logits = self.qa_outputs(sequence_output) start_logits, end_logits = logits.split(1, dim=-1) start_logits = start_logits.squeeze(-1).contiguous() end_logits = end_logits.squeeze(-1).contiguous() total_loss = None if start_positions is not None and end_positions is not None: # If we are on multi-GPU, split add a dimension if len(start_positions.size()) > 1: start_positions = start_positions.squeeze(-1) if len(end_positions.size()) > 1: end_positions = end_positions.squeeze(-1) # sometimes the start/end positions are outside our model inputs, we ignore these terms ignored_index = start_logits.size(1) start_positions = start_positions.clamp(0, ignored_index) end_positions = end_positions.clamp(0, ignored_index) loss_fct = CrossEntropyLoss(ignore_index=ignored_index) start_loss = loss_fct(start_logits, start_positions) end_loss = loss_fct(end_logits, end_positions) total_loss = (start_loss + end_loss) / 2 if not return_dict: output = (start_logits, end_logits) + outputs[1:] return ((total_loss,) + output) if total_loss is not None else output return QuestionAnsweringModelOutput( loss=total_loss, start_logits=start_logits, end_logits=end_logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) __all__ = [ "DebertaForMaskedLM", "DebertaForQuestionAnswering", "DebertaForSequenceClassification", "DebertaForTokenClassification", "DebertaModel", "DebertaPreTrainedModel", ]
DebertaForQuestionAnswering
python
Pylons__pyramid
src/pyramid/config/assets.py
{ "start": 9151, "end": 10429 }
class ____: """ An asset source relative to a path in the filesystem. """ def __init__(self, prefix): self.prefix = prefix def get_path(self, resource_name): if resource_name: path = os.path.join(self.prefix, resource_name) else: path = self.prefix return path def get_filename(self, resource_name): path = self.get_path(resource_name) if os.path.exists(path): return path def get_stream(self, resource_name): path = self.get_filename(resource_name) if path is not None: return open(path, 'rb') def get_string(self, resource_name): stream = self.get_stream(resource_name) if stream is not None: with stream: return stream.read() def exists(self, resource_name): path = self.get_filename(resource_name) if path is not None: return True def isdir(self, resource_name): path = self.get_filename(resource_name) if path is not None: return os.path.isdir(path) def listdir(self, resource_name): path = self.get_filename(resource_name) if path is not None: return os.listdir(path)
FSAssetSource
python
tensorflow__tensorflow
tensorflow/python/framework/ops_test.py
{ "start": 4039, "end": 15989 }
class ____(test_util.TensorFlowTestCase): def testShape(self): op = ops.Operation.from_node_def( ops._NodeDef("FloatOutput", "myop"), ops.Graph(), [], [dtypes.float32] ) t = op.outputs[0] self.assertEqual(tensor_shape.unknown_shape(), t.get_shape()) t.set_shape([1, 2, 3]) self.assertEqual([1, 2, 3], t.get_shape()) def testNdim(self): @def_function.function def f(a): self.assertEqual(a.ndim, 2) return 0 x = array_ops.zeros((3, 4)) f(x) def testIterable(self): if not context.executing_eagerly(): self.skipTest("Eager-mode test") op = ops.Operation.from_node_def( ops._NodeDef("FloatOutput", "myop"), ops.Graph(), [], [dtypes.float32] ) t = op.outputs[0] with self.assertRaisesRegex(TypeError, "Cannot iterate"): iter(t) def testIterableGraph(self): if context.executing_eagerly(): self.skipTest("Graph-mode test") op = ops.Operation.from_node_def( ops._NodeDef("FloatOutput", "myop"), ops.Graph(), [], [dtypes.float32] ) t = op.outputs[0] with self.assertRaisesRegex( TypeError, "Iterating.*not allowed.*Graph mode"): next(iter(t)) with self.assertRaisesRegex( TypeError, "Iterating.*AutoGraph.*unsupported feature"): with ag_ctx.ControlStatusCtx(ag_ctx.Status.ENABLED): next(iter(t)) with self.assertRaisesRegex( TypeError, "Iterating.*AutoGraph.*not be visible"): with ag_ctx.ControlStatusCtx(ag_ctx.Status.DISABLED): next(iter(t)) def testImplicitBool(self): op = ops.Operation.from_node_def( ops._NodeDef("FloatOutput", "myop"), ops.Graph(), [], [dtypes.bool] ) t = op.outputs[0] with self.assertRaisesRegex( TypeError, "Using.*as a.*bool.*not allowed.*Graph mode"): bool(t) with self.assertRaisesRegex( TypeError, "Using.*as a.*bool.*AutoGraph.*unsupported feature"): with ag_ctx.ControlStatusCtx(ag_ctx.Status.ENABLED): bool(t) with self.assertRaisesRegex( TypeError, "Using.*as a.*bool.*AutoGraph.*not be visible"): with ag_ctx.ControlStatusCtx(ag_ctx.Status.DISABLED): bool(t) def testAddShape(self): with self.cached_session(): a = array_ops.zeros([2, 3]) b = array_ops.ones([1, 3]) c = a + b self.assertEqual([2, 3], c.shape) @test_util.run_deprecated_v1 def testUnknownDim(self): with self.cached_session(): a = array_ops.placeholder(dtype=dtypes.float32, shape=[2, None, 3]) b = array_ops.placeholder(dtype=dtypes.float32, shape=[2, None, 3]) c = a + b self.assertEqual([2, None, 3], c.shape.as_list()) @test_util.run_deprecated_v1 def testUnknownShape(self): with self.cached_session(): a = array_ops.placeholder(dtype=dtypes.float32, shape=None) b = array_ops.ones([1, 3]) c = a + b self.assertEqual(tensor_shape.unknown_shape(), c.shape) @test_util.run_deprecated_v1 def testScalarShape(self): with self.cached_session(): a = array_ops.placeholder(dtype=dtypes.float32, shape=[]) b = array_ops.ones([]) c = a + b self.assertEqual(tensor_shape.TensorShape([]), c.shape) @test_util.run_deprecated_v1 def testShapeFunctionError(self): with self.cached_session(): a = array_ops.ones([1, 2, 3]) b = array_ops.ones([4, 5, 6]) with self.assertRaisesRegex( ValueError, r"Dimensions must be equal, but are 2 and 5 for .*add" r".*Add(V2)?.* with input shapes: \[1,2,3\], \[4,5,6\]."): _ = a + b def testNumpyArray(self): with ops.Graph().as_default(): x = array_ops.ones((3, 4), name="test_ones") with self.assertRaisesRegex(NotImplementedError, r"Cannot convert a symbolic.+test_ones"): np.array(x) with self.assertRaisesRegex(TypeError, "not well defined.+test_ones"): len(x) # EagerTensors should still behave as numpy arrays. with context.eager_mode(): x = array_ops.ones((3, 4)) self.assertAllEqual(x, np.ones((3, 4))) self.assertAllEqual(np.array(x), np.ones((3, 4))) self.assertLen(x, 3) def testConstructor(self): a = array_ops.ones([]) for name in ["T", "astype", "ravel", "transpose", "reshape", "clip", "size", "tolist", "data"]: with self.assertRaisesRegex( AttributeError, r"If you are looking for numpy-related methods"): getattr(a, name) with self.assertRaisesRegex( AttributeError, r"object has no attribute"): a.foo_bar() def testRef(self): x1 = constant_op.constant(3) x2 = x1 y = constant_op.constant(3) z = constant_op.constant([6, 10]) w = variables.Variable(5) self.assertEqual(x1.ref(), x1.ref()) self.assertEqual(x2.ref(), x2.ref()) self.assertEqual(x1.ref(), x2.ref()) self.assertEqual(y.ref(), y.ref()) self.assertEqual(z.ref(), z.ref()) self.assertEqual(w.ref(), w.ref()) self.assertNotEqual(x1.ref(), y.ref()) self.assertNotEqual(x1.ref(), z.ref()) self.assertNotEqual(x1.ref(), w.ref()) self.assertNotEqual(y.ref(), z.ref()) self.assertNotEqual(y.ref(), w.ref()) self.assertNotEqual(z.ref(), w.ref()) def testRefDeref(self): x1 = constant_op.constant(3) x2 = x1 y = constant_op.constant(3) z = constant_op.constant([6, 10]) w = variables.Variable(5) self.assertIs(x1, x1.ref().deref()) self.assertIs(x2, x2.ref().deref()) self.assertIs(x1, x2.ref().deref()) self.assertIs(x2, x1.ref().deref()) self.assertIs(y, y.ref().deref()) self.assertIs(z, z.ref().deref()) self.assertIsNot(x1, y.ref().deref()) self.assertIsNot(x1, z.ref().deref()) self.assertIsNot(x1, w.ref().deref()) self.assertIsNot(y, z.ref().deref()) self.assertIsNot(y, w.ref().deref()) self.assertIsNot(z, w.ref().deref()) def testRefInSet(self): x1 = constant_op.constant(3) x2 = x1 y = constant_op.constant(3) z = constant_op.constant([6, 10]) w = variables.Variable(5) self.assertEqual(x1.ref(), x2.ref()) tensor_set = { x1.ref(), x2.ref(), y.ref(), z.ref(), w.ref(), } self.assertLen(tensor_set, 4) self.assertIn(x1.ref(), tensor_set) self.assertIn(x2.ref(), tensor_set) self.assertIn(y.ref(), tensor_set) self.assertIn(z.ref(), tensor_set) self.assertIn(w.ref(), tensor_set) def testRefInDict(self): x1 = constant_op.constant(3) x2 = x1 y = constant_op.constant(3) z = constant_op.constant([6, 10]) w = variables.Variable(5) self.assertEqual(x1.ref(), x2.ref()) tensor_dict = { x1.ref(): "x1", y.ref(): "y", z.ref(): "z", w.ref(): "w", } self.assertLen(tensor_dict, 4) # Overwriting x1 tensor_dict[x2.ref()] = "x2" self.assertLen(tensor_dict, 4) self.assertEqual(tensor_dict[x1.ref()], "x2") self.assertEqual(tensor_dict[x2.ref()], "x2") self.assertEqual(tensor_dict[y.ref()], "y") self.assertEqual(tensor_dict[z.ref()], "z") self.assertEqual(tensor_dict[w.ref()], "w") def testTensorRefStrong(self): x = constant_op.constant(1.) x_ref = x.ref() del x self.assertIsNotNone(x_ref.deref()) def testVariableRefStrong(self): x = variables.Variable(1.) x_ref = x.ref() del x self.assertIsNotNone(x_ref.deref()) @test_util.run_in_graph_and_eager_modes def testBitwiseAndNumeric(self): x = constant_op.constant([0, 1, 3]) y = constant_op.constant([1, 1, 1]) z = x & y self.assertAllEqual(z, [0, 1, 1]) @test_util.run_in_graph_and_eager_modes def testBitwiseAndBool(self): x = constant_op.constant([False, False, True, True]) y = constant_op.constant([False, True, False, True]) z = x & y self.assertAllEqual(z, [False, False, False, True]) @test_util.run_in_graph_and_eager_modes def testBitwiseAndErrors(self): x_int = constant_op.constant(0) x_bool = constant_op.constant(True) if context.executing_eagerly(): # :( expected_errtype = errors.InvalidArgumentError else: expected_errtype = TypeError with self.assertRaises(expected_errtype): _ = x_int & x_bool with self.assertRaises(expected_errtype): _ = x_int & constant_op.constant("a") with self.assertRaises(expected_errtype): _ = x_bool & x_int with self.assertRaises(expected_errtype): _ = x_bool & constant_op.constant("a") with self.assertRaises(expected_errtype): _ = constant_op.constant("a") & constant_op.constant("b") @test_util.run_in_graph_and_eager_modes def testBitwiseOrNumeric(self): x = constant_op.constant([0, 1, 2]) y = constant_op.constant([1, 1, 1]) z = x | y self.assertAllEqual(z, [1, 1, 3]) @test_util.run_in_graph_and_eager_modes def testBitwiseOrBool(self): x = constant_op.constant([False, False, True, True]) y = constant_op.constant([False, True, False, True]) z = x | y self.assertAllEqual(z, [False, True, True, True]) @test_util.run_in_graph_and_eager_modes def testBitwiseOrErrors(self): x_int = constant_op.constant(0) x_bool = constant_op.constant(True) if context.executing_eagerly(): # :( expected_errtype = errors.InvalidArgumentError else: expected_errtype = TypeError with self.assertRaises(expected_errtype): _ = x_int | x_bool with self.assertRaises(expected_errtype): _ = x_int | constant_op.constant("a") with self.assertRaises(expected_errtype): _ = x_bool | x_int with self.assertRaises(expected_errtype): _ = x_bool | constant_op.constant("a") with self.assertRaises(expected_errtype): _ = constant_op.constant("a") | constant_op.constant("b") @test_util.run_in_graph_and_eager_modes def testBitwiseXorNumeric(self): x = constant_op.constant([0, 1, 3]) y = constant_op.constant([1, 1, 1]) z = x ^ y self.assertAllEqual(z, [1, 0, 2]) @test_util.run_in_graph_and_eager_modes def testBitwiseXorBool(self): x = constant_op.constant([False, False, True, True]) y = constant_op.constant([False, True, False, True]) z = x ^ y self.assertAllEqual(z, [False, True, True, False]) @test_util.run_in_graph_and_eager_modes def testBitwiseXorErrors(self): x_int = constant_op.constant(0) x_bool = constant_op.constant(True) if context.executing_eagerly(): # :( expected_errtype = errors.InvalidArgumentError else: expected_errtype = TypeError with self.assertRaises(expected_errtype): _ = x_int ^ x_bool with self.assertRaises(expected_errtype): _ = x_int ^ constant_op.constant("a") with self.assertRaises(expected_errtype): _ = x_bool ^ x_int with self.assertRaises(expected_errtype): _ = x_bool ^ constant_op.constant("a") with self.assertRaises(expected_errtype): _ = constant_op.constant("a") ^ constant_op.constant("b") @test_util.run_in_graph_and_eager_modes def testBitwiseNotNumeric(self): x = constant_op.constant([0, dtypes.int32.min, 1]) # pylint: disable=invalid-unary-operand-type y = ~x self.assertAllEqual(y, [-1, dtypes.int32.max, -2]) @test_util.run_in_graph_and_eager_modes def testBitwiseNotBool(self): x = constant_op.constant([False, True]) # pylint: disable=invalid-unary-operand-type y = ~x self.assertAllEqual(y, [True, False]) @test_util.run_in_graph_and_eager_modes def testBitwiseNotErrors(self): if context.executing_eagerly(): # :( expected_errtype = errors.InvalidArgumentError else: expected_errtype = TypeError # pylint: disable=invalid-unary-operand-type with self.assertRaises(expected_errtype): _ = ~constant_op.constant("a") @test_util.run_all_in_graph_and_eager_modes
TensorAndShapeTest