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
HypothesisWorks__hypothesis
hypothesis-python/tests/cover/test_cache_implementation.py
{ "start": 831, "end": 1206 }
class ____(GenericCache): __slots__ = ("__tick",) def __init__(self, max_size): super().__init__(max_size) self.__tick = 0 def new_entry(self, key, value): return self.tick() def on_access(self, key, value, score): return self.tick() def tick(self): self.__tick += 1 return self.__tick
LRUCacheAlternative
python
davidhalter__jedi
test/completion/classes.py
{ "start": 8755, "end": 8933 }
class ____(A()): b = 3 #? B.a #? B().a #? int() B.b #? int() B().b # ----------------- # With import # ----------------- from import_tree.classes import Config2, BaseClass
B
python
sympy__sympy
sympy/stats/crv_types.py
{ "start": 24757, "end": 26836 }
class ____(SingleContinuousDistribution): _argnames = ('k',) @staticmethod def check(k): _value_check(k > 0, "Number of degrees of freedom (k) must be positive.") _value_check(k.is_integer, "Number of degrees of freedom (k) must be an integer.") set = Interval(0, oo) def pdf(self, x): k = self.k return 1/(2**(k/2)*gamma(k/2))*x**(k/2 - 1)*exp(-x/2) def _cdf(self, x): k = self.k return Piecewise( (S.One/gamma(k/2)*lowergamma(k/2, x/2), x >= 0), (0, True) ) def _characteristic_function(self, t): return (1 - 2*I*t)**(-self.k/2) def _moment_generating_function(self, t): return (1 - 2*t)**(-self.k/2) def ChiSquared(name, k): r""" Create a continuous random variable with a Chi-squared distribution. Explanation =========== The density of the Chi-squared distribution is given by .. math:: f(x) := \frac{1}{2^{\frac{k}{2}}\Gamma\left(\frac{k}{2}\right)} x^{\frac{k}{2}-1} e^{-\frac{x}{2}} with :math:`x \geq 0`. Parameters ========== k : Positive integer The number of degrees of freedom. Returns ======= RandomSymbol Examples ======== >>> from sympy.stats import ChiSquared, density, E, variance, moment >>> from sympy import Symbol >>> k = Symbol("k", integer=True, positive=True) >>> z = Symbol("z") >>> X = ChiSquared("x", k) >>> density(X)(z) z**(k/2 - 1)*exp(-z/2)/(2**(k/2)*gamma(k/2)) >>> E(X) k >>> variance(X) 2*k >>> moment(X, 3) k**3 + 6*k**2 + 8*k References ========== .. [1] https://en.wikipedia.org/wiki/Chi_squared_distribution .. [2] https://mathworld.wolfram.com/Chi-SquaredDistribution.html """ return rv(name, ChiSquaredDistribution, (k, )) #------------------------------------------------------------------------------- # Dagum distribution -----------------------------------------------------------
ChiSquaredDistribution
python
pytorch__pytorch
test/jit/test_backends.py
{ "start": 25527, "end": 27286 }
class ____(JitBackendTestCase): """ Tests for CompModule, which is a module with two lowered submodules with same module name """ class ModuleAdd(torch.nn.Module): """ A simple Module used to test to_backend lowering machinery. """ def forward(self, x, h): return x + h class CompModule(torch.nn.Module): """ A module with two lowered submodules. """ def __init__(self) -> None: super().__init__() compile_spec = { "forward": { "some_other_option": "True", }, } self.add = torch._C._jit_to_backend( "backend_with_compiler_demo", torch.jit.script(ModuleAdd()), # noqa: F821 compile_spec, ) self.sub = torch._C._jit_to_backend( "backend_with_compiler_demo", torch.jit.script(ModuleAdd()), # noqa: F821 compile_spec, ) def forward(self, a, b, s: int): c = self.add.forward(a, b) d = self.sub.forward(a, b) y = s * (c * d) return y def setUp(self): super().setUp() self.module = CompModule() # noqa: F821 self.scripted_module = torch.jit.script(self.module) buffer = io.BytesIO(self.scripted_module._save_to_buffer_for_lite_interpreter()) buffer.seek(0) self.mobile_module = _load_for_lite_interpreter(buffer) def test_execution(self): a = torch.ones(1) b = 3 * torch.ones(1) s = 3 # Test forward. self.check_function("forward", (a, b, s))
CompModuleTestSameNameWithCompiler
python
pytorch__pytorch
test/inductor/test_extension_backend.py
{ "start": 3392, "end": 5973 }
class ____(BaseExtensionBackendTests): @skipIfWindows def test_open_device_registration(self): torch.utils.rename_privateuse1_backend("extension_device") torch._register_device_module("extension_device", self.module) register_backend_for_device( "extension_device", ExtensionScheduling, ExtensionWrapperCodegen, ExtensionCppWrapperCodegen, ) self.assertTrue( get_scheduling_for_device("extension_device") == ExtensionScheduling ) self.assertTrue( get_wrapper_codegen_for_device("extension_device") == ExtensionWrapperCodegen ) self.assertTrue( get_wrapper_codegen_for_device("extension_device", True) == ExtensionCppWrapperCodegen ) self.assertFalse(self.module.custom_op_called()) device = self.module.custom_device() x = torch.empty(2, 16).to(device=device).fill_(1) self.assertTrue(self.module.custom_op_called()) y = torch.empty(2, 16).to(device=device).fill_(2) z = torch.empty(2, 16).to(device=device).fill_(3) ref = torch.empty(2, 16).fill_(5) self.assertTrue(x.device == device) self.assertTrue(y.device == device) self.assertTrue(z.device == device) def fn(a, b, c): return a * b + c cpp_utils.DEVICE_TO_ATEN["extension_device"] = "at::kPrivateUse1" for cpp_wrapper_flag in [True, False]: with config.patch({"cpp_wrapper": cpp_wrapper_flag}): metrics.reset() opt_fn = torch.compile()(fn) _, code = run_and_get_cpp_code(opt_fn, x, y, z) if ( cpu_vec_isa.valid_vec_isa_list() and os.getenv("ATEN_CPU_CAPABILITY") != "default" ): load_expr = "loadu" else: load_expr = " = in_ptr0[static_cast<long>(i0)];" FileCheck().check("void").check(load_expr).check( "extension_device" ).run(code) opt_fn(x, y, z) res = opt_fn(x, y, z) self.assertEqual(ref, res.to(device="cpu")) if __name__ == "__main__": from torch._inductor.test_case import run_tests from torch.testing._internal.inductor_utils import HAS_CPU # cpp_extension doesn't work in fbcode right now if HAS_CPU and not IS_MACOS and not IS_FBCODE: run_tests(needs="filelock")
ExtensionBackendTests
python
apache__airflow
providers/salesforce/tests/unit/salesforce/hooks/test_salesforce.py
{ "start": 1170, "end": 20853 }
class ____: def setup_method(self): self.salesforce_hook = SalesforceHook(salesforce_conn_id="conn_id") def test_get_conn_exists(self): self.salesforce_hook.conn = Mock(spec=Salesforce) self.salesforce_hook.get_conn() assert self.salesforce_hook.conn.return_value is not None @patch("airflow.providers.salesforce.hooks.salesforce.Salesforce") def test_get_conn_password_auth(self, mock_salesforce, create_connection_without_db): """ Testing mock password authentication to Salesforce. Users should provide a username, password, and security token in the Connection. Providing a client ID, Salesforce API version, proxy mapping, and domain are optional. Connection params not provided or set as empty strings should be converted to `None`. """ password_auth_conn = Connection( conn_id="password_auth_conn", conn_type="salesforce", login=None, password=None, extra=""" { "client_id": "my_client", "domain": "test", "security_token": "token", "version": "42.0" } """, ) create_connection_without_db(password_auth_conn) self.salesforce_hook = SalesforceHook(salesforce_conn_id="password_auth_conn") self.salesforce_hook.get_conn() extras = password_auth_conn.extra_dejson mock_salesforce.assert_called_once_with( username=password_auth_conn.login, password=password_auth_conn.password, security_token=extras["security_token"], domain=extras["domain"], session_id=None, instance=None, instance_url=None, organizationId=None, version=extras["version"], proxies=None, session=None, client_id=extras["client_id"], consumer_key=None, consumer_secret=None, privatekey_file=None, privatekey=None, ) @patch("airflow.providers.salesforce.hooks.salesforce.Salesforce") def test_get_conn_direct_session_access(self, mock_salesforce, create_connection_without_db): """ Testing mock direct session access to Salesforce. Users should provide an instance (or instance URL) in the Connection and set a `session_id` value when calling `SalesforceHook`. Providing a client ID, Salesforce API version, proxy mapping, and domain are optional. Connection params not provided or set as empty strings should be converted to `None`. """ direct_access_conn = Connection( conn_id="direct_access_conn", conn_type="salesforce", login=None, password=None, extra=""" { "client_id": "my_client2", "domain": "test", "instance_url": "https://my.salesforce.com", "version": "29.0" } """, ) create_connection_without_db(direct_access_conn) with request_session() as session: self.salesforce_hook = SalesforceHook( salesforce_conn_id="direct_access_conn", session_id="session_id", session=session ) self.salesforce_hook.get_conn() extras = direct_access_conn.extra_dejson mock_salesforce.assert_called_once_with( username=direct_access_conn.login, password=direct_access_conn.password, security_token=None, domain=extras["domain"], session_id=self.salesforce_hook.session_id, instance=None, instance_url=extras["instance_url"], organizationId=None, version=extras["version"], proxies=None, session=self.salesforce_hook.session, client_id=extras["client_id"], consumer_key=None, consumer_secret=None, privatekey_file=None, privatekey=None, ) @patch("airflow.providers.salesforce.hooks.salesforce.Salesforce") def test_get_conn_jwt_auth(self, mock_salesforce, create_connection_without_db): """ Testing mock JWT bearer authentication to Salesforce. Users should provide consumer key and private key (or path to a private key) in the Connection. Providing a client ID, Salesforce API version, proxy mapping, and domain are optional. Connection params not provided or set as empty strings should be converted to `None`. """ jwt_auth_conn = Connection( conn_id="jwt_auth_conn", conn_type="salesforce", login=None, password=None, extra=""" { "client_id": "my_client3", "consumer_key": "consumer_key", "consumer_secret": "consumer_secret", "domain": "login", "private_key": "private_key", "version": "34.0" } """, ) create_connection_without_db(jwt_auth_conn) self.salesforce_hook = SalesforceHook(salesforce_conn_id="jwt_auth_conn") self.salesforce_hook.get_conn() extras = jwt_auth_conn.extra_dejson mock_salesforce.assert_called_once_with( username=jwt_auth_conn.login, password=jwt_auth_conn.password, security_token=None, domain=extras["domain"], session_id=None, instance=None, instance_url=None, organizationId=None, version=extras["version"], proxies=None, session=None, client_id=extras["client_id"], consumer_key=extras["consumer_key"], consumer_secret=extras["consumer_secret"], privatekey_file=None, privatekey=extras["private_key"], ) @patch("airflow.providers.salesforce.hooks.salesforce.Salesforce") def test_get_conn_ip_filtering_auth(self, mock_salesforce, create_connection_without_db): """ Testing mock IP filtering (aka allow-listing) authentication to Salesforce. Users should provide username, password, and organization ID in the Connection. Providing a client ID, Salesforce API version, proxy mapping, and domain are optional. Connection params not provided or set as empty strings should be converted to `None`. """ ip_filtering_auth_conn = Connection( conn_id="ip_filtering_auth_conn", conn_type="salesforce", login="username", password="password", extra=""" { "organization_id": "my_organization" } """, ) create_connection_without_db(ip_filtering_auth_conn) self.salesforce_hook = SalesforceHook(salesforce_conn_id="ip_filtering_auth_conn") self.salesforce_hook.get_conn() extras = ip_filtering_auth_conn.extra_dejson mock_salesforce.assert_called_once_with( username=ip_filtering_auth_conn.login, password=ip_filtering_auth_conn.password, security_token=None, domain=None, session_id=None, instance=None, instance_url=None, organizationId=extras["organization_id"], version=api.DEFAULT_API_VERSION, proxies=None, session=None, client_id=None, consumer_key=None, consumer_secret=None, privatekey_file=None, privatekey=None, ) @patch("airflow.providers.salesforce.hooks.salesforce.Salesforce") def test_get_conn_default_to_none( self, mock_salesforce, create_connection_without_db, mock_supervisor_comms ): """ Testing mock authentication to Salesforce so that every extra connection param set as an empty string will be converted to `None`. """ default_to_none_conn = Connection( conn_id="default_to_none_conn", conn_type="salesforce", login=None, password=None, extra=""" { "client_id": "", "consumer_key": "", "consumer_secret": "", "domain": "", "instance": "", "instance_url": "", "organization_id": "", "private_key": "", "private_key_file_path": "", "proxies": "", "security_token": "" } """, ) create_connection_without_db(default_to_none_conn) self.salesforce_hook = SalesforceHook(salesforce_conn_id="default_to_none_conn") self.salesforce_hook.get_conn() mock_salesforce.assert_called_once_with( username=default_to_none_conn.login, password=default_to_none_conn.password, security_token=None, domain=None, session_id=None, instance=None, instance_url=None, organizationId=None, version=api.DEFAULT_API_VERSION, proxies=None, session=None, client_id=None, consumer_key=None, consumer_secret=None, privatekey_file=None, privatekey=None, ) @patch("airflow.providers.salesforce.hooks.salesforce.Salesforce") def test_make_query(self, mock_salesforce): mock_salesforce.return_value.query_all.return_value = dict(totalSize=123, done=True) self.salesforce_hook.conn = mock_salesforce.return_value query = "SELECT * FROM table" query_results = self.salesforce_hook.make_query(query, include_deleted=True) mock_salesforce.return_value.query_all.assert_called_once_with(query, include_deleted=True) assert query_results == mock_salesforce.return_value.query_all.return_value @patch("airflow.providers.salesforce.hooks.salesforce.Salesforce") def test_describe_object(self, mock_salesforce): obj = "obj_name" mock_salesforce.return_value.__setattr__(obj, Mock(spec=Salesforce)) self.salesforce_hook.conn = mock_salesforce.return_value obj_description = self.salesforce_hook.describe_object(obj) mock_salesforce.return_value.__getattr__(obj).describe.assert_called_once_with() assert obj_description == mock_salesforce.return_value.__getattr__(obj).describe.return_value @patch( "airflow.providers.salesforce.hooks.salesforce.SalesforceHook.describe_object", return_value={"fields": [{"name": "field_1"}, {"name": "field_2"}]}, ) def test_get_available_fields(self, mock_describe_object): obj = "obj_name" available_fields = self.salesforce_hook.get_available_fields(obj) mock_describe_object.assert_called_once_with(obj) assert available_fields == ["field_1", "field_2"] @patch("airflow.providers.salesforce.hooks.salesforce.SalesforceHook.make_query") def test_get_object_from_salesforce(self, mock_make_query): salesforce_objects = self.salesforce_hook.get_object_from_salesforce( obj="obj_name", fields=["field_1", "field_2"] ) mock_make_query.assert_called_once_with("SELECT field_1,field_2 FROM obj_name") assert salesforce_objects == mock_make_query.return_value def test_write_object_to_file_invalid_format(self): with pytest.raises(ValueError, match="Format value is not recognized: test"): self.salesforce_hook.write_object_to_file(query_results=[], filename="test", fmt="test") @patch( "pandas.DataFrame.from_records", return_value=pd.DataFrame({"test": [1, 2, 3], "dict": [np.nan, np.nan, {"foo": "bar"}]}), ) def test_write_object_to_file_csv(self, mock_data_frame): mock_data_frame.return_value.to_csv = Mock() filename = "test" data_frame = self.salesforce_hook.write_object_to_file(query_results=[], filename=filename, fmt="csv") mock_data_frame.return_value.to_csv.assert_called_once_with(filename, index=False) # Note that the latest version of pandas dataframes (1.1.2) returns "nan" rather than "None" here pd.testing.assert_frame_equal( data_frame, pd.DataFrame({"test": [1, 2, 3], "dict": ["nan", "nan", str({"foo": "bar"})]}), check_index_type=False, ) @patch( "airflow.providers.salesforce.hooks.salesforce.SalesforceHook.describe_object", return_value={"fields": [{"name": "field_1", "type": "date"}]}, ) @patch( "pandas.DataFrame.from_records", return_value=pd.DataFrame({"test": [1, 2, 3], "field_1": ["2019-01-01", "2019-01-02", "2019-01-03"]}), ) def test_write_object_to_file_json_with_timestamp_conversion(self, mock_data_frame, mock_describe_object): mock_data_frame.return_value.to_json = Mock() filename = "test" obj_name = "obj_name" data_frame = self.salesforce_hook.write_object_to_file( query_results=[{"attributes": {"type": obj_name}}], filename=filename, fmt="json", coerce_to_timestamp=True, ) mock_describe_object.assert_called_once_with(obj_name) mock_data_frame.return_value.to_json.assert_called_once_with( filename, orient="records", date_unit="s" ) pd.testing.assert_frame_equal( data_frame, pd.DataFrame({"test": [1, 2, 3], "field_1": [1.546301e09, 1.546387e09, 1.546474e09]}) ) @patch("airflow.providers.salesforce.hooks.salesforce.time.time", return_value=1.23) @patch( "pandas.DataFrame.from_records", return_value=pd.DataFrame({"test": [1, 2, 3]}), ) def test_write_object_to_file_ndjson_with_record_time(self, mock_data_frame, mock_time): mock_data_frame.return_value.to_json = Mock() filename = "test" data_frame = self.salesforce_hook.write_object_to_file( query_results=[], filename=filename, fmt="ndjson", record_time_added=True ) mock_data_frame.return_value.to_json.assert_called_once_with( filename, orient="records", lines=True, date_unit="s" ) pd.testing.assert_frame_equal( data_frame, pd.DataFrame( { "test": [1, 2, 3], "time_fetched_from_salesforce": [ mock_time.return_value, mock_time.return_value, mock_time.return_value, ], } ), ) @patch( "airflow.providers.salesforce.hooks.salesforce.SalesforceHook.describe_object", return_value={"fields": [{"name": "field_1", "type": "date"}]}, ) @patch( "pandas.DataFrame.from_records", return_value=pd.DataFrame( {"test": [1, 2, 3, 4], "field_1": ["2019-01-01", "2019-01-02", "2019-01-03", "NaT"]} ), ) def test_object_to_df_with_timestamp_conversion(self, mock_data_frame, mock_describe_object): obj_name = "obj_name" data_frame = self.salesforce_hook.object_to_df( query_results=[{"attributes": {"type": obj_name}}], coerce_to_timestamp=True, ) mock_describe_object.assert_called_once_with(obj_name) pd.testing.assert_frame_equal( data_frame, pd.DataFrame({"test": [1, 2, 3, 4], "field_1": [1.546301e09, 1.546387e09, 1.546474e09, np.nan]}), ) @patch("airflow.providers.salesforce.hooks.salesforce.time.time", return_value=1.23) @patch( "pandas.DataFrame.from_records", return_value=pd.DataFrame({"test": [1, 2, 3]}), ) def test_object_to_df_with_record_time(self, mock_data_frame, mock_time): data_frame = self.salesforce_hook.object_to_df(query_results=[], record_time_added=True) pd.testing.assert_frame_equal( data_frame, pd.DataFrame( { "test": [1, 2, 3], "time_fetched_from_salesforce": [ mock_time.return_value, mock_time.return_value, mock_time.return_value, ], } ), ) @pytest.mark.parametrize( "uri", [ pytest.param( "a://?extra__salesforce__security_token=token&extra__salesforce__domain=domain", id="prefix", ), pytest.param("a://?security_token=token&domain=domain", id="no-prefix"), ], ) @patch("airflow.providers.salesforce.hooks.salesforce.Salesforce") def test_backcompat_prefix_works(self, mock_client, uri): with patch.dict(os.environ, {"AIRFLOW_CONN_MY_CONN": uri}): hook = SalesforceHook("my_conn") hook.get_conn() mock_client.assert_called_with( client_id=None, consumer_key=None, consumer_secret=None, domain="domain", instance=None, instance_url=None, organizationId=None, password=None, privatekey=None, privatekey_file=None, proxies=None, security_token="token", session=None, session_id=None, username=None, version=mock.ANY, ) @patch("airflow.providers.salesforce.hooks.salesforce.Salesforce") def test_backcompat_prefix_both_prefers_short(self, mock_client): with patch.dict( os.environ, { "AIRFLOW_CONN_MY_CONN": "a://?security_token=non-prefixed" "&extra__salesforce__security_token=prefixed" }, ): hook = SalesforceHook("my_conn") hook.get_conn() mock_client.assert_called_with( client_id=None, consumer_key=None, consumer_secret=None, domain=None, instance=None, instance_url=None, organizationId=None, password=None, privatekey=None, privatekey_file=None, proxies=None, security_token="non-prefixed", session=None, session_id=None, username=None, version=mock.ANY, ) @patch( "airflow.providers.salesforce.hooks.salesforce.SalesforceHook.describe_object", return_value={"fields": [{"name": "field_1"}, {"name": "field_2"}]}, ) def test_connection_success(self, mock_describe_object): hook = SalesforceHook("my_conn") status, msg = hook.test_connection() assert status is True assert msg == "Connection successfully tested" @patch( "airflow.providers.salesforce.hooks.salesforce.SalesforceHook.describe_object", side_effect=Exception("Test"), ) def test_connection_failure(self, mock_describe_object): hook = SalesforceHook("my_conn") status, msg = hook.test_connection() assert status is False assert msg == "Test"
TestSalesforceHook
python
pennersr__django-allauth
tests/apps/socialaccount/providers/spotify/tests.py
{ "start": 248, "end": 1351 }
class ____(OAuth2TestsMixin, TestCase): provider_id = SpotifyOAuth2Provider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """{ "birthdate": "1937-06-01", "country": "SE", "display_name": "JM Wizzler", "email": "email@example.com", "external_urls": { "spotify": "https://open.spotify.com/user/wizzler" }, "followers" : { "href" : null, "total" : 3829 }, "href": "https://api.spotify.com/v1/users/wizzler", "id": "wizzler", "images": [ { "height": null, "url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-frc3/t1.0-1/1970403_10152215092574354_1798272330_n.jpg", "width": null } ], "product": "premium", "type": "user", "uri": "spotify:user:wizzler" }""", ) # noqa def get_expected_to_str(self): return "email@example.com"
SpotifyOAuth2Tests
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_userdict.py
{ "start": 1750, "end": 9482 }
class ____(mapping_tests.TestHashMappingProtocol): type2test = collections.UserDict def test_all(self): # Test constructors u = collections.UserDict() u0 = collections.UserDict(d0) u1 = collections.UserDict(d1) u2 = collections.UserDict(d2) uu = collections.UserDict(u) uu0 = collections.UserDict(u0) uu1 = collections.UserDict(u1) uu2 = collections.UserDict(u2) # keyword arg constructor self.assertEqual(collections.UserDict(one=1, two=2), d2) # item sequence constructor self.assertEqual(collections.UserDict([('one',1), ('two',2)]), d2) self.assertEqual(collections.UserDict(dict=[('one',1), ('two',2)]), {'dict': [('one', 1), ('two', 2)]}) # both together self.assertEqual(collections.UserDict([('one',1), ('two',2)], two=3, three=5), d3) # alternate constructor self.assertEqual(collections.UserDict.fromkeys('one two'.split()), d4) self.assertEqual(collections.UserDict().fromkeys('one two'.split()), d4) self.assertEqual(collections.UserDict.fromkeys('one two'.split(), 1), d5) self.assertEqual(collections.UserDict().fromkeys('one two'.split(), 1), d5) self.assertTrue(u1.fromkeys('one two'.split()) is not u1) self.assertIsInstance(u1.fromkeys('one two'.split()), collections.UserDict) self.assertIsInstance(u2.fromkeys('one two'.split()), collections.UserDict) # Test __repr__ self.assertEqual(str(u0), str(d0)) self.assertEqual(repr(u1), repr(d1)) self.assertIn(repr(u2), ("{'one': 1, 'two': 2}", "{'two': 2, 'one': 1}")) # Test rich comparison and __len__ all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2] for a in all: for b in all: self.assertEqual(a == b, len(a) == len(b)) # Test __getitem__ self.assertEqual(u2["one"], 1) self.assertRaises(KeyError, u1.__getitem__, "two") # Test __setitem__ u3 = collections.UserDict(u2) u3["two"] = 2 u3["three"] = 3 # Test __delitem__ del u3["three"] self.assertRaises(KeyError, u3.__delitem__, "three") # Test clear u3.clear() self.assertEqual(u3, {}) # Test copy() u2a = u2.copy() self.assertEqual(u2a, u2) u2b = collections.UserDict(x=42, y=23) u2c = u2b.copy() # making a copy of a UserDict is special cased self.assertEqual(u2b, u2c) class MyUserDict(collections.UserDict): def display(self): print(self) m2 = MyUserDict(u2) m2a = m2.copy() self.assertEqual(m2a, m2) # SF bug #476616 -- copy() of UserDict subclass shared data m2['foo'] = 'bar' self.assertNotEqual(m2a, m2) # Test keys, items, values self.assertEqual(sorted(u2.keys()), sorted(d2.keys())) self.assertEqual(sorted(u2.items()), sorted(d2.items())) self.assertEqual(sorted(u2.values()), sorted(d2.values())) # Test "in". for i in u2.keys(): self.assertIn(i, u2) self.assertEqual(i in u1, i in d1) self.assertEqual(i in u0, i in d0) # Test update t = collections.UserDict() t.update(u2) self.assertEqual(t, u2) # Test get for i in u2.keys(): self.assertEqual(u2.get(i), u2[i]) self.assertEqual(u1.get(i), d1.get(i)) self.assertEqual(u0.get(i), d0.get(i)) # Test "in" iteration. for i in range(20): u2[i] = str(i) ikeys = [] for k in u2: ikeys.append(k) keys = u2.keys() self.assertEqual(set(ikeys), set(keys)) # Test setdefault t = collections.UserDict() self.assertEqual(t.setdefault("x", 42), 42) self.assertIn("x", t) self.assertEqual(t.setdefault("x", 23), 42) # Test pop t = collections.UserDict(x=42) self.assertEqual(t.pop("x"), 42) self.assertRaises(KeyError, t.pop, "x") self.assertEqual(t.pop("x", 1), 1) t["x"] = 42 self.assertEqual(t.pop("x", 1), 42) # Test popitem t = collections.UserDict(x=42) self.assertEqual(t.popitem(), ("x", 42)) self.assertRaises(KeyError, t.popitem) def test_init(self): for kw in 'self', 'other', 'iterable': self.assertEqual(list(collections.UserDict(**{kw: 42}).items()), [(kw, 42)]) self.assertEqual(list(collections.UserDict({}, dict=42).items()), [('dict', 42)]) self.assertEqual(list(collections.UserDict({}, dict=None).items()), [('dict', None)]) self.assertEqual(list(collections.UserDict(dict={'a': 42}).items()), [('dict', {'a': 42})]) self.assertRaises(TypeError, collections.UserDict, 42) self.assertRaises(TypeError, collections.UserDict, (), ()) self.assertRaises(TypeError, collections.UserDict.__init__) def test_update(self): for kw in 'self', 'dict', 'other', 'iterable': d = collections.UserDict() d.update(**{kw: 42}) self.assertEqual(list(d.items()), [(kw, 42)]) self.assertRaises(TypeError, collections.UserDict().update, 42) self.assertRaises(TypeError, collections.UserDict().update, {}, {}) self.assertRaises(TypeError, collections.UserDict.update) def test_missing(self): # Make sure UserDict doesn't have a __missing__ method self.assertEqual(hasattr(collections.UserDict, "__missing__"), False) # Test several cases: # (D) subclass defines __missing__ method returning a value # (E) subclass defines __missing__ method raising RuntimeError # (F) subclass sets __missing__ instance variable (no effect) # (G) subclass doesn't define __missing__ at all class D(collections.UserDict): def __missing__(self, key): return 42 d = D({1: 2, 3: 4}) self.assertEqual(d[1], 2) self.assertEqual(d[3], 4) self.assertNotIn(2, d) self.assertNotIn(2, d.keys()) self.assertEqual(d[2], 42) class E(collections.UserDict): def __missing__(self, key): raise RuntimeError(key) e = E() try: e[42] except RuntimeError as err: self.assertEqual(err.args, (42,)) else: self.fail("e[42] didn't raise RuntimeError") class F(collections.UserDict): def __init__(self): # An instance variable __missing__ should have no effect self.__missing__ = lambda key: None collections.UserDict.__init__(self) f = F() try: f[42] except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail("f[42] didn't raise KeyError") class G(collections.UserDict): pass g = G() try: g[42] except KeyError as err: self.assertEqual(err.args, (42,)) else: self.fail("g[42] didn't raise KeyError") # Decorate existing test with recursion limit, because # the test is for C structure, but `UserDict` is a Python structure. # test_repr_deep = support.infinite_recursion(25)( # mapping_tests.TestHashMappingProtocol.test_repr_deep, # ) if __name__ == "__main__": run_tests()
UserDictTest
python
Pylons__pyramid
tests/test_authentication.py
{ "start": 24120, "end": 50172 }
class ____(unittest.TestCase): def _getTargetClass(self): from pyramid.authentication import AuthTktCookieHelper return AuthTktCookieHelper def _makeOne(self, *arg, **kw): helper = self._getTargetClass()(*arg, **kw) # laziness after moving auth_tkt classes and funcs into # authentication module auth_tkt = DummyAuthTktModule() helper.auth_tkt = auth_tkt helper.AuthTicket = auth_tkt.AuthTicket helper.parse_ticket = auth_tkt.parse_ticket helper.BadTicket = auth_tkt.BadTicket return helper def _makeRequest(self, cookie=None, ipv6=False): environ = {'wsgi.version': (1, 0)} if ipv6 is False: environ['REMOTE_ADDR'] = '1.1.1.1' else: environ['REMOTE_ADDR'] = '::1' environ['SERVER_NAME'] = 'localhost' return DummyRequest(environ, cookie=cookie) def _cookieValue(self, cookie): items = cookie.value.split('/') D = {} for item in items: k, v = item.split('=', 1) D[k] = v return D def _parseHeaders(self, headers): return [self._parseHeader(header) for header in headers] def _parseHeader(self, header): cookie = self._parseCookie(header[1]) return cookie def _parseCookie(self, cookie): cookies = SimpleCookie() cookies.load(cookie) return cookies.get('auth_tkt') def test_init_cookie_str_reissue_invalid(self): self.assertRaises( ValueError, self._makeOne, 'secret', reissue_time='invalid value' ) def test_init_cookie_str_timeout_invalid(self): self.assertRaises( ValueError, self._makeOne, 'secret', timeout='invalid value' ) def test_init_cookie_str_max_age_invalid(self): self.assertRaises( ValueError, self._makeOne, 'secret', max_age='invalid value' ) def test_identify_nocookie(self): helper = self._makeOne('secret') request = self._makeRequest() result = helper.identify(request) self.assertEqual(result, None) def test_identify_cookie_value_is_None(self): helper = self._makeOne('secret') request = self._makeRequest(None) result = helper.identify(request) self.assertEqual(result, None) def test_identify_good_cookie_include_ip(self): helper = self._makeOne('secret', include_ip=True) request = self._makeRequest('ticket') result = helper.identify(request) self.assertEqual(len(result), 4) self.assertEqual(result['tokens'], ()) self.assertEqual(result['userid'], 'userid') self.assertEqual(result['userdata'], '') self.assertEqual(result['timestamp'], 0) self.assertEqual(helper.auth_tkt.value, 'ticket') self.assertEqual(helper.auth_tkt.remote_addr, '1.1.1.1') self.assertEqual(helper.auth_tkt.secret, 'secret') environ = request.environ self.assertEqual(environ['REMOTE_USER_TOKENS'], ()) self.assertEqual(environ['REMOTE_USER_DATA'], '') self.assertEqual(environ['AUTH_TYPE'], 'cookie') def test_identify_good_cookie_include_ipv6(self): helper = self._makeOne('secret', include_ip=True) request = self._makeRequest('ticket', ipv6=True) result = helper.identify(request) self.assertEqual(len(result), 4) self.assertEqual(result['tokens'], ()) self.assertEqual(result['userid'], 'userid') self.assertEqual(result['userdata'], '') self.assertEqual(result['timestamp'], 0) self.assertEqual(helper.auth_tkt.value, 'ticket') self.assertEqual(helper.auth_tkt.remote_addr, '::1') self.assertEqual(helper.auth_tkt.secret, 'secret') environ = request.environ self.assertEqual(environ['REMOTE_USER_TOKENS'], ()) self.assertEqual(environ['REMOTE_USER_DATA'], '') self.assertEqual(environ['AUTH_TYPE'], 'cookie') def test_identify_good_cookie_dont_include_ip(self): helper = self._makeOne('secret', include_ip=False) request = self._makeRequest('ticket') result = helper.identify(request) self.assertEqual(len(result), 4) self.assertEqual(result['tokens'], ()) self.assertEqual(result['userid'], 'userid') self.assertEqual(result['userdata'], '') self.assertEqual(result['timestamp'], 0) self.assertEqual(helper.auth_tkt.value, 'ticket') self.assertEqual(helper.auth_tkt.remote_addr, '0.0.0.0') self.assertEqual(helper.auth_tkt.secret, 'secret') environ = request.environ self.assertEqual(environ['REMOTE_USER_TOKENS'], ()) self.assertEqual(environ['REMOTE_USER_DATA'], '') self.assertEqual(environ['AUTH_TYPE'], 'cookie') def test_identify_good_cookie_int_useridtype(self): helper = self._makeOne('secret', include_ip=False) helper.auth_tkt.userid = '1' helper.auth_tkt.user_data = 'userid_type:int' request = self._makeRequest('ticket') result = helper.identify(request) self.assertEqual(len(result), 4) self.assertEqual(result['tokens'], ()) self.assertEqual(result['userid'], 1) self.assertEqual(result['userdata'], 'userid_type:int') self.assertEqual(result['timestamp'], 0) environ = request.environ self.assertEqual(environ['REMOTE_USER_TOKENS'], ()) self.assertEqual(environ['REMOTE_USER_DATA'], 'userid_type:int') self.assertEqual(environ['AUTH_TYPE'], 'cookie') def test_identify_nonuseridtype_user_data(self): helper = self._makeOne('secret', include_ip=False) helper.auth_tkt.userid = '1' helper.auth_tkt.user_data = 'bogus:int' request = self._makeRequest('ticket') result = helper.identify(request) self.assertEqual(len(result), 4) self.assertEqual(result['tokens'], ()) self.assertEqual(result['userid'], '1') self.assertEqual(result['userdata'], 'bogus:int') self.assertEqual(result['timestamp'], 0) environ = request.environ self.assertEqual(environ['REMOTE_USER_TOKENS'], ()) self.assertEqual(environ['REMOTE_USER_DATA'], 'bogus:int') self.assertEqual(environ['AUTH_TYPE'], 'cookie') def test_identify_good_cookie_unknown_useridtype(self): helper = self._makeOne('secret', include_ip=False) helper.auth_tkt.userid = 'abc' helper.auth_tkt.user_data = 'userid_type:unknown' request = self._makeRequest('ticket') result = helper.identify(request) self.assertEqual(len(result), 4) self.assertEqual(result['tokens'], ()) self.assertEqual(result['userid'], 'abc') self.assertEqual(result['userdata'], 'userid_type:unknown') self.assertEqual(result['timestamp'], 0) environ = request.environ self.assertEqual(environ['REMOTE_USER_TOKENS'], ()) self.assertEqual(environ['REMOTE_USER_DATA'], 'userid_type:unknown') self.assertEqual(environ['AUTH_TYPE'], 'cookie') def test_identify_good_cookie_b64str_useridtype(self): from base64 import b64encode helper = self._makeOne('secret', include_ip=False) helper.auth_tkt.userid = b64encode(b'encoded').strip() helper.auth_tkt.user_data = 'userid_type:b64str' request = self._makeRequest('ticket') result = helper.identify(request) self.assertEqual(len(result), 4) self.assertEqual(result['tokens'], ()) self.assertEqual(result['userid'], b'encoded') self.assertEqual(result['userdata'], 'userid_type:b64str') self.assertEqual(result['timestamp'], 0) environ = request.environ self.assertEqual(environ['REMOTE_USER_TOKENS'], ()) self.assertEqual(environ['REMOTE_USER_DATA'], 'userid_type:b64str') self.assertEqual(environ['AUTH_TYPE'], 'cookie') def test_identify_good_cookie_b64unicode_useridtype(self): from base64 import b64encode helper = self._makeOne('secret', include_ip=False) helper.auth_tkt.userid = b64encode(b'\xc3\xa9ncoded').strip() helper.auth_tkt.user_data = 'userid_type:b64unicode' request = self._makeRequest('ticket') result = helper.identify(request) self.assertEqual(len(result), 4) self.assertEqual(result['tokens'], ()) self.assertEqual(result['userid'], text_(b'\xc3\xa9ncoded', 'utf-8')) self.assertEqual(result['userdata'], 'userid_type:b64unicode') self.assertEqual(result['timestamp'], 0) environ = request.environ self.assertEqual(environ['REMOTE_USER_TOKENS'], ()) self.assertEqual(environ['REMOTE_USER_DATA'], 'userid_type:b64unicode') self.assertEqual(environ['AUTH_TYPE'], 'cookie') def test_identify_bad_cookie(self): helper = self._makeOne('secret', include_ip=True) helper.auth_tkt.parse_raise = True request = self._makeRequest('ticket') result = helper.identify(request) self.assertEqual(result, None) def test_identify_cookie_timeout(self): helper = self._makeOne('secret', timeout=1) self.assertEqual(helper.timeout, 1) def test_identify_cookie_str_timeout(self): helper = self._makeOne('secret', timeout='1') self.assertEqual(helper.timeout, 1) def test_identify_cookie_timeout_aged(self): import time helper = self._makeOne('secret', timeout=10) now = time.time() helper.auth_tkt.timestamp = now - 1 helper.now = now + 10 helper.auth_tkt.tokens = (text_('a'),) request = self._makeRequest('bogus') result = helper.identify(request) self.assertFalse(result) def test_identify_cookie_reissue(self): import time helper = self._makeOne('secret', timeout=10, reissue_time=0) now = time.time() helper.auth_tkt.timestamp = now helper.now = now + 1 helper.auth_tkt.tokens = (text_('a'),) request = self._makeRequest('bogus') result = helper.identify(request) self.assertTrue(result) self.assertEqual(len(request.callbacks), 1) response = DummyResponse() request.callbacks[0](request, response) self.assertEqual(len(response.headerlist), 1) self.assertEqual(response.headerlist[0][0], 'Set-Cookie') def test_identify_cookie_str_reissue(self): import time helper = self._makeOne('secret', timeout=10, reissue_time='0') now = time.time() helper.auth_tkt.timestamp = now helper.now = now + 1 helper.auth_tkt.tokens = (text_('a'),) request = self._makeRequest('bogus') result = helper.identify(request) self.assertTrue(result) self.assertEqual(len(request.callbacks), 1) response = DummyResponse() request.callbacks[0](request, response) self.assertEqual(len(response.headerlist), 1) self.assertEqual(response.headerlist[0][0], 'Set-Cookie') def test_identify_cookie_reissue_already_reissued_this_request(self): import time helper = self._makeOne('secret', timeout=10, reissue_time=0) now = time.time() helper.auth_tkt.timestamp = now helper.now = now + 1 request = self._makeRequest('bogus') request._authtkt_reissued = True result = helper.identify(request) self.assertTrue(result) self.assertEqual(len(request.callbacks), 0) def test_identify_cookie_reissue_notyet(self): import time helper = self._makeOne('secret', timeout=10, reissue_time=10) now = time.time() helper.auth_tkt.timestamp = now helper.now = now + 1 request = self._makeRequest('bogus') result = helper.identify(request) self.assertTrue(result) self.assertEqual(len(request.callbacks), 0) def test_identify_cookie_reissue_revoked_by_forget(self): import time helper = self._makeOne('secret', timeout=10, reissue_time=0) now = time.time() helper.auth_tkt.timestamp = now helper.now = now + 1 request = self._makeRequest('bogus') result = helper.identify(request) self.assertTrue(result) self.assertEqual(len(request.callbacks), 1) result = helper.forget(request) self.assertTrue(result) self.assertEqual(len(request.callbacks), 1) response = DummyResponse() request.callbacks[0](request, response) self.assertEqual(len(response.headerlist), 0) def test_identify_cookie_reissue_revoked_by_remember(self): import time helper = self._makeOne('secret', timeout=10, reissue_time=0) now = time.time() helper.auth_tkt.timestamp = now helper.now = now + 1 request = self._makeRequest('bogus') result = helper.identify(request) self.assertTrue(result) self.assertEqual(len(request.callbacks), 1) result = helper.remember(request, 'bob') self.assertTrue(result) self.assertEqual(len(request.callbacks), 1) response = DummyResponse() request.callbacks[0](request, response) self.assertEqual(len(response.headerlist), 0) def test_identify_cookie_reissue_with_tokens_default(self): # see https://github.com/Pylons/pyramid/issues#issue/108 import time helper = self._makeOne('secret', timeout=10, reissue_time=0) auth_tkt = DummyAuthTktModule(tokens=['']) helper.auth_tkt = auth_tkt helper.AuthTicket = auth_tkt.AuthTicket helper.parse_ticket = auth_tkt.parse_ticket helper.BadTicket = auth_tkt.BadTicket now = time.time() helper.auth_tkt.timestamp = now helper.now = now + 1 request = self._makeRequest('bogus') result = helper.identify(request) self.assertTrue(result) self.assertEqual(len(request.callbacks), 1) response = DummyResponse() request.callbacks[0](None, response) self.assertEqual(len(response.headerlist), 1) self.assertEqual(response.headerlist[0][0], 'Set-Cookie') self.assertTrue("/tokens=/" in response.headerlist[0][1]) def test_remember(self): helper = self._makeOne('secret') request = self._makeRequest() result = helper.remember(request, 'userid') self.assertEqual(len(result), 1) name, value = result[0] self.assertEqual(name, 'Set-Cookie') self.assertTrue( value.endswith('; Domain=localhost; Path=/; SameSite=Lax') ) self.assertTrue(value.startswith('auth_tkt=')) def test_remember_nondefault_samesite(self): helper = self._makeOne('secret', samesite='Strict') request = self._makeRequest() result = helper.remember(request, 'userid') self.assertEqual(len(result), 1) name, value = result[0] self.assertEqual(name, 'Set-Cookie') self.assertTrue( value.endswith('; Domain=localhost; Path=/; SameSite=Strict') ) self.assertTrue(value.startswith('auth_tkt=')) def test_remember_None_samesite(self): helper = self._makeOne('secret', samesite=None) request = self._makeRequest() result = helper.remember(request, 'userid') self.assertEqual(len(result), 1) name, value = result[0] self.assertEqual(name, 'Set-Cookie') self.assertTrue('SameSite=' not in value) self.assertTrue(value.endswith('; Domain=localhost; Path=/')) self.assertTrue(value.startswith('auth_tkt=')) def test_remember_include_ip(self): helper = self._makeOne('secret', include_ip=True) request = self._makeRequest() result = helper.remember(request, 'other') self.assertEqual(len(result), 1) name, value = result[0] self.assertEqual(name, 'Set-Cookie') self.assertTrue( value.endswith('; Domain=localhost; Path=/; SameSite=Lax') ) self.assertTrue(value.startswith('auth_tkt=')) def test_remember_path(self): helper = self._makeOne( 'secret', include_ip=True, path="/cgi-bin/app.cgi/" ) request = self._makeRequest() result = helper.remember(request, 'other') self.assertEqual(len(result), 1) name, value = result[0] self.assertEqual(name, 'Set-Cookie') self.assertTrue( value.endswith( '; Domain=localhost; Path=/cgi-bin/app.cgi/; SameSite=Lax' ) ) self.assertTrue(value.startswith('auth_tkt=')) def test_remember_http_only(self): helper = self._makeOne('secret', include_ip=True, http_only=True) request = self._makeRequest() result = helper.remember(request, 'other') self.assertEqual(len(result), 1) name, value = result[0] self.assertEqual(name, 'Set-Cookie') self.assertTrue(value.endswith('; HttpOnly; SameSite=Lax')) self.assertTrue(value.startswith('auth_tkt=')) def test_remember_secure(self): helper = self._makeOne('secret', include_ip=True, secure=True) request = self._makeRequest() result = helper.remember(request, 'other') self.assertEqual(len(result), 1) name, value = result[0] self.assertEqual(name, 'Set-Cookie') self.assertTrue('; secure' in value) self.assertTrue(value.startswith('auth_tkt=')) def test_remember_wild_domain_disabled(self): helper = self._makeOne('secret', wild_domain=False) request = self._makeRequest() result = helper.remember(request, 'other') self.assertEqual(len(result), 1) name, value = result[0] self.assertEqual(name, 'Set-Cookie') self.assertTrue('Domain=' not in value) self.assertTrue(value.endswith('; Path=/; SameSite=Lax')) self.assertTrue(value.startswith('auth_tkt=')) def test_remember_parent_domain(self): helper = self._makeOne('secret', parent_domain=True) request = self._makeRequest() request.domain = 'www.example.com' result = helper.remember(request, 'other') self.assertEqual(len(result), 1) name, value = result[0] self.assertEqual(name, 'Set-Cookie') self.assertTrue( value.endswith('; Domain=example.com; Path=/; SameSite=Lax') ) self.assertTrue(value.startswith('auth_tkt=')) def test_remember_parent_domain_supercedes_wild_domain(self): helper = self._makeOne('secret', parent_domain=True, wild_domain=True) request = self._makeRequest() request.domain = 'www.example.com' result = helper.remember(request, 'other') self.assertEqual(len(result), 1) name, value = result[0] self.assertEqual(name, 'Set-Cookie') self.assertTrue( value.endswith('; Domain=example.com; Path=/; SameSite=Lax') ) def test_remember_explicit_domain(self): helper = self._makeOne('secret', domain='pyramid.bazinga') request = self._makeRequest() request.domain = 'www.example.com' result = helper.remember(request, 'other') self.assertEqual(len(result), 1) self.assertEqual(result[0][0], 'Set-Cookie') self.assertTrue( result[0][1].endswith( '; Domain=pyramid.bazinga; Path=/; SameSite=Lax' ) ) self.assertTrue(result[0][1].startswith('auth_tkt=')) def test_remember_domain_supercedes_parent_and_wild_domain(self): helper = self._makeOne( 'secret', domain='pyramid.bazinga', parent_domain=True, wild_domain=True, ) request = self._makeRequest() request.domain = 'www.example.com' result = helper.remember(request, 'other') self.assertEqual(len(result), 1) self.assertTrue( result[0][1].endswith( '; Domain=pyramid.bazinga; Path=/; SameSite=Lax' ) ) def test_remember_binary_userid(self): import base64 helper = self._makeOne('secret') request = self._makeRequest() result = helper.remember(request, b'userid') values = self._parseHeaders(result) self.assertEqual(len(result), 1) val = self._cookieValue(values[0]) self.assertEqual( val['userid'], text_(base64.b64encode(b'userid').strip()) ) self.assertEqual(val['user_data'], 'userid_type:b64str') def test_remember_int_userid(self): helper = self._makeOne('secret') request = self._makeRequest() result = helper.remember(request, 1) values = self._parseHeaders(result) self.assertEqual(len(result), 1) val = self._cookieValue(values[0]) self.assertEqual(val['userid'], '1') self.assertEqual(val['user_data'], 'userid_type:int') def test_remember_unicode_userid(self): import base64 helper = self._makeOne('secret') request = self._makeRequest() userid = text_(b'\xc2\xa9', 'utf-8') result = helper.remember(request, userid) values = self._parseHeaders(result) self.assertEqual(len(result), 1) val = self._cookieValue(values[0]) self.assertEqual( val['userid'], text_(base64.b64encode(userid.encode('utf-8'))) ) self.assertEqual(val['user_data'], 'userid_type:b64unicode') def test_remember_insane_userid(self): helper = self._makeOne('secret') request = self._makeRequest() userid = object() with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always', RuntimeWarning) result = helper.remember(request, userid) self.assertTrue(str(w[-1].message).startswith('userid is of type')) values = self._parseHeaders(result) self.assertEqual(len(result), 1) value = values[0] self.assertTrue('userid' in value.value) def test_remember_max_age(self): helper = self._makeOne('secret') request = self._makeRequest() result = helper.remember(request, 'userid', max_age=500) values = self._parseHeaders(result) self.assertEqual(len(result), 1) self.assertEqual(values[0]['max-age'], '500') self.assertTrue(values[0]['expires']) def test_remember_str_max_age(self): helper = self._makeOne('secret') request = self._makeRequest() result = helper.remember(request, 'userid', max_age='500') values = self._parseHeaders(result) self.assertEqual(len(result), 1) self.assertEqual(values[0]['max-age'], '500') self.assertTrue(values[0]['expires']) def test_remember_str_max_age_invalid(self): helper = self._makeOne('secret') request = self._makeRequest() self.assertRaises( ValueError, helper.remember, request, 'userid', max_age='invalid value', ) def test_remember_tokens(self): helper = self._makeOne('secret') request = self._makeRequest() result = helper.remember(request, 'other', tokens=('foo', 'bar')) self.assertEqual(len(result), 1) name, value = result[0] self.assertEqual(name, 'Set-Cookie') self.assertTrue("/tokens=foo|bar/" in value) def test_remember_samesite_nondefault(self): helper = self._makeOne('secret', samesite='Strict') request = self._makeRequest() result = helper.remember(request, 'userid') self.assertEqual(len(result), 1) name, value = result[0] self.assertEqual(name, 'Set-Cookie') self.assertTrue( 'SameSite=Strict' in [x.strip() for x in value.split(';')], value, ) def test_remember_samesite_default(self): helper = self._makeOne('secret') request = self._makeRequest() result = helper.remember(request, 'userid') self.assertEqual(len(result), 1) name, value = result[0] self.assertEqual(name, 'Set-Cookie') self.assertTrue( 'SameSite=Lax' in [x.strip() for x in value.split(';')], value, ) def test_remember_unicode_but_ascii_token(self): helper = self._makeOne('secret') request = self._makeRequest() la = text_(b'foo', 'utf-8') result = helper.remember(request, 'other', tokens=(la,)) # tokens must be str type on both Python 2 and 3 self.assertTrue("/tokens=foo/" in result[0][1]) def test_remember_nonascii_token(self): helper = self._makeOne('secret') request = self._makeRequest() la = text_(b'La Pe\xc3\xb1a', 'utf-8') self.assertRaises( ValueError, helper.remember, request, 'other', tokens=(la,) ) def test_remember_invalid_token_format(self): helper = self._makeOne('secret') request = self._makeRequest() self.assertRaises( ValueError, helper.remember, request, 'other', tokens=('foo bar',) ) self.assertRaises( ValueError, helper.remember, request, 'other', tokens=('1bar',) ) def test_forget(self): helper = self._makeOne('secret') request = self._makeRequest() headers = helper.forget(request) self.assertEqual(len(headers), 1) name, value = headers[0] self.assertEqual(name, 'Set-Cookie') self.assertEqual( value, 'auth_tkt=; Domain=localhost; Max-Age=0; Path=/; ' 'expires=Wed, 31-Dec-97 23:59:59 GMT; SameSite=Lax', )
TestAuthTktCookieHelper
python
getsentry__sentry
tests/sentry/new_migrations/monkey/test_monkey.py
{ "start": 355, "end": 622 }
class ____(TestCase): def test(self) -> None: assert executor.MigrationExecutor is SentryMigrationExecutor assert writer.MIGRATION_TEMPLATE == SENTRY_MIGRATION_TEMPLATE assert Field.deconstruct == deconstruct != original_deconstruct
MonkeyTest
python
ray-project__ray
rllib/algorithms/marwil/marwil_learner.py
{ "start": 557, "end": 1806 }
class ____(Learner): @override(Learner) def build(self) -> None: super().build() # Dict mapping module IDs to the respective moving averages of squared # advantages. self.moving_avg_sqd_adv_norms_per_module: Dict[ ModuleID, TensorType ] = LambdaDefaultDict( lambda module_id: self._get_tensor_variable( self.config.get_config_for_module( module_id ).moving_average_sqd_adv_norm_start ) ) @override(Learner) def remove_module( self, module_id: ModuleID, *, new_should_module_be_updated: Optional[ShouldModuleBeUpdatedFn] = None, ) -> None: super().remove_module( module_id, new_should_module_be_updated=new_should_module_be_updated, ) # In case of BC (beta==0.0 and this property never being used), self.moving_avg_sqd_adv_norms_per_module.pop(module_id, None) @classmethod @override(Learner) def rl_module_required_apis(cls) -> list[type]: # In order for a PPOLearner to update an RLModule, it must implement the # following APIs: return [ValueFunctionAPI]
MARWILLearner
python
pytorch__pytorch
torch/_inductor/codegen/simd_kernel_features.py
{ "start": 1345, "end": 2023 }
class ____(NodeScheduleMarker): """ Marker to end a DisableReduction block. """ @staticmethod def filter(node_schedule: list[NodeScheduleEntry]) -> Iterable[SchedulerNode]: """ Get the nodes from node_schedule skipping those in a DisableReduction block. """ disabled = False for node in node_schedule: if node in (EnableReduction, DisableReduction): # Don't tile stuff outside the main reduction loop disabled = node is DisableReduction elif disabled: pass else: yield node # type: ignore[misc]
EnableReduction
python
Textualize__textual
src/textual/css/stylesheet.py
{ "start": 4048, "end": 4614 }
class ____(NamedTuple): """Contains the CSS content and whether or not the CSS comes from user defined stylesheets vs widget-level stylesheets. Args: content: The CSS as a string. is_defaults: True if the CSS is default (i.e. that defined at the widget level). False if it's user CSS (which will override the defaults). tie_breaker: Specificity tie breaker. scope: Scope of CSS. """ content: str is_defaults: bool tie_breaker: int = 0 scope: str = "" @rich.repr.auto(angular=True)
CssSource
python
ApeWorX__ape
tests/functional/test_coverage.py
{ "start": 3810, "end": 4329 }
class ____: def test_function_rate(self, coverage_project): assert coverage_project.function_rate == 0.5 def test_lines_coverage(self, coverage_project): # Doubles because has 2 contracts in it now (with same amounts of things) assert coverage_project.lines_covered == 8 def test_miss_count(self, coverage_project): assert coverage_project.miss_count == 4 def test_line_rate(self, coverage_project): assert coverage_project.line_rate == 2 / 3
TestCoverageProject
python
pydantic__pydantic
.github/actions/people/people.py
{ "start": 6844, "end": 6966 }
class ____(BaseModel): """Complete response structure for pull requests query.""" data: PRsResponseData
PRsResponse
python
pytest-dev__pytest
src/_pytest/python.py
{ "start": 21051, "end": 24389 }
class ____(nodes.File, PyCollector): """Collector for test classes and functions in a Python module.""" def _getobj(self): return importtestmodule(self.path, self.config) def collect(self) -> Iterable[nodes.Item | nodes.Collector]: self._register_setup_module_fixture() self._register_setup_function_fixture() self.session._fixturemanager.parsefactories(self) return super().collect() def _register_setup_module_fixture(self) -> None: """Register an autouse, module-scoped fixture for the collected module object that invokes setUpModule/tearDownModule if either or both are available. Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with other fixtures (#517). """ setup_module = _get_first_non_fixture_func( self.obj, ("setUpModule", "setup_module") ) teardown_module = _get_first_non_fixture_func( self.obj, ("tearDownModule", "teardown_module") ) if setup_module is None and teardown_module is None: return def xunit_setup_module_fixture(request) -> Generator[None]: module = request.module if setup_module is not None: _call_with_optional_argument(setup_module, module) yield if teardown_module is not None: _call_with_optional_argument(teardown_module, module) self.session._fixturemanager._register_fixture( # Use a unique name to speed up lookup. name=f"_xunit_setup_module_fixture_{self.obj.__name__}", func=xunit_setup_module_fixture, nodeid=self.nodeid, scope="module", autouse=True, ) def _register_setup_function_fixture(self) -> None: """Register an autouse, function-scoped fixture for the collected module object that invokes setup_function/teardown_function if either or both are available. Using a fixture to invoke this methods ensures we play nicely and unsurprisingly with other fixtures (#517). """ setup_function = _get_first_non_fixture_func(self.obj, ("setup_function",)) teardown_function = _get_first_non_fixture_func( self.obj, ("teardown_function",) ) if setup_function is None and teardown_function is None: return def xunit_setup_function_fixture(request) -> Generator[None]: if request.instance is not None: # in this case we are bound to an instance, so we need to let # setup_method handle this yield return function = request.function if setup_function is not None: _call_with_optional_argument(setup_function, function) yield if teardown_function is not None: _call_with_optional_argument(teardown_function, function) self.session._fixturemanager._register_fixture( # Use a unique name to speed up lookup. name=f"_xunit_setup_function_fixture_{self.obj.__name__}", func=xunit_setup_function_fixture, nodeid=self.nodeid, scope="function", autouse=True, )
Module
python
pydantic__pydantic
tests/benchmarks/basemodel_eq_performance.py
{ "start": 3918, "end": 5999 }
class ____(pydantic.BaseModel, frozen=True): def __eq__(self, other: Any) -> bool: if isinstance(other, pydantic.BaseModel): # When comparing instances of generic types for equality, as long as all field values are equal, # only require their generic origin types to be equal, rather than exact type equality. # This prevents headaches like MyGeneric(x=1) != MyGeneric[Any](x=1). self_type = self.__pydantic_generic_metadata__['origin'] or self.__class__ other_type = other.__pydantic_generic_metadata__['origin'] or other.__class__ # Perform common checks first if not ( self_type == other_type and self.__pydantic_private__ == other.__pydantic_private__ and self.__pydantic_extra__ == other.__pydantic_extra__ ): return False # Fix GH-7444 by comparing only pydantic fields # We provide a fast-path for performance: __dict__ comparison is *much* faster # See tests/benchmarks/test_basemodel_eq_performances.py and GH-7825 for benchmarks if self.__dict__ == other.__dict__: # If the check above passes, then pydantic fields are equal, we can return early return True else: # Else, we need to perform a more detailed, costlier comparison model_fields = type(self).model_fields.keys() getter = operator.itemgetter(*model_fields) if model_fields else lambda _: None return getter(self.__dict__) == getter(other.__dict__) else: return NotImplemented # delegate to the other item in the comparison K = TypeVar('K') V = TypeVar('V') # We need a sentinel value for missing fields when comparing models # Models are equals if-and-only-if they miss the same fields, and since None is a legitimate value # we can't default to None # We use the single-value enum trick to allow correct typing when using a sentinel
ItemGetterEqModelFastPath
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 141585, "end": 143337 }
class ____(BaseModel, extra="forbid"): """ Operation for updating parameters of the existing collection """ vectors: Optional["VectorsConfigDiff"] = Field( default=None, description="Map of vector data parameters to update for each named vector. To update parameters in a collection having a single unnamed vector, use an empty string as name.", ) optimizers_config: Optional["OptimizersConfigDiff"] = Field( default=None, description="Custom params for Optimizers. If none - it is left unchanged. This operation is blocking, it will only proceed once all current optimizations are complete", ) params: Optional["CollectionParamsDiff"] = Field( default=None, description="Collection base params. If none - it is left unchanged." ) hnsw_config: Optional["HnswConfigDiff"] = Field( default=None, description="HNSW parameters to update for the collection index. If none - it is left unchanged." ) quantization_config: Optional["QuantizationConfigDiff"] = Field( default=None, description="Quantization parameters to update. If none - it is left unchanged." ) sparse_vectors: Optional["SparseVectorsConfig"] = Field( default=None, description="Map of sparse vector data parameters to update for each sparse vector." ) strict_mode_config: Optional["StrictModeConfig"] = Field( default=None, description="Operation for updating parameters of the existing collection" ) metadata: Optional["Payload"] = Field( default=None, description="Metadata to update for the collection. If provided, this will merge with existing metadata. To remove metadata, set it to an empty object.", )
UpdateCollection
python
huggingface__transformers
src/transformers/cache_utils.py
{ "start": 21237, "end": 24830 }
class ____(DynamicLayer): """ A quantized layer similar to what is described in the [KIVI: A Tuning-Free Asymmetric 2bit Quantization for KV Cache paper](https://huggingface.co/papers/2402.02750). It allows the model to generate longer sequence length without allocating too much memory for the key and value caches by applying quantization. The cache has two types of storage, one for original precision and one for the quantized cache. A `residual length` is set as a maximum capacity for the original precision cache. When the length goes beyond maximum capacity, the original precision cache is discarded and moved into the quantized cache. The quantization is done per-channel with a set `q_group_size` for both Keys and Values, in contrast to what was described in the paper. """ def __init__( self, nbits: int = 4, axis_key: int = 0, axis_value: int = 0, q_group_size: int = 64, residual_length: int = 128, ): super().__init__() self.nbits = nbits self.axis_key = axis_key self.axis_value = axis_value self.q_group_size = q_group_size self.residual_length = residual_length self.cumulative_length = 0 def update( self, key_states: torch.Tensor, value_states: torch.Tensor, cache_kwargs: Optional[dict[str, Any]] = None, ) -> tuple[torch.Tensor, torch.Tensor]: """ Update the key and value caches in-place, and return the necessary keys and value states. Args: key_states (`torch.Tensor`): The new key states to cache. value_states (`torch.Tensor`): The new value states to cache. cache_kwargs (`dict[str, Any]`, *optional*): Additional arguments for the cache. Returns: tuple[`torch.Tensor`, `torch.Tensor`]: The key and value states. """ self.cumulative_length += key_states.shape[-2] # Lazy initialization if not self.is_initialized: self.lazy_initialization(key_states) self._quantized_keys = self._quantize(key_states.contiguous(), axis=self.axis_key) self._quantized_values = self._quantize(value_states.contiguous(), axis=self.axis_value) return key_states, value_states dequant_keys = self._dequantize(self._quantized_keys) dequant_values = self._dequantize(self._quantized_values) keys_to_return = torch.cat([dequant_keys, self.keys, key_states], dim=-2) values_to_return = torch.cat([dequant_values, self.values, value_states], dim=-2) if self.keys.dim() == 4 and self.keys.shape[-2] + 1 >= self.residual_length: self._quantized_keys = self._quantize(keys_to_return.contiguous(), axis=self.axis_key) self._quantized_values = self._quantize(values_to_return.contiguous(), axis=self.axis_value) self.keys = torch.tensor([], dtype=key_states.dtype, device=key_states.device) self.values = torch.tensor([], dtype=key_states.dtype, device=key_states.device) else: self.keys = torch.cat([self.keys, key_states], dim=-2) self.values = torch.cat([self.values, value_states], dim=-2) return keys_to_return, values_to_return @abstractmethod def _quantize(self, tensor, axis): ... @abstractmethod def _dequantize(self, q_tensor): ... def get_seq_length(self) -> int: """Returns the sequence length of the cached states.""" return self.cumulative_length
QuantizedLayer
python
TheAlgorithms__Python
data_structures/binary_tree/diameter_of_binary_tree.py
{ "start": 198, "end": 1645 }
class ____: data: int left: Node | None = None right: Node | None = None def depth(self) -> int: """ >>> root = Node(1) >>> root.depth() 1 >>> root.left = Node(2) >>> root.depth() 2 >>> root.left.depth() 1 >>> root.right = Node(3) >>> root.depth() 2 """ left_depth = self.left.depth() if self.left else 0 right_depth = self.right.depth() if self.right else 0 return max(left_depth, right_depth) + 1 def diameter(self) -> int: """ >>> root = Node(1) >>> root.diameter() 1 >>> root.left = Node(2) >>> root.diameter() 2 >>> root.left.diameter() 1 >>> root.right = Node(3) >>> root.diameter() 3 """ left_depth = self.left.depth() if self.left else 0 right_depth = self.right.depth() if self.right else 0 return left_depth + right_depth + 1 if __name__ == "__main__": from doctest import testmod testmod() root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) r""" Constructed binary tree is 1 / \ 2 3 / \ 4 5 """ print(f"{root.diameter() = }") # 4 print(f"{root.left.diameter() = }") # 3 print(f"{root.right.diameter() = }") # 1
Node
python
ipython__ipython
IPython/core/profiledir.py
{ "start": 654, "end": 899 }
class ____(Exception): pass #----------------------------------------------------------------------------- # Class for managing profile directories #-----------------------------------------------------------------------------
ProfileDirError
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 53049, "end": 54470 }
class ____(ExprNode): """Base class for nodes that inherit the result of their temp argument and can modify it. """ subexprs = ['arg'] is_temp = False def __init__(self, pos, arg): super().__init__(pos, arg=arg) @property def type(self): return self.arg.type def infer_type(self, env): return self.arg.infer_type(env) def analyse_types(self, env): self.arg = self.arg.analyse_types(env) return self def calculate_constant_result(self): return self.arg.calculate_constant_result() def may_be_none(self): return self.arg.may_be_none() def is_simple(self): return self.arg.is_simple() def result_in_temp(self): return self.arg.result_in_temp() def nonlocally_immutable(self): return self.arg.nonlocally_immutable() def calculate_result_code(self): return self.arg.result() def generate_result_code(self, code): pass def generate_post_assignment_code(self, code): self.arg.generate_post_assignment_code(code) def allocate_temp_result(self, code): return self.arg.allocate_temp_result(code) def free_temps(self, code): self.arg.free_temps(code) #------------------------------------------------------------------- # # Constants # #-------------------------------------------------------------------
_TempModifierNode
python
celery__celery
celery/exceptions.py
{ "start": 4428, "end": 4504 }
class ____(Exception): """Base class for all Celery errors."""
CeleryError
python
apache__airflow
providers/sendgrid/tests/unit/sendgrid/utils/test_emailer.py
{ "start": 954, "end": 5099 }
class ____: # Unit test for sendgrid.send_email() def setup_method(self): self.recipients = ["foo@foo.com", "bar@bar.com"] self.subject = "sendgrid-send-email unit test" self.html_content = "<b>Foo</b> bar" self.carbon_copy = ["foo-cc@foo.com", "bar-cc@bar.com"] self.bcc = ["foo-bcc@foo.com", "bar-bcc@bar.com"] self.expected_mail_data = { "content": [{"type": "text/html", "value": self.html_content}], "personalizations": [ { "cc": [{"email": "foo-cc@foo.com"}, {"email": "bar-cc@bar.com"}], "to": [{"email": "foo@foo.com"}, {"email": "bar@bar.com"}], "bcc": [{"email": "foo-bcc@foo.com"}, {"email": "bar-bcc@bar.com"}], } ], "from": {"email": "foo@bar.com"}, "subject": "sendgrid-send-email unit test", } self.personalization_custom_args = {"arg1": "val1", "arg2": "val2"} self.categories = ["cat1", "cat2"] # extras self.expected_mail_data_extras = copy.deepcopy(self.expected_mail_data) self.expected_mail_data_extras["personalizations"][0]["custom_args"] = ( self.personalization_custom_args ) self.expected_mail_data_extras["categories"] = ["cat2", "cat1"] self.expected_mail_data_extras["from"] = { "name": "Foo", "email": "foo@bar.com", } # sender self.expected_mail_data_sender = copy.deepcopy(self.expected_mail_data) self.expected_mail_data_sender["from"] = { "name": "Foo Bar", "email": "foo@foo.bar", } # Test the right email is constructed. @mock.patch.dict("os.environ", SENDGRID_MAIL_FROM="foo@bar.com") @mock.patch("airflow.providers.sendgrid.utils.emailer._post_sendgrid_mail") def test_send_email_sendgrid_correct_email(self, mock_post): with tempfile.NamedTemporaryFile(mode="wt", suffix=".txt") as f: f.write("this is some test data") f.flush() filename = os.path.basename(f.name) expected_mail_data = dict( self.expected_mail_data, attachments=[ { "content": "dGhpcyBpcyBzb21lIHRlc3QgZGF0YQ==", "content_id": f"<{filename}>", "disposition": "attachment", "filename": filename, "type": "text/plain", } ], ) send_email( self.recipients, self.subject, self.html_content, cc=self.carbon_copy, bcc=self.bcc, files=[f.name], ) mock_post.assert_called_once_with(expected_mail_data, "sendgrid_default") # Test the right email is constructed. @mock.patch.dict("os.environ", SENDGRID_MAIL_FROM="foo@bar.com", SENDGRID_MAIL_SENDER="Foo") @mock.patch("airflow.providers.sendgrid.utils.emailer._post_sendgrid_mail") def test_send_email_sendgrid_correct_email_extras(self, mock_post): send_email( self.recipients, self.subject, self.html_content, cc=self.carbon_copy, bcc=self.bcc, personalization_custom_args=self.personalization_custom_args, categories=self.categories, ) mock_post.assert_called_once_with(self.expected_mail_data_extras, "sendgrid_default") @mock.patch.dict("os.environ", clear=True) @mock.patch("airflow.providers.sendgrid.utils.emailer._post_sendgrid_mail") def test_send_email_sendgrid_sender(self, mock_post): send_email( self.recipients, self.subject, self.html_content, cc=self.carbon_copy, bcc=self.bcc, from_email="foo@foo.bar", from_name="Foo Bar", ) mock_post.assert_called_once_with(self.expected_mail_data_sender, "sendgrid_default")
TestSendEmailSendGrid
python
allegroai__clearml
clearml/backend_api/services/v2_9/events.py
{ "start": 85459, "end": 88805 }
class ____(Response): """ Response of events.get_task_plots endpoint. :param plots: Plots list :type plots: Sequence[dict] :param returned: Number of results returned :type returned: int :param total: Total number of results available for this query :type total: float :param scroll_id: Scroll ID for getting more results :type scroll_id: str """ _service = "events" _action = "get_task_plots" _version = "2.9" _schema = { "definitions": {}, "properties": { "plots": { "description": "Plots list", "items": {"type": "object"}, "type": ["array", "null"], }, "returned": { "description": "Number of results returned", "type": ["integer", "null"], }, "scroll_id": { "description": "Scroll ID for getting more results", "type": ["string", "null"], }, "total": { "description": "Total number of results available for this query", "type": ["number", "null"], }, }, "type": "object", } def __init__( self, plots: Optional[List[dict]] = None, returned: Optional[int] = None, total: Optional[float] = None, scroll_id: Optional[str] = None, **kwargs: Any ) -> None: super(GetTaskPlotsResponse, self).__init__(**kwargs) self.plots = plots self.returned = returned self.total = total self.scroll_id = scroll_id @schema_property("plots") def plots(self) -> Optional[List[dict]]: return self._property_plots @plots.setter def plots(self, value: Optional[List[dict]]) -> None: if value is None: self._property_plots = None return self.assert_isinstance(value, "plots", (list, tuple)) self.assert_isinstance(value, "plots", (dict,), is_array=True) self._property_plots = value @schema_property("returned") def returned(self) -> Optional[int]: return self._property_returned @returned.setter def returned(self, value: Optional[int]) -> None: if value is None: self._property_returned = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "returned", six.integer_types) self._property_returned = value @schema_property("total") def total(self) -> Optional[float]: return self._property_total @total.setter def total(self, value: Optional[float]) -> None: if value is None: self._property_total = None return self.assert_isinstance(value, "total", six.integer_types + (float,)) self._property_total = value @schema_property("scroll_id") def scroll_id(self) -> Optional[str]: return self._property_scroll_id @scroll_id.setter def scroll_id(self, value: Optional[str]) -> None: if value is None: self._property_scroll_id = None return self.assert_isinstance(value, "scroll_id", six.string_types) self._property_scroll_id = value
GetTaskPlotsResponse
python
doocs__leetcode
lcci/17.08.Circus Tower/Solution.py
{ "start": 0, "end": 365 }
class ____: def __init__(self, n): self.n = n self.c = [0] * (n + 1) def update(self, x, delta): while x <= self.n: self.c[x] = max(self.c[x], delta) x += x & -x def query(self, x): s = 0 while x: s = max(s, self.c[x]) x -= x & -x return s
BinaryIndexedTree
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/data_structures/list_ops_test.py
{ "start": 2085, "end": 81809 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): def _testPushPop(self, max_num_elements): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[], max_num_elements=max_num_elements) l = list_ops.tensor_list_push_back(l, constant_op.constant(1.0)) l, e = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) l = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) l, e = self.evaluate((l, e)) self.assertAllEqual(l, []) self.assertAllEqual(e, 1.0) @parameterized.named_parameters(("NoMaxNumElements", None), ("WithMaxNumElements", 2)) def testPushPop(self, max_num_elements): self._testPushPop(max_num_elements) @parameterized.named_parameters(("NoMaxNumElements", None), ("WithMaxNumElements", 2)) @test_util.run_gpu_only def testPushPopGPU(self, max_num_elements): with context.device("gpu:0"): self._testPushPop(max_num_elements) @test_util.run_deprecated_v1 def testPushInFullListFails(self): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[], max_num_elements=1) l = list_ops.tensor_list_push_back(l, constant_op.constant(1.0)) with self.assertRaisesRegex(errors.InvalidArgumentError, "Tried to push item into a full list"): l = list_ops.tensor_list_push_back(l, 2.) self.evaluate(l) @parameterized.named_parameters(("NoMaxNumElements", None), ("WithMaxNumElements", 2)) @test_util.run_deprecated_v1 def testPopFromEmptyTensorListFails(self, max_num_elements): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[], max_num_elements=max_num_elements) with self.assertRaisesRegex(errors.InvalidArgumentError, "Trying to pop from an empty list"): l = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) self.evaluate(l) def testTensorListReserveWithNonScalarNumElements(self): # list_kernels.cc in tf/core/kernels raises InvalidArgumentError, and # tf_ops_n_z.cc in tf/compiler/mlir/tf/ir raises UnknownError. with self.assertRaises((errors.InvalidArgumentError, errors.UnknownError)): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[2, 3], num_elements=constant_op.constant([1, 1])) self.evaluate(l) def testPopUninitializedTensorUseListElementShape(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[2, 3], num_elements=3) _, e = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) l = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) l, e = self.evaluate((l, e)) self.assertAllEqual(e, np.zeros((2, 3))) self.assertAllEqual(l, np.zeros((3, 2, 3))) def testPopUninitializedTensorUseSpecifiedElementShape(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[None, 3], num_elements=3) _, e = gen_list_ops.tensor_list_pop_back( l, element_dtype=dtypes.float32, element_shape=[4, 3]) self.assertAllEqual(e, np.zeros((4, 3))) def testPopUninitializedTensorWithInvalidElementShapeFails(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=None, num_elements=3) with self.assertRaisesRegex( errors.InvalidArgumentError, "Trying to read an uninitialized tensor but " "element_shape is not fully defined"): _, e = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) self.evaluate(e) l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[None, 2], num_elements=3) with self.assertRaisesRegex( errors.InvalidArgumentError, r"Incompatible shapes during merge: \[1,3\] vs. \[\?,2\]"): _, e = gen_list_ops.tensor_list_pop_back( l, element_dtype=dtypes.float32, element_shape=[1, 3]) self.evaluate(e) def testPushGetGrad(self): with backprop.GradientTape() as tape: l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=None) c0 = constant_op.constant(5.0) c1 = constant_op.constant([10.0, 20.0]) tape.watch(c0) tape.watch(c1) l = list_ops.tensor_list_push_back(l, c0) l = list_ops.tensor_list_push_back(l, c1) t1 = list_ops.tensor_list_get_item(l, 1, element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t1), [10.0, 20.0]) # t1 == c1 so the gradient should be [0., [1., 1.]] # This tests that the gradient of push_back correctly converts DT_INVALID # tensors to zeros. The list returned by the gradient of GetItem will # have only have tensor at index 1 set and others set to DT_INVALID. dt0, dt1 = tape.gradient(t1, [c0, c1]) self.assertAllEqual(self.evaluate(dt1), [1.0, 1.0]) self.assertEqual(self.evaluate(dt0), 0.0) def _testStack(self, max_num_elements): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[], max_num_elements=max_num_elements) l = list_ops.tensor_list_push_back(l, constant_op.constant(1.0)) l = list_ops.tensor_list_push_back(l, constant_op.constant(2.0)) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) if not context.executing_eagerly(): self.assertAllEqual(t.shape.as_list(), [None]) self.assertAllEqual(self.evaluate(t), [1.0, 2.0]) @parameterized.named_parameters(("NoMaxNumElements", None), ("WithMaxNumElements", 2)) def testStack(self, max_num_elements): self._testStack(max_num_elements) @parameterized.named_parameters(("NoMaxNumElements", None), ("WithMaxNumElements", 2)) @test_util.run_gpu_only def testStackGPU(self, max_num_elements): with context.device("gpu:0"): self._testStack(max_num_elements) @parameterized.named_parameters(("NoMaxNumElements", None), ("WithMaxNumElements", 3)) @test_util.run_deprecated_v1 def testStackWithUnknownElementShape(self, max_num_elements): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=None, max_num_elements=max_num_elements) l = list_ops.tensor_list_push_back(l, constant_op.constant(1.0)) l = list_ops.tensor_list_push_back(l, constant_op.constant(2.0)) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t), [1.0, 2.0]) # Should raise an error when the element tensors do not all have the same # shape. with self.assertRaisesRegex(errors.InvalidArgumentError, "Incompatible ranks during merge: 0 vs. 1"): l = list_ops.tensor_list_push_back(l, constant_op.constant([3.0, 4.0])) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) self.evaluate(t) @parameterized.named_parameters(("NoMaxNumElements", None), ("WithMaxNumElements", 3)) @test_util.run_deprecated_v1 def testStackWithPartiallyDefinedElementShape(self, max_num_elements): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[None], max_num_elements=max_num_elements) l = list_ops.tensor_list_push_back(l, constant_op.constant([1.0])) l = list_ops.tensor_list_push_back(l, constant_op.constant([2.0])) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t), [[1.0], [2.0]]) # Should raise an error when the element tensors do not all have the same # shape. with self.assertRaisesRegex( errors.InvalidArgumentError, r"Incompatible shapes during merge: \[1\] vs. \[2\]"): l = list_ops.tensor_list_push_back(l, constant_op.constant([2.0, 3.0])) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) self.evaluate(t) @parameterized.named_parameters(("NoMaxNumElements", None), ("WithMaxNumElements", 2)) @test_util.run_deprecated_v1 def testStackEmptyList(self, max_num_elements): # Should be able to stack empty lists with fully defined element_shape. l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[1, 2], max_num_elements=max_num_elements) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t).shape, (0, 1, 2)) # Should not be able to stack empty lists with partially defined # element_shape. with self.assertRaisesRegex(errors.InvalidArgumentError, "non-fully-defined"): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[None, 2], max_num_elements=max_num_elements) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) self.evaluate(t) # Should not be able to stack empty lists with undefined element_shape. with self.assertRaisesRegex(errors.InvalidArgumentError, "non-fully-defined"): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=None, max_num_elements=max_num_elements) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) self.evaluate(t) def _testStackWithUninitializedTensors(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[], num_elements=3) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) self.assertAllEqual(t, [0., 0., 0.]) def testStackWithUninitializedTensors(self): self._testStackWithUninitializedTensors() @test_util.run_gpu_only def testStackWithUninitializedTensorsGpu(self): with context.device("gpu:0"): self._testStackWithUninitializedTensors() def _testStackWithUninitializedTensorsInferShape(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=None, num_elements=3) l = list_ops.tensor_list_set_item(l, 1, [1., 2.]) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) self.assertAllEqual(t, [[0., 0.], [1., 2.], [0., 0.]]) def testStackWithUninitializedTensorsInferShape(self): self._testStackWithUninitializedTensorsInferShape() @test_util.run_gpu_only def testStackWithUninitializedTensorsInferShapeGpu(self): with context.device("gpu:0"): self._testStackWithUninitializedTensorsInferShape() def testStackReservedListWithNoElementsAndPartialElementShapeFails(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=None, num_elements=3) with self.assertRaisesRegex( errors.InvalidArgumentError, "Tried to stack list which only contains " "uninitialized tensors and has a " "non-fully-defined element_shape: <unknown>"): t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) self.evaluate(t) def testStackUsingSpecifiedElementShape(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=None, num_elements=3) t = gen_list_ops.tensor_list_stack( l, element_dtype=dtypes.float32, element_shape=[]) if context.executing_eagerly(): self.assertEqual(t.shape.as_list(), [3]) else: self.assertEqual(t.shape.as_list(), [None]) self.assertAllEqual(self.evaluate(t), np.zeros((3,))) @parameterized.named_parameters(("NoMaxNumElements", None), ("WithMaxNumElements", 2)) def testGatherGrad(self, max_num_elements): with backprop.GradientTape() as tape: l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[], max_num_elements=max_num_elements) c0 = constant_op.constant(1.0) tape.watch(c0) l = list_ops.tensor_list_push_back(l, c0) l = list_ops.tensor_list_push_back(l, constant_op.constant(2.0)) t = list_ops.tensor_list_gather(l, [1, 0], element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t), [2.0, 1.0]) s = (t[0] + t[1]) * (t[0] + t[1]) dt = tape.gradient(s, c0) self.assertAllEqual(self.evaluate(dt), 6.0) @parameterized.named_parameters(("NoMaxNumElements", None), ("WithMaxNumElements", 3)) @test_util.run_deprecated_v1 def testGatherWithUnknownElementShape(self, max_num_elements): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=None, max_num_elements=max_num_elements) l = list_ops.tensor_list_push_back(l, constant_op.constant(1.0)) l = list_ops.tensor_list_push_back(l, constant_op.constant(2.0)) l = list_ops.tensor_list_push_back(l, constant_op.constant([3.0, 4.0])) t = list_ops.tensor_list_gather(l, [1, 0], element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t), [2.0, 1.0]) t = list_ops.tensor_list_gather(l, [2], element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t), [[3.0, 4.0]]) # Should raise an error when the requested tensors do not all have the same # shape. with self.assertRaisesRegex(errors.InvalidArgumentError, "Incompatible ranks during merge: 0 vs. 1"): t = list_ops.tensor_list_gather(l, [0, 2], element_dtype=dtypes.float32) self.evaluate(t) @parameterized.named_parameters(("NoMaxNumElements", None), ("WithMaxNumElements", 3)) @test_util.run_deprecated_v1 def testGatherWithPartiallyDefinedElementShape(self, max_num_elements): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[None], max_num_elements=max_num_elements) l = list_ops.tensor_list_push_back(l, constant_op.constant([1.0])) l = list_ops.tensor_list_push_back(l, constant_op.constant([2.0, 3.0])) l = list_ops.tensor_list_push_back(l, constant_op.constant([4.0, 5.0])) t = list_ops.tensor_list_gather(l, [0], element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t), [[1.0]]) t = list_ops.tensor_list_gather(l, [1, 2], element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t), [[2.0, 3.0], [4.0, 5.0]]) # Should raise an error when the requested tensors do not all have the same # shape. with self.assertRaisesRegex( errors.InvalidArgumentError, r"Incompatible shapes during merge: \[1\] vs. \[2\]"): t = list_ops.tensor_list_gather(l, [0, 2], element_dtype=dtypes.float32) self.evaluate(t) @parameterized.named_parameters(("NoMaxNumElements", None), ("WithMaxNumElements", 3)) @test_util.run_deprecated_v1 def testGatherEmptyList(self, max_num_elements): # Should be able to gather from empty lists with fully defined # element_shape. l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[1, 2], max_num_elements=max_num_elements) t = list_ops.tensor_list_gather(l, [], element_dtype=dtypes.float32) self.assertAllEqual((0, 1, 2), self.evaluate(t).shape) # Should not be able to gather from empty lists with partially defined # element_shape. with self.assertRaisesRegex(errors.InvalidArgumentError, "non-fully-defined"): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[None, 2], max_num_elements=max_num_elements) t = list_ops.tensor_list_gather(l, [], element_dtype=dtypes.float32) self.evaluate(t) # Should not be able to gather from empty lists with undefined # element_shape. with self.assertRaisesRegex(errors.InvalidArgumentError, "non-fully-defined"): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=None, max_num_elements=max_num_elements) t = list_ops.tensor_list_gather(l, [], element_dtype=dtypes.float32) self.evaluate(t) def testGatherGradWithNonContiguousIndices(self): with backprop.GradientTape(persistent=True) as tape: t = constant_op.constant([1.0, 2.0, 3.0]) l = list_ops.tensor_list_from_tensor(t, element_shape=[]) c = constant_op.constant(5.0) tape.watch(c) l = list_ops.tensor_list_set_item(l, 1, c) t = list_ops.tensor_list_gather(l, [1], element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t), [5.0]) s = t[0] * t[0] dt = tape.gradient(s, c) self.assertAllEqual(self.evaluate(dt), 10.0) dl = tape.gradient(t, l) dl_length = list_ops.tensor_list_length(dl) self.assertAllEqual(self.evaluate(dl_length), 3) def _testGatherWithUninitializedTensors(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[], num_elements=3) t = list_ops.tensor_list_gather(l, [0, 2], element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t), [0., 0.]) def testGatherWithUninitializedTensors(self): self._testGatherWithUninitializedTensors() @test_util.run_gpu_only def testGatherWithUninitializedTensorsGpu(self): with context.device("gpu:0"): self._testGatherWithUninitializedTensors() def _testGatherWithUninitializedTensorsInferShape(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=None, num_elements=3) l = list_ops.tensor_list_set_item(l, 1, [1., 2.]) t = list_ops.tensor_list_gather(l, [1, 2], element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t), [[1., 2.], [0., 0.]]) def testGatherWithUninitializedTensorsInferShape(self): self._testGatherWithUninitializedTensorsInferShape() @test_util.run_gpu_only def testGatherWithUninitializedTensorsInferShapeGpu(self): with context.device("gpu:0"): self._testGatherWithUninitializedTensorsInferShape() def testGatherReservedListWithNoElementsAndPartialElementShapeFails(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=None, num_elements=3) with self.assertRaisesRegex( errors.InvalidArgumentError, "Tried to gather uninitialized tensors from a" " list with non-fully-defined element_shape"): t = list_ops.tensor_list_gather(l, [0], element_dtype=dtypes.float32) self.evaluate(t) def testGatherUsingSpecifiedElementShape(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=None, num_elements=3) t = gen_list_ops.tensor_list_gather( l, [0, 1, 2], element_dtype=dtypes.float32, element_shape=[]) self.assertEqual(t.shape.as_list(), [3]) self.assertAllEqual(self.evaluate(t), np.zeros((3,))) def testGatherWithInvalidIndicesFails(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=None, num_elements=3 ) # Should raise an error when the input index is negative. with self.assertRaisesRegex( errors.InvalidArgumentError, "Trying to gather element -1 in a list with 3 elements.", ): t = list_ops.tensor_list_gather(l, [-1], element_dtype=dtypes.float32) self.evaluate(t) # Should raise an error when the input index is larger than the number of # elements in the list. with self.assertRaisesRegex( errors.InvalidArgumentError, "Trying to gather element 3 in a list with 3 elements.", ): t = list_ops.tensor_list_gather(l, [3], element_dtype=dtypes.float32) self.evaluate(t) def testScatterOutputListSize(self): c0 = constant_op.constant([1.0, 2.0]) l = list_ops.tensor_list_scatter(c0, [1, 3], []) # TensorListScatter should return a list with size largest index + 1. self.assertAllEqual(list_ops.tensor_list_length(l), 4) def testScatterOutputListSizeWithNumElementsSpecified(self): c0 = constant_op.constant([1.0, 2.0]) l = gen_list_ops.tensor_list_scatter_v2( c0, [1, 3], list_ops._build_element_shape([]), num_elements=5) # TensorListScatter should return a list with size num_elements. self.assertAllEqual(list_ops.tensor_list_length(l), 5) def testScatterFailsWhenElementShapeIsNotVector(self): c0 = constant_op.constant([1.0, 2.0]) # In Eager mode, InvalidArgumentError is generated by the Compute function. # In graph mode, ValueError is generated by the shape function. with self.assertRaisesRegex( (errors.InvalidArgumentError, ValueError), "must be at most rank 1"): l = gen_list_ops.tensor_list_scatter( # Wrong element_shape. Should be at most rank 1. c0, [1, 3], element_shape=[[1]]) self.evaluate(l) def testScatterV2FailsWhenElementShapeIsNotVector(self): c0 = constant_op.constant([1.0, 2.0]) # In Eager mode, InvalidArgumentError is generated by the Compute function. # In graph mode, ValueError is generated by the shape function. with self.assertRaisesRegex( (errors.InvalidArgumentError, ValueError), "must be at most rank 1"): l = gen_list_ops.tensor_list_scatter_v2( # Wrong element_shape. Should be at most rank 1. c0, [1, 3], element_shape=[[1]], num_elements=2) self.evaluate(l) def testScatterFailsWhenIndexLargerThanNumElements(self): c0 = constant_op.constant([1.0, 2.0]) with self.assertRaisesRegex( errors.InvalidArgumentError, "TensorListScatter: Trying to scatter at index 3 in list with size 3"): l = gen_list_ops.tensor_list_scatter_v2( c0, [1, 3], list_ops._build_element_shape([]), num_elements=3) self.evaluate(l) def testScatterFailsWithInvalidNumElements(self): c0 = constant_op.constant([1.0, 2.0]) with self.assertRaisesRegex( errors.InvalidArgumentError, "TensorListScatter expects num_elements >= -1, found: -2"): l = gen_list_ops.tensor_list_scatter_v2( c0, [1, 3], list_ops._build_element_shape([]), num_elements=-2) self.evaluate(l) def testScatterWithInvalidRowsInInputTensorFails(self): c0 = constant_op.constant([1.0, 2.0]) with self.assertRaisesRegex( errors.InvalidArgumentError, "Invalid number of rows in input tensor. Expected: 3 Actual: 2"): l = list_ops.tensor_list_scatter(c0, [1, 0, 2], []) self.evaluate(l) def testScatterWithNegativeIndicesFails(self): c0 = constant_op.constant([1.0, 2.0]) with self.assertRaisesRegex( errors.InvalidArgumentError, "Indices in TensorListScatter must all be non-negative."): l = list_ops.tensor_list_scatter(c0, [-1, -2], element_shape=[]) self.evaluate(l) @test_util.run_in_graph_and_eager_modes def testScatterWithNonScalarFails(self): c = constant_op.constant(value=[2]) num_elements = np.array([[], [], []], dtype=np.float32) with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), r"Shape must be rank 0 but is rank \d+|" r"\w+ must be a scalar"): self.evaluate( gen_list_ops.TensorListScatterV2( tensor=c, indices=c, element_shape=c, num_elements=num_elements)) def testScatterIntoExistingList(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[], num_elements=3) l = list_ops.tensor_list_scatter(tensor=[1.], indices=[0], element_shape=[]) l = list_ops.tensor_list_scatter( tensor=[2., 3.], indices=[1, 2], element_shape=[], input_handle=l) self.assertAllEqual( list_ops.tensor_list_stack(l, element_dtype=dtypes.float32), [1., 2., 3.]) def testScatterGrad(self): with backprop.GradientTape() as tape: c0 = constant_op.constant([1.0, 2.0]) tape.watch(c0) l = list_ops.tensor_list_scatter(c0, [1, 0], element_shape=[]) t0 = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32) t1 = list_ops.tensor_list_get_item(l, 1, element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t0), 2.0) self.assertAllEqual(self.evaluate(t1), 1.0) loss = t0 * t0 + t1 * t1 dt = tape.gradient(loss, c0) self.assertAllEqual(self.evaluate(dt), [2., 4.]) def testScatterWithPartialReadGrad(self): with backprop.GradientTape() as tape: c0 = constant_op.constant([1.0, 2.0]) tape.watch(c0) l = list_ops.tensor_list_scatter(c0, [1, 0], element_shape=[]) t0 = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t0), 2.0) loss = t0 * t0 dt = tape.gradient(loss, c0) self.assertAllEqual(self.evaluate(dt), [0., 4.]) def testTensorListFromTensor(self): t = constant_op.constant([1.0, 2.0]) l = list_ops.tensor_list_from_tensor(t, element_shape=[]) e = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32) self.assertAllEqual(e, 1.0) l, e = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) self.assertAllEqual(e, 2.0) l, e = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) self.assertAllEqual(e, 1.0) self.assertAllEqual(list_ops.tensor_list_length(l), 0) def testTensorListFromTensorFailsWhenElementShapeIsNotVector(self): t = constant_op.constant([1.0, 2.0]) # In Eager mode, InvalidArgumentError is generated by the Compute function. # In graph mode, ValueError is generated by the shape function. with self.assertRaisesRegex( (errors.InvalidArgumentError, ValueError), "must be at most rank 1"): # Wrong element_shape. Should be at most rank 1. l = list_ops.tensor_list_from_tensor(t, element_shape=[[1]]) self.evaluate(l) @test_util.run_gpu_only def testFromTensorGPU(self): with context.device("gpu:0"): self.testTensorListFromTensor() def testGetSetBool(self): t = constant_op.constant([True, False]) l = list_ops.tensor_list_from_tensor(t, element_shape=[]) e0 = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.bool) self.assertAllEqual(self.evaluate(e0), True) l = list_ops.tensor_list_set_item(l, 0, False) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.bool) self.assertAllEqual(self.evaluate(t), [False, False]) @test_util.run_gpu_only def testGetSetBoolGPU(self): with context.device("gpu:0"): self.testGetSetBool() def _testGetSetNumeric(self, dtype): t = constant_op.constant([1.0, 2.0], dtype=dtype) l = list_ops.tensor_list_from_tensor(t, element_shape=[]) e0 = list_ops.tensor_list_get_item(l, 0, element_dtype=dtype) self.assertAllEqual(self.evaluate(e0), 1.0) l = list_ops.tensor_list_set_item( l, 0, constant_op.constant(3.0, dtype=dtype)) t = list_ops.tensor_list_stack(l, element_dtype=dtype) self.assertAllEqual(self.evaluate(t), [3.0, 2.0]) @parameterized.parameters([dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128]) def testGetSetNumeric(self, dtype): self._testGetSetNumeric(dtype) @parameterized.parameters([dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128]) @test_util.run_gpu_only def testGetSetNumericGPU(self, dtype): with context.device("gpu:0"): self._testGetSetNumeric(dtype) def testGetSetReserved(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[], num_elements=2) e0 = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32) self.assertAllEqual(e0, 0.0) l = list_ops.tensor_list_set_item(l, 0, 3.0) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) self.assertAllEqual(t, [3.0, 0.0]) @test_util.run_gpu_only def testGetSetReservedGPU(self): with context.device("gpu:0"): self.testGetSetReserved() def testSetGetGrad(self): with backprop.GradientTape() as tape: t = constant_op.constant(5.) tape.watch(t) l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[], num_elements=3) l = list_ops.tensor_list_set_item(l, 1, 2. * t) e = list_ops.tensor_list_get_item(l, 1, element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(e), 10.0) self.assertAllEqual(self.evaluate(tape.gradient(e, t)), 2.0) def testGetUninitializedTensorUseListElementShape(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[], num_elements=3) l = list_ops.tensor_list_set_item(l, 0, 5.) e1 = list_ops.tensor_list_get_item(l, 1, element_dtype=dtypes.float32) e2 = list_ops.tensor_list_get_item(l, 2, element_dtype=dtypes.float32) self.assertEqual(self.evaluate(e1), 0.) self.assertEqual(self.evaluate(e2), 0.) def testGetUninitializedTensorUseSpecifiedElementShape(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=None, num_elements=3) e0 = gen_list_ops.tensor_list_get_item( l, 0, element_shape=[], element_dtype=dtypes.float32) e1 = gen_list_ops.tensor_list_get_item( l, 1, element_shape=constant_op.constant([2, 3], dtype=dtypes.int64), element_dtype=dtypes.float32, ) self.assertEqual(e0.shape.as_list(), []) self.assertEqual(e1.shape.as_list(), [2, 3]) self.assertEqual(self.evaluate(e0), 0.) self.assertAllEqual(self.evaluate(e1), np.zeros((2, 3))) l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[None, 3], num_elements=3) e1 = gen_list_ops.tensor_list_get_item( l, 1, element_shape=[2, 3], element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(e1), np.zeros((2, 3))) def testGetUninitializedTensorWithInvalidElementShapeFails(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=None, num_elements=3) with self.assertRaisesRegex( errors.InvalidArgumentError, "Trying to read an uninitialized tensor but " "element_shape is not fully defined"): e0 = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32) self.evaluate(e0) l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[None, 2], num_elements=3) # In eager mode the shape mismatch is caught in the TensorListGetItem # kernel which raises an InvalidArgumentError. # In graph mode the shape mismatch is caught in the C++ shape inference # which raises a ValueError. if context.executing_eagerly(): error_type = errors.InvalidArgumentError else: error_type = ValueError with self.assertRaisesRegex(error_type, r"shapes"): e0 = gen_list_ops.tensor_list_get_item( l, 0, element_dtype=dtypes.float32, element_shape=[1, 3]) self.evaluate(e0) @test_util.run_deprecated_v1 @test_util.enable_control_flow_v2 def testSkipEagerSetItemIndexOutOfBounds(self): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[]) e0 = constant_op.constant(5.) l = list_ops.tensor_list_set_item( l, 0, 2. * e0, resize_if_index_out_of_bounds=True) l = list_ops.tensor_list_set_item( l, 1, 1., resize_if_index_out_of_bounds=True) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) grad = gradients_impl.gradients(t, e0)[0] self.assertAllEqual(self.evaluate(grad), 2.) @test_util.run_deprecated_v1 def testSetOnEmptyListWithMaxNumElementsFails(self): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[], max_num_elements=3) with self.assertRaisesRegex( errors.InvalidArgumentError, "Trying to modify element 0 in a list with 0 elements."): l = list_ops.tensor_list_set_item(l, 0, 1.) self.evaluate(l) def testUnknownShape(self): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=None) l = list_ops.tensor_list_push_back(l, constant_op.constant(1.0)) l = list_ops.tensor_list_push_back(l, constant_op.constant([1.0, 2.0])) l, e = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(e), [1.0, 2.0]) l, e = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(e), 1.0) @test_util.run_gpu_only def testCPUGPUCopy(self): t = constant_op.constant([1.0, 2.0]) l = list_ops.tensor_list_from_tensor(t, element_shape=[]) with context.device("gpu:0"): l_gpu = array_ops.identity(l) self.assertAllEqual( self.evaluate( list_ops.tensor_list_pop_back( l_gpu, element_dtype=dtypes.float32)[1]), 2.0) l_cpu = array_ops.identity(l_gpu) self.assertAllEqual( self.evaluate( list_ops.tensor_list_pop_back( l_cpu, element_dtype=dtypes.float32)[1]), 2.0) @test_util.run_gpu_only def testCPUGPUCopyNested(self): t = constant_op.constant([1.0, 2.0]) child_l = list_ops.tensor_list_from_tensor(t, element_shape=[]) l = list_ops.empty_tensor_list( element_shape=constant_op.constant([], dtype=dtypes.int32), element_dtype=dtypes.variant) l = list_ops.tensor_list_push_back(l, child_l) with context.device("gpu:0"): l_gpu = array_ops.identity(l) _, child_l_gpu = list_ops.tensor_list_pop_back( l_gpu, element_dtype=dtypes.variant) self.assertAllEqual( self.evaluate( list_ops.tensor_list_pop_back( child_l_gpu, element_dtype=dtypes.float32)[1]), 2.0) l_cpu = array_ops.identity(l_gpu) _, child_l_cpu = list_ops.tensor_list_pop_back( l_cpu, element_dtype=dtypes.variant) self.assertAllEqual( self.evaluate( list_ops.tensor_list_pop_back( child_l_cpu, element_dtype=dtypes.float32)[1]), 2.0) def testGraphStack(self): with self.cached_session(): tl = list_ops.empty_tensor_list( element_shape=constant_op.constant([1], dtype=dtypes.int32), element_dtype=dtypes.int32) tl = list_ops.tensor_list_push_back(tl, [1]) self.assertAllEqual( self.evaluate( list_ops.tensor_list_stack(tl, element_dtype=dtypes.int32)), [[1]]) def testSkipEagerStackInLoop(self): with self.cached_session(): t1 = list_ops.empty_tensor_list( element_shape=constant_op.constant([], dtype=dtypes.int32), element_dtype=dtypes.int32) i = constant_op.constant(0, dtype=dtypes.int32) def body(i, t1): t1 = list_ops.tensor_list_push_back(t1, i) i += 1 return i, t1 i, t1 = while_loop.while_loop(lambda i, t1: math_ops.less(i, 4), body, [i, t1]) s1 = list_ops.tensor_list_stack(t1, element_dtype=dtypes.int32) self.assertAllEqual(self.evaluate(s1), [0, 1, 2, 3]) def testSkipEagerStackSwitchDtype(self): with self.cached_session(): list_ = list_ops.empty_tensor_list( element_shape=constant_op.constant([], dtype=dtypes.int32), element_dtype=dtypes.int32) m = constant_op.constant([1, 2, 3], dtype=dtypes.float32) def body(list_, m): list_ = cond.cond( math_ops.equal(list_ops.tensor_list_length(list_), 0), lambda: list_ops.empty_tensor_list(m.shape, m.dtype), lambda: list_) list_ = list_ops.tensor_list_push_back(list_, m) return list_, m for _ in range(2): list_, m = body(list_, m) s1 = list_ops.tensor_list_stack(list_, element_dtype=dtypes.float32) np_s1 = np.array([[1, 2, 3], [1, 2, 3]], dtype=np.float32) self.assertAllEqual(self.evaluate(s1), np_s1) def testSkipEagerStackInLoopSwitchDtype(self): with self.cached_session(): t1 = list_ops.empty_tensor_list( element_shape=constant_op.constant([], dtype=dtypes.int32), element_dtype=dtypes.int32) i = constant_op.constant(0, dtype=dtypes.float32) m = constant_op.constant([1, 2, 3], dtype=dtypes.float32) def body(i, m, t1): t1 = cond.cond( math_ops.equal(list_ops.tensor_list_length(t1), 0), lambda: list_ops.empty_tensor_list(m.shape, m.dtype), lambda: t1) t1 = list_ops.tensor_list_push_back(t1, m * i) i += 1.0 return i, m, t1 i, m, t1 = while_loop.while_loop(lambda i, m, t1: math_ops.less(i, 4), body, [i, m, t1]) s1 = list_ops.tensor_list_stack(t1, element_dtype=dtypes.float32) np_s1 = np.vstack([np.arange(1, 4) * i for i in range(4)]) self.assertAllEqual(self.evaluate(s1), np_s1) def testSerialize(self): worker = test_util.create_local_cluster(num_workers=1, num_ps=1)[0][0] with ops.Graph().as_default(), session.Session(target=worker.target): with ops.device("/job:worker"): t = constant_op.constant([[1.0], [2.0]]) l = list_ops.tensor_list_from_tensor(t, element_shape=[1]) with ops.device("/job:ps"): l_ps = array_ops.identity(l) l_ps, e = list_ops.tensor_list_pop_back( l_ps, element_dtype=dtypes.float32) with ops.device("/job:worker"): worker_e = array_ops.identity(e) self.assertAllEqual(self.evaluate(worker_e), [2.0]) def testSerializeListWithInvalidTensors(self): worker = test_util.create_local_cluster(num_workers=1, num_ps=1)[0][0] with ops.Graph().as_default(), session.Session(target=worker.target): with ops.device("/job:worker"): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[], num_elements=2) l = list_ops.tensor_list_set_item(l, 0, 1.) with ops.device("/job:ps"): l_ps = array_ops.identity(l) l_ps = list_ops.tensor_list_set_item(l_ps, 1, 2.) t = list_ops.tensor_list_stack(l_ps, element_dtype=dtypes.float32) with ops.device("/job:worker"): worker_t = array_ops.identity(t) self.assertAllEqual(self.evaluate(worker_t), [1.0, 2.0]) def testSerializeListWithUnknownRank(self): worker = test_util.create_local_cluster(num_workers=1, num_ps=1)[0][0] with ops.Graph().as_default(), session.Session(target=worker.target): with ops.device("/job:worker"): t = constant_op.constant([[1.0], [2.0]]) l = list_ops.tensor_list_from_tensor(t, element_shape=None) with ops.device("/job:ps"): l_ps = array_ops.identity(l) element_shape = list_ops.tensor_list_element_shape( l_ps, shape_type=dtypes.int32) with ops.device("/job:worker"): element_shape = array_ops.identity(element_shape) self.assertEqual(self.evaluate(element_shape), -1) def testSerializeListWithMaxNumElements(self): worker = test_util.create_local_cluster(num_workers=1, num_ps=1)[0][0] with ops.Graph().as_default(), session.Session(target=worker.target): with ops.device("/job:worker"): l = list_ops.empty_tensor_list( element_shape=None, element_dtype=dtypes.float32, max_num_elements=2) l = list_ops.tensor_list_push_back(l, 1.) with ops.device("/job:ps"): l_ps = array_ops.identity(l) l_ps = list_ops.tensor_list_push_back(l_ps, 2.) with self.assertRaisesRegex(errors.InvalidArgumentError, "Tried to push item into a full list"): with ops.device("/job:worker"): l_worker = array_ops.identity(l_ps) l_worker = list_ops.tensor_list_push_back(l_worker, 3.0) self.evaluate(l_worker) def testPushPopGradients(self): with backprop.GradientTape() as tape: l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[]) c = constant_op.constant(1.0) tape.watch(c) l = list_ops.tensor_list_push_back(l, c) l, e = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) e = 2 * e self.assertAllEqual(self.evaluate(tape.gradient(e, [c])[0]), 2.0) def testStackFromTensorGradients(self): with backprop.GradientTape() as tape: c = constant_op.constant([1.0, 2.0]) tape.watch(c) l = list_ops.tensor_list_from_tensor(c, element_shape=[]) c2 = list_ops.tensor_list_stack( l, element_dtype=dtypes.float32, num_elements=2) result = c2 * 2.0 grad = tape.gradient(result, [c])[0] self.assertAllEqual(self.evaluate(grad), [2.0, 2.0]) def testGetSetGradients(self): with backprop.GradientTape() as tape: c = constant_op.constant([1.0, 2.0]) tape.watch(c) l = list_ops.tensor_list_from_tensor(c, element_shape=[]) c2 = constant_op.constant(3.0) tape.watch(c2) l = list_ops.tensor_list_set_item(l, 0, c2) e = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32) ee = list_ops.tensor_list_get_item(l, 1, element_dtype=dtypes.float32) y = e * e + ee * ee grad_c, grad_c2 = tape.gradient(y, [c, c2]) self.assertAllEqual(self.evaluate(grad_c), [0.0, 4.0]) self.assertAllEqual(self.evaluate(grad_c2), 6.0) @test_util.run_deprecated_v1 def testSetOutOfBounds(self): c = constant_op.constant([1.0, 2.0]) l = list_ops.tensor_list_from_tensor(c, element_shape=[]) with self.assertRaises(errors.InvalidArgumentError): self.evaluate(list_ops.tensor_list_set_item(l, 20, 3.0)) @test_util.run_deprecated_v1 def testSkipEagerSetItemWithMismatchedShapeFails(self): with self.cached_session() as sess: ph = array_ops.placeholder(dtypes.float32) c = constant_op.constant([1.0, 2.0]) l = list_ops.tensor_list_from_tensor(c, element_shape=[]) # Set a placeholder with unknown shape to satisfy the shape inference # at graph building time. l = list_ops.tensor_list_set_item(l, 0, ph) l_0 = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32) with self.assertRaisesRegex(errors.InvalidArgumentError, "incompatible shape"): sess.run(l_0, {ph: [3.0]}) def testResourceVariableScatterGather(self): c = constant_op.constant([1.0, 2.0], dtype=dtypes.float32) l = list_ops.tensor_list_from_tensor(c, element_shape=[]) v = vs.get_variable("var", initializer=[l] * 10, use_resource=True) v_r_0_stacked = list_ops.tensor_list_stack(v[0], dtypes.float32) self.evaluate(v.initializer) self.assertAllEqual([1.0, 2.0], self.evaluate(v_r_0_stacked)) v_r_sparse_stacked = list_ops.tensor_list_stack( v.sparse_read(0), dtypes.float32) self.assertAllEqual([1.0, 2.0], self.evaluate(v_r_sparse_stacked)) l_new_0 = list_ops.tensor_list_from_tensor([3.0, 4.0], element_shape=[]) l_new_1 = list_ops.tensor_list_from_tensor([5.0, 6.0], element_shape=[]) updated_v = state_ops.scatter_update(v, [3, 5], [l_new_0, l_new_1]) updated_v_elems = array_ops_stack.unstack(updated_v) updated_v_stacked = [ list_ops.tensor_list_stack(el, dtypes.float32) for el in updated_v_elems ] expected = ([[1.0, 2.0]] * 3 + [[3.0, 4.0], [1.0, 2.0], [5.0, 6.0]] + [[1.0, 2.0]] * 4) self.assertAllEqual(self.evaluate(updated_v_stacked), expected) def testResourceVariableScatterGatherInt64(self): c = constant_op.constant([1, 2], dtype=dtypes.int64) l = list_ops.tensor_list_from_tensor(c, element_shape=[]) v = vs.get_variable("var", initializer=[l] * 10, use_resource=True) v_r_0_stacked = list_ops.tensor_list_stack(v[0], dtypes.int64) self.evaluate(v.initializer) self.assertAllEqual([1, 2], self.evaluate(v_r_0_stacked)) v_r_sparse_stacked = list_ops.tensor_list_stack( v.sparse_read(0), dtypes.int64) self.assertAllEqual([1, 2], self.evaluate(v_r_sparse_stacked)) c34 = constant_op.constant([3, 4], dtype=dtypes.int64) l_new_0 = list_ops.tensor_list_from_tensor(c34, element_shape=[]) c56 = constant_op.constant([5, 6], dtype=dtypes.int64) l_new_1 = list_ops.tensor_list_from_tensor(c56, element_shape=[]) updated_v = state_ops.scatter_update(v, [3, 5], [l_new_0, l_new_1]) updated_v_elems = array_ops_stack.unstack(updated_v) updated_v_stacked = [ list_ops.tensor_list_stack(el, dtypes.int64) for el in updated_v_elems ] expected = ([[1, 2]] * 3 + [[3, 4], [1, 2], [5, 6]] + [[1, 2]] * 4) self.assertAllEqual(self.evaluate(updated_v_stacked), expected) @test_util.run_deprecated_v1 def testConcat(self): c = constant_op.constant([1.0, 2.0], dtype=dtypes.float32) l0 = list_ops.tensor_list_from_tensor(c, element_shape=[]) l1 = list_ops.tensor_list_from_tensor([-1.0], element_shape=[]) l_batch_0 = array_ops_stack.stack([l0, l1]) l_batch_1 = array_ops_stack.stack([l1, l0]) l_concat_01 = list_ops.tensor_list_concat_lists( l_batch_0, l_batch_1, element_dtype=dtypes.float32) l_concat_10 = list_ops.tensor_list_concat_lists( l_batch_1, l_batch_0, element_dtype=dtypes.float32) l_concat_00 = list_ops.tensor_list_concat_lists( l_batch_0, l_batch_0, element_dtype=dtypes.float32) l_concat_11 = list_ops.tensor_list_concat_lists( l_batch_1, l_batch_1, element_dtype=dtypes.float32) expected_0 = [[1.0, 2.0], [-1.0]] expected_1 = [[-1.0], [1.0, 2.0]] expected_00 = [[1.0, 2.0, 1.0, 2.0], [-1.0, -1.0]] expected_01 = [[1.0, 2.0, -1.0], [-1.0, 1.0, 2.0]] expected_10 = [[-1.0, 1.0, 2.0], [1.0, 2.0, -1.0]] expected_11 = [[-1.0, -1.0], [1.0, 2.0, 1.0, 2.0]] for i, (concat, expected) in enumerate(zip( [l_batch_0, l_batch_1, l_concat_00, l_concat_01, l_concat_10, l_concat_11], [expected_0, expected_1, expected_00, expected_01, expected_10, expected_11])): splitted = array_ops_stack.unstack(concat) # go/LEGACY_TYPO splitted_stacked_ret = self.evaluate( # go/LEGACY_TYPO (list_ops.tensor_list_stack(splitted[0], dtypes.float32), list_ops.tensor_list_stack(splitted[1], dtypes.float32))) print("Test concat %d: %s, %s, %s, %s" % (i, expected[0], splitted_stacked_ret[0], expected[1], splitted_stacked_ret[1])) self.assertAllClose(expected[0], splitted_stacked_ret[0]) self.assertAllClose(expected[1], splitted_stacked_ret[1]) # Concatenating mismatched shapes fails. with self.assertRaises((errors.InvalidArgumentError, ValueError)): self.evaluate( list_ops.tensor_list_concat_lists( l_batch_0, list_ops.empty_tensor_list([], dtypes.float32), element_dtype=dtypes.float32)) if context.executing_eagerly(): expected_error = ( errors.InvalidArgumentError, "element shapes are not identical at index 0") else: expected_error = (ValueError, "Shapes must be equal rank") with self.assertRaisesRegex(*expected_error): l_batch_of_vec_tls = array_ops_stack.stack( [list_ops.tensor_list_from_tensor([[1.0]], element_shape=[1])] * 2) self.evaluate( list_ops.tensor_list_concat_lists(l_batch_0, l_batch_of_vec_tls, element_dtype=dtypes.float32)) if context.executing_eagerly(): expected_error = (errors.InvalidArgumentError, r"input_b\[0\].dtype != element_dtype.") else: expected_error = (ValueError, "input_b.type != element_dtype") with self.assertRaisesRegex(*expected_error): l_batch_of_int_tls = array_ops_stack.stack( [list_ops.tensor_list_from_tensor([1], element_shape=[])] * 2) self.evaluate( list_ops.tensor_list_concat_lists(l_batch_0, l_batch_of_int_tls, element_dtype=dtypes.float32)) @test_util.run_deprecated_v1 def testPushBackBatch(self): c = constant_op.constant([1.0, 2.0], dtype=dtypes.float32) l0 = list_ops.tensor_list_from_tensor(c, element_shape=[]) l1 = list_ops.tensor_list_from_tensor([-1.0], element_shape=[]) l_batch = array_ops_stack.stack([l0, l1]) l_push = list_ops.tensor_list_push_back_batch(l_batch, [3.0, 4.0]) l_unstack = array_ops_stack.unstack(l_push) l0_ret = list_ops.tensor_list_stack(l_unstack[0], dtypes.float32) l1_ret = list_ops.tensor_list_stack(l_unstack[1], dtypes.float32) self.assertAllClose([1.0, 2.0, 3.0], self.evaluate(l0_ret)) self.assertAllClose([-1.0, 4.0], self.evaluate(l1_ret)) with ops.control_dependencies([l_push]): l_unstack_orig = array_ops_stack.unstack(l_batch) l0_orig_ret = list_ops.tensor_list_stack(l_unstack_orig[0], dtypes.float32) l1_orig_ret = list_ops.tensor_list_stack(l_unstack_orig[1], dtypes.float32) # Check that without aliasing, push_back_batch still works; and # that it doesn't modify the input. l0_r_v, l1_r_v, l0_orig_v, l1_orig_v = self.evaluate( (l0_ret, l1_ret, l0_orig_ret, l1_orig_ret)) self.assertAllClose([1.0, 2.0, 3.0], l0_r_v) self.assertAllClose([-1.0, 4.0], l1_r_v) self.assertAllClose([1.0, 2.0], l0_orig_v) self.assertAllClose([-1.0], l1_orig_v) # Pushing back mismatched shapes fails. with self.assertRaises((errors.InvalidArgumentError, ValueError)): self.evaluate(list_ops.tensor_list_push_back_batch(l_batch, [])) with self.assertRaisesRegex(errors.InvalidArgumentError, "incompatible shape to a list at index 0"): self.evaluate( list_ops.tensor_list_push_back_batch(l_batch, [[3.0], [4.0]])) if context.executing_eagerly(): expected_error = (errors.InvalidArgumentError, "Invalid data type") else: expected_error = (ValueError, "wrong element dtype") with self.assertRaisesRegex(*expected_error): self.evaluate(list_ops.tensor_list_push_back_batch(l_batch, [3, 4])) def testZerosLike(self): for dtype in (dtypes.uint8, dtypes.uint16, dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64, dtypes.float16, dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128, dtypes.bool): l_empty = list_ops.empty_tensor_list( element_dtype=dtype, element_shape=[]) l_empty_zeros = array_ops.zeros_like(l_empty) t_empty_zeros = list_ops.tensor_list_stack( l_empty_zeros, element_dtype=dtype) l_full = list_ops.tensor_list_push_back(l_empty, math_ops.cast(0, dtype=dtype)) l_full = list_ops.tensor_list_push_back(l_full, math_ops.cast(1, dtype=dtype)) l_full_zeros = array_ops.zeros_like(l_full) t_full_zeros = list_ops.tensor_list_stack( l_full_zeros, element_dtype=dtype) self.assertAllEqual(self.evaluate(t_empty_zeros), []) self.assertAllEqual( self.evaluate(t_full_zeros), np.zeros( (2,), dtype=dtype.as_numpy_dtype)) def testZerosLikeNested(self): for dtype in (dtypes.uint8, dtypes.uint16, dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64, dtypes.float16, dtypes.float32, dtypes.float64, dtypes.complex64, dtypes.complex128, dtypes.bool): l = list_ops.empty_tensor_list( element_dtype=dtypes.variant, element_shape=[]) sub_l = list_ops.empty_tensor_list(element_dtype=dtype, element_shape=[]) l = list_ops.tensor_list_push_back(l, sub_l) sub_l = list_ops.tensor_list_push_back(sub_l, math_ops.cast( 1, dtype=dtype)) l = list_ops.tensor_list_push_back(l, sub_l) sub_l = list_ops.tensor_list_push_back(sub_l, math_ops.cast( 2, dtype=dtype)) l = list_ops.tensor_list_push_back(l, sub_l) # l : [[], # [1], # [1, 2]] # # l_zeros : [[], # [0], # [0, 0]] l_zeros = array_ops.zeros_like(l) outputs = [] for _ in range(3): l_zeros, out = list_ops.tensor_list_pop_back( l_zeros, element_dtype=dtypes.variant) outputs.append(list_ops.tensor_list_stack(out, element_dtype=dtype)) # Note: `outputs` contains popped values so the order is reversed. self.assertAllEqual(self.evaluate(outputs[2]), []) self.assertAllEqual( self.evaluate(outputs[1]), np.zeros((1,), dtype=dtype.as_numpy_dtype)) self.assertAllEqual( self.evaluate(outputs[0]), np.zeros((2,), dtype=dtype.as_numpy_dtype)) def testElementShape(self): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=None) shape = list_ops.tensor_list_element_shape(l, shape_type=dtypes.int32) self.assertEqual(self.evaluate(shape), -1) def testZerosLikeUninitialized(self): l0 = list_ops.tensor_list_reserve([], 3, element_dtype=dtypes.float32) l1 = list_ops.tensor_list_set_item(l0, 0, 1.) # [1., _, _] zeros_1 = array_ops.zeros_like(l1) # [0., _, _] l2 = list_ops.tensor_list_set_item(l1, 2, 2.) # [1., _, 2.] zeros_2 = array_ops.zeros_like(l2) # [0., _, 0.] # Gather indices with zeros in `zeros_1`. res_1 = list_ops.tensor_list_gather( zeros_1, [0], element_dtype=dtypes.float32) # Gather indices with zeros in `zeros_2`. res_2 = list_ops.tensor_list_gather( zeros_2, [0, 2], element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(res_1), [0.]) self.assertAllEqual(self.evaluate(res_2), [0., 0.]) @test_util.run_deprecated_v1 def testSkipEagerTensorListGetItemGradAggregation(self): l = list_ops.tensor_list_reserve( element_shape=[], num_elements=1, element_dtype=dtypes.float32) x = constant_op.constant(1.0) l = list_ops.tensor_list_set_item(l, 0, x) l_read1 = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32) l_read2 = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32) grad = gradients_impl.gradients([l_read1, l_read2], [x]) with self.cached_session() as sess: self.assertSequenceEqual(self.evaluate(grad), [2.]) @test_util.run_deprecated_v1 def testSkipEagerBuildElementShape(self): fn = list_ops._build_element_shape # Unknown shape -> -1. self.assertEqual(fn(None), -1) self.assertEqual(fn(tensor_shape.unknown_shape()), -1) # Scalar shape -> [] with type int32. self.assertEqual(fn([]).dtype, dtypes.int32) self.assertEqual(fn(tensor_shape.TensorShape([])).dtype, dtypes.int32) self.assertAllEqual(self.evaluate(fn([])), np.array([], np.int32)) self.assertAllEqual( self.evaluate(fn(tensor_shape.TensorShape([]))), np.array([], np.int32)) # Tensor -> Tensor shape = constant_op.constant(1) self.assertIs(fn(shape), shape) # Shape with unknown dims -> shape list with -1's. shape = [None, 5] self.assertAllEqual(fn(shape), [-1, 5]) self.assertAllEqual(fn(tensor_shape.TensorShape(shape)), [-1, 5]) # Shape with unknown dims and tensor dims -> shape list with -1's and tensor # dims. t = array_ops.placeholder(dtypes.int32) shape = [None, 5, t] result = fn(shape) self.assertAllEqual(result[:2], [-1, 5]) self.assertIs(result[2], t) def testAddN(self): l1 = list_ops.tensor_list_from_tensor([1.0, 2.0], element_shape=[]) l2 = list_ops.tensor_list_from_tensor([3.0, 4.0], element_shape=[]) l3 = list_ops.tensor_list_from_tensor([5.0, 6.0], element_shape=[]) result = math_ops.add_n((l1, l2, l3)) result_t = list_ops.tensor_list_stack(result, element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(result_t), [9., 12.]) def testAddNNestedList(self): l1 = list_ops.tensor_list_from_tensor([1.0, 2.0], element_shape=[]) l2 = list_ops.tensor_list_from_tensor([3.0, 4.0], element_shape=[]) l3 = list_ops.tensor_list_from_tensor([5.0, 6.0], element_shape=[]) l4 = list_ops.tensor_list_from_tensor([7.0, 8.0], element_shape=[]) a = list_ops.empty_tensor_list( element_dtype=dtypes.variant, element_shape=[]) a = list_ops.tensor_list_push_back(a, l1) a = list_ops.tensor_list_push_back(a, l2) b = list_ops.empty_tensor_list( element_dtype=dtypes.variant, element_shape=[]) b = list_ops.tensor_list_push_back(b, l3) b = list_ops.tensor_list_push_back(b, l4) result = math_ops.add_n((a, b)) result_0 = list_ops.tensor_list_stack( list_ops.tensor_list_get_item(result, 0, element_dtype=dtypes.variant), element_dtype=dtypes.float32) result_1 = list_ops.tensor_list_stack( list_ops.tensor_list_get_item(result, 1, element_dtype=dtypes.variant), element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(result_0), [6., 8.]) self.assertAllEqual(self.evaluate(result_1), [10., 12.]) def testAddTensorListsFailsIfLeadingDimsMismatch(self): l1 = list_ops.tensor_list_reserve( element_shape=[], element_dtype=dtypes.float32, num_elements=2) l2 = list_ops.tensor_list_reserve( element_shape=[], element_dtype=dtypes.float32, num_elements=3) with self.assertRaisesRegex( errors.InvalidArgumentError, "Trying to add two lists of tensors with different lengths"): l = math_ops.add_n([l1, l2]) self.evaluate(list_ops.tensor_list_stack(l, element_dtype=dtypes.float32)) @test_util.run_v1_only("Uses placeholders") def testSkipEagerAddTensorListsFailsIfElementShapesMismatch(self): with self.cached_session() as sess: # Use placeholders instead of constant values for shapes to prevent TF's # shape inference from catching this early. l1_element_shape = array_ops.placeholder(dtype=dtypes.int32) l2_element_shape = array_ops.placeholder(dtype=dtypes.int32) l1 = list_ops.tensor_list_reserve( element_shape=l1_element_shape, element_dtype=dtypes.float32, num_elements=3) l2 = list_ops.tensor_list_reserve( element_shape=l2_element_shape, element_dtype=dtypes.float32, num_elements=3) l = math_ops.add_n([l1, l2]) with self.assertRaisesRegex( errors.InvalidArgumentError, "Trying to add two lists of tensors with incompatible element shapes" ): sess.run( list_ops.tensor_list_stack(l, element_dtype=dtypes.float32), { l1_element_shape: [], l2_element_shape: [2] }) @test_util.run_deprecated_v1 def testSkipEagerConcatShapeInference(self): def BuildTensor(element_shape): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=element_shape) return list_ops.tensor_list_concat(l, element_dtype=dtypes.float32) self.assertIsNone(BuildTensor(None).shape.rank) self.assertAllEqual(BuildTensor([None, 2, 3]).shape.as_list(), [None, 2, 3]) self.assertAllEqual( BuildTensor([None, 2, None]).shape.as_list(), [None, 2, None]) self.assertAllEqual(BuildTensor([1, 2, 3]).shape.as_list(), [None, 2, 3]) def testConcatWithFullyDefinedElementShape(self): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[2, 2]) l = list_ops.tensor_list_push_back(l, [[0., 1.], [2., 3.]]) l = list_ops.tensor_list_push_back(l, [[4., 5.], [6., 7.]]) t = list_ops.tensor_list_concat(l, element_dtype=dtypes.float32) self.assertAllEqual( self.evaluate(t), [[0., 1.], [2., 3.], [4., 5.], [6., 7.]]) def testConcatWithNonFullyDefinedElementShape(self): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[None, 2]) l = list_ops.tensor_list_push_back(l, [[0., 1.]]) l = list_ops.tensor_list_push_back(l, [[2., 3.], [4., 5.]]) t = list_ops.tensor_list_concat(l, element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t), [[0., 1.], [2., 3.], [4., 5.]]) def testConcatWithMismatchingTensorShapesFails(self): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=None) l = list_ops.tensor_list_push_back(l, [[0., 1.]]) l = list_ops.tensor_list_push_back(l, [[2.], [4.]]) with self.assertRaisesRegex( errors.InvalidArgumentError, r"Incompatible shapes during merge: " r"\[2\] vs. \[1\]"): t = list_ops.tensor_list_concat(l, element_dtype=dtypes.float32) self.evaluate(t) def testConcatEmptyListWithFullyDefinedElementShape(self): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[5, 2]) t = list_ops.tensor_list_concat(l, element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t).shape, (0, 2)) l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[None, 2]) t = list_ops.tensor_list_concat(l, element_dtype=dtypes.float32) self.assertAllEqual(self.evaluate(t).shape, (0, 2)) def testConcatEmptyListWithUnknownElementShapeFails(self): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=None) with self.assertRaisesRegex( errors.InvalidArgumentError, "All except the first dimension must be fully" " defined when concating an empty tensor list"): t = list_ops.tensor_list_concat(l, element_dtype=dtypes.float32) self.evaluate(t) def testConcatEmptyListWithPartiallyDefinedElementShapeFails(self): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=[2, None]) with self.assertRaisesRegex( errors.InvalidArgumentError, "All except the first dimension must be fully" " defined when concating an empty tensor list"): t = list_ops.tensor_list_concat(l, element_dtype=dtypes.float32) self.evaluate(t) def testConcatListWithScalarElementShapeFails(self): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=tensor_shape.TensorShape([])) with self.assertRaisesRegex( errors.InvalidArgumentError, "Concat requires elements to be at least vectors, " "found scalars instead"): t = list_ops.tensor_list_concat(l, element_dtype=dtypes.float32) self.evaluate(t) def testConcatListWithScalarElementsFails(self): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=None) l1 = list_ops.tensor_list_push_back(l, 1.) with self.assertRaisesRegex( errors.InvalidArgumentError, "Concat saw a scalar shape at index 0" " but requires at least vectors"): t = list_ops.tensor_list_concat(l1, element_dtype=dtypes.float32) self.evaluate(t) l1 = list_ops.tensor_list_push_back(l, [1.]) l1 = list_ops.tensor_list_push_back(l1, 2.) with self.assertRaisesRegex( errors.InvalidArgumentError, "Concat saw a scalar shape at index 1" " but requires at least vectors"): t = list_ops.tensor_list_concat(l1, element_dtype=dtypes.float32) self.evaluate(t) def testConcatWithUninitializedTensorsUseListElementShape(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[2, 3], num_elements=3) t = list_ops.tensor_list_concat(l, element_dtype=dtypes.float32) self.assertAllEqual(np.zeros((6, 3)), t) def testConcatWithUninitializedTensorsUseProvidedElementShape(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=None, num_elements=3) t = list_ops.tensor_list_concat( l, element_dtype=dtypes.float32, element_shape=(2, 3)) self.assertAllEqual(np.zeros((6, 3)), t) def testConcatWithUninitializedTensorsUseProvidedElementShapeAndLengths(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=None, num_elements=3) t, _ = gen_list_ops.tensor_list_concat_v2( l, element_dtype=dtypes.float32, element_shape=list_ops._build_element_shape((None, 3)), leading_dims=[2, 3, 5]) self.assertAllEqual(np.zeros((10, 3)), t) l = list_ops.tensor_list_set_item(l, 1, [[2., 3.], [4., 5.], [6., 7.]]) t, _ = gen_list_ops.tensor_list_concat_v2( l, element_dtype=dtypes.float32, element_shape=list_ops._build_element_shape((None, 2)), leading_dims=[2, 3, 4]) self.assertAllEqual([[0., 0.], [0., 0.], [2., 3.], [4., 5.], [6., 7.], [0., 0.], [0., 0.], [0., 0.], [0., 0.]], t) def testConcatWithUninitializedTensorsInferShapeFromElements(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=None, num_elements=3) l = list_ops.tensor_list_set_item(l, 1, [[2., 3.], [4., 5.], [6., 7.]]) t = list_ops.tensor_list_concat(l, element_dtype=dtypes.float32) self.assertAllEqual([[0., 0.], [0., 0.], [0., 0.], [2., 3.], [4., 5.], [6., 7.], [0., 0.], [0., 0.], [0., 0.]], t) def testConcatWithUninitializedTensorsFailsIfNoElementShape(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=None, num_elements=3) with self.assertRaisesRegex( errors.InvalidArgumentError, r"Trying to concat list with only uninitialized tensors " r"but element_shape_except_first_dim is not fully defined"): t = list_ops.tensor_list_concat(l, element_dtype=dtypes.float32) self.evaluate(t) def testConcatWithUninitializedTensorsFailsIfNoInputLengths(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[None, 3], num_elements=3) with self.assertRaisesRegex( errors.InvalidArgumentError, r"List contains uninitialized tensor at index 0" r" but leading_dims has only 0 elements."): t = list_ops.tensor_list_concat(l, element_dtype=dtypes.float32) self.evaluate(t) @test_util.run_in_graph_and_eager_modes def testConcatWithInvalidElementShape(self): l = list_ops.tensor_list_reserve( element_dtype=dtypes.float32, element_shape=[], num_elements=0) with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), r"element_shape must not be empty"): self.evaluate(gen_list_ops.tensor_list_concat( input_handle=l, element_dtype=dtypes.float32, element_shape=[])) def testEmptyTensorListInvalidShape(self): with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), r"Shape must be at most rank 1 but is rank 2"): t = gen_list_ops.EmptyTensorList( element_shape=array_ops.ones(dtype=dtypes.int32, shape=[1, 0]), max_num_elements=constant_op.constant(1), element_dtype=dtypes.int32) self.evaluate(t) def testEvenSplit(self): def RunTest(input_tensor, lengths, expected_stacked_output): l = list_ops.tensor_list_split( input_tensor, element_shape=None, lengths=lengths) self.assertAllEqual( list_ops.tensor_list_stack(l, element_dtype=dtypes.float32), expected_stacked_output) RunTest([1., 2., 3.], [1, 1, 1], [[1.], [2.], [3.]]) RunTest([1., 2., 3., 4.], [2, 2], [[1., 2.], [3., 4.]]) RunTest([[1., 2.], [3., 4.]], [1, 1], [[[1., 2.]], [[3., 4.]]]) def testUnevenSplit(self): l = list_ops.tensor_list_split([1., 2., 3., 4., 5], element_shape=None, lengths=[3, 2]) self.assertAllEqual(list_ops.tensor_list_length(l), 2) self.assertAllEqual( list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32), [1., 2., 3.]) self.assertAllEqual( list_ops.tensor_list_get_item(l, 1, element_dtype=dtypes.float32), [4., 5.]) @test_util.run_deprecated_v1 def testSkipEagerSplitWithInvalidTensorShapeFails(self): with self.cached_session(): tensor = array_ops.placeholder(dtype=dtypes.float32) l = list_ops.tensor_list_split(tensor, element_shape=None, lengths=[1]) with self.assertRaisesRegex( errors.InvalidArgumentError, r"Tensor must be at least a vector, but saw shape: \[\]"): l.eval({tensor: 1}) @test_util.run_deprecated_v1 def testSkipEagerSplitWithInvalidLengthsShapeFails(self): with self.cached_session(): lengths = array_ops.placeholder(dtype=dtypes.int64) l = list_ops.tensor_list_split([1., 2.], element_shape=None, lengths=lengths) with self.assertRaisesRegex( errors.InvalidArgumentError, r"Expected lengths to be a vector, received shape: \[\]"): l.eval({lengths: 1}) def testSplitWithInvalidLengthsFails(self): with self.assertRaisesRegex(errors.InvalidArgumentError, r"Invalid value in lengths: -1"): l = list_ops.tensor_list_split([1., 2.], element_shape=None, lengths=[1, -1]) self.evaluate(l) with self.assertRaisesRegex( errors.InvalidArgumentError, r"Attempting to slice \[0, 3\] from tensor with length 2"): l = list_ops.tensor_list_split([1., 2.], element_shape=None, lengths=[3]) self.evaluate(l) with self.assertRaisesRegex( errors.InvalidArgumentError, r"Unused values in tensor. Length of tensor: 2 Values used: 1"): l = list_ops.tensor_list_split([1., 2.], element_shape=None, lengths=[1]) self.evaluate(l) @test_util.run_deprecated_v1 def testSkipEagerSplitWithScalarElementShapeFails(self): with self.assertRaisesRegex(ValueError, r"Shapes must be equal rank, but are 1 and 0"): l = list_ops.tensor_list_split([1., 2.], element_shape=[], lengths=[1, 1]) with self.cached_session(): with self.assertRaisesRegex( errors.InvalidArgumentError, r"TensorListSplit requires element_shape to be at least of rank 1, " r"but saw: \[\]"): element_shape = array_ops.placeholder(dtype=dtypes.int32) l = list_ops.tensor_list_split([1., 2.], element_shape=element_shape, lengths=[1, 1]) l.eval({element_shape: []}) def testEagerOnlySplitWithScalarElementShapeFails(self): if context.executing_eagerly(): with self.assertRaisesRegex( errors.InvalidArgumentError, r"TensorListSplit requires element_shape to be at least of rank 1, " r"but saw: \[\]"): list_ops.tensor_list_split([1., 2.], element_shape=[], lengths=[1, 1]) @test_util.run_deprecated_v1 def testSkipEagerSplitWithIncompatibleTensorShapeAndElementShapeFails(self): with self.assertRaisesRegex(ValueError, r"Shapes must be equal rank, but are 2 and 1"): l = list_ops.tensor_list_split([[1.], [2.]], element_shape=[1], lengths=[1, 1]) with self.cached_session(): with self.assertRaisesRegex( errors.InvalidArgumentError, r"tensor shape \[2,1\] is not compatible with element_shape \[1\]"): element_shape = array_ops.placeholder(dtype=dtypes.int32) l = list_ops.tensor_list_split([[1.], [2.]], element_shape=element_shape, lengths=[1, 1]) l.eval({element_shape: [1]}) def testEagerOnlySplitWithIncompatibleTensorShapeAndElementShapeFails(self): if context.executing_eagerly(): with self.assertRaisesRegex( errors.InvalidArgumentError, r"tensor shape \[2,1\] is not compatible with element_shape \[1\]"): list_ops.tensor_list_split([[1.], [2.]], element_shape=[1], lengths=[1, 1]) def testResizeGrow(self): l = list_ops.tensor_list_from_tensor([1., 2.], element_shape=[]) l = list_ops.tensor_list_resize(l, 4) self.assertEqual(self.evaluate(list_ops.tensor_list_length(l)), 4) self.assertEqual( self.evaluate( list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32)), 1.) self.assertEqual( self.evaluate( list_ops.tensor_list_get_item(l, 1, element_dtype=dtypes.float32)), 2.) def testResizeShrink(self): l = list_ops.tensor_list_from_tensor([1., 2., 3.], element_shape=[]) l = list_ops.tensor_list_resize(l, 2) self.assertEqual(self.evaluate(list_ops.tensor_list_length(l)), 2) self.assertAllEqual( self.evaluate( list_ops.tensor_list_stack(l, element_dtype=dtypes.float32)), [1., 2.]) def testResizeWithInvalidSizeFails(self): with self.assertRaisesRegex( errors.InvalidArgumentError, "TensorListSlice expects size to be non-negative"): l = list_ops.tensor_list_from_tensor([1., 2., 3.], element_shape=[]) l = list_ops.tensor_list_resize(l, -1) self.evaluate(l) @test_util.run_in_graph_and_eager_modes def testResizeWithNonScalarFails(self): l = list_ops.tensor_list_from_tensor([3, 4, 5], element_shape=[]) size = np.zeros([0, 2, 3, 3]) with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), r"Shape must be rank 0 but is rank \d+|" r"\w+ must be a scalar"): self.evaluate(gen_list_ops.TensorListResize(input_handle=l, size=size)) @test_util.run_deprecated_v1 @test_util.enable_control_flow_v2 def testSkipEagerResizeGrad(self): t = constant_op.constant([1., 2., 3.]) l = list_ops.tensor_list_from_tensor(t, element_shape=[]) l = list_ops.tensor_list_set_item( l, 3, 4., resize_if_index_out_of_bounds=True) t1 = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) grad = gradients_impl.gradients(t1, t)[0] self.assertAllEqual(self.evaluate(grad), [1., 1., 1.]) def testHandleDataAcrossFunctionCall(self): @def_function.function def func(): t = constant_op.constant([1., 2., 3.]) l = list_ops.tensor_list_from_tensor(t, element_shape=[]) handle_data = resource_variable_ops.get_eager_safe_handle_data(l) self.assertTrue(handle_data.is_set) self.assertEqual(handle_data.shape_and_type[0].type.type_id, full_type_pb2.TFT_ARRAY) return l tensor_list = func() handle_data = resource_variable_ops.get_eager_safe_handle_data(tensor_list) self.assertTrue(handle_data.is_set) self.assertEqual(dtypes.float32, handle_data.shape_and_type[0].dtype) self.assertEqual(handle_data.shape_and_type[0].type.type_id, full_type_pb2.TFT_ARRAY) element = list_ops.tensor_list_get_item( tensor_list, 0, element_dtype=dtypes.float32) self.assertAllEqual(element.shape.as_list(), []) @test_util.run_gpu_only def testNestedListDevicetoDeviceCopy(self): if context.num_gpus() < 2: self.skipTest("Need at least 2 GPUs for this test, found %d" % context.num_gpus()) with ops.device("gpu:0"): t = constant_op.constant([1.0, 2.0, 3.0]) inner_l = list_ops.tensor_list_from_tensor(t, element_shape=[]) outer_l = list_ops.empty_tensor_list( element_dtype=dtypes.variant, element_shape=[]) outer_l = list_ops.tensor_list_push_back(outer_l, inner_l) # Stress test. for _ in range(1024): with ops.device("gpu:1"): outer_l = array_ops.identity(outer_l) with ops.device("gpu:0"): outer_l = array_ops.identity(outer_l) with ops.device("gpu:1"): _, inner_l = list_ops.tensor_list_pop_back( outer_l, element_dtype=dtypes.variant) t = list_ops.tensor_list_stack(inner_l, element_dtype=dtypes.float32) self.assertAllEqual(t, [1.0, 2.0, 3.0]) def testTensorListStrings(self): @def_function.function def f(): return map_fn.map_fn(string_ops.string_upper, constant_op.constant(["a", "b", "c"])) self.assertAllEqual(f(), [b"A", b"B", b"C"]) def testTensorListStringsNoInline(self): # Generator function output type is a variant with a host-only underlying # data type. "ColocationGraph::AddHostOnlyDataTypesConstraints" needs to # have "deep op inspection" to be able to correctly place the while loop # generated from map_fn. self.skipTest("b/150742232") @def_function.function(experimental_attributes={"_noinline": True}) def generator(c): return list_ops.tensor_list_from_tensor(c, element_shape=[]) @def_function.function def f(c): l = generator(c) def upper(i): e = list_ops.tensor_list_get_item(l, i, element_dtype=dtypes.string) return string_ops.string_upper(e) return map_fn.map_fn( upper, constant_op.constant([0, 1, 2]), dtype=dtypes.string) c = constant_op.constant(["a", "b", "c"]) self.assertAllEqual(f(c), [b"A", b"B", b"C"]) def testPopBackGrad(self): # https://github.com/tensorflow/tensorflow/issues/37230 @def_function.function def g(x): x_prod = constant_op.constant([1.]) for unused_i in math_ops.range(3): x_prod = x_prod * x return x_prod x = constant_op.constant(1.) with backprop.GradientTape() as t: t.watch(x) with backprop.GradientTape() as tt: tt.watch(x) loss = g(x) jac = tt.gradient(loss, x) hess = t.gradient(jac, x) self.assertAllEqual(hess, 6.) def testTensorListElementShapeShapeInference(self): @def_function.function def f(): l = list_ops.empty_tensor_list( element_dtype=dtypes.float32, element_shape=None) l_element_shape = list_ops.tensor_list_element_shape(l, dtypes.int32) self.assertIsNone(l_element_shape.shape.rank) shape_l = list_ops.empty_tensor_list( element_dtype=dtypes.int32, element_shape=l_element_shape.shape) shape_l = list_ops.tensor_list_push_back(shape_l, l_element_shape) return list_ops.tensor_list_pop_back(shape_l, dtypes.int32)[1] self.assertAllEqual(f(), -1) def testElementShapeArgOfTensorListFromTensor(self): @def_function.function def f(): t = array_ops.ones([3, 3]) l = list_ops.tensor_list_from_tensor(t, element_shape=[-1]) l = list_ops.tensor_list_push_back(l, array_ops.ones([4])) read_val = list_ops.tensor_list_get_item( l, 3, element_dtype=dtypes.float32) self.assertAllEqual(read_val.shape.as_list(), [None]) return read_val self.assertAllEqual(f(), [1.0, 1.0, 1.0, 1.0]) if __name__ == "__main__": test.main()
ListOpsTest
python
PrefectHQ__prefect
src/prefect/_internal/concurrency/cancellation.py
{ "start": 9090, "end": 9647 }
class ____(CancelScope): """ A cancel scope that does nothing. This is used for environments where cancellation is not supported. """ def __init__( self, name: Optional[str] = None, timeout: Optional[float] = None, reason: Optional[str] = None, ) -> None: super().__init__(name, timeout) self.reason = reason or "null cancel scope" def cancel(self, throw: bool = True) -> bool: logger.warning("%r cannot cancel %s.", self, self.reason) return False
NullCancelScope
python
doocs__leetcode
solution/1900-1999/1930.Unique Length-3 Palindromic Subsequences/Solution.py
{ "start": 0, "end": 256 }
class ____: def countPalindromicSubsequence(self, s: str) -> int: ans = 0 for c in ascii_lowercase: l, r = s.find(c), s.rfind(c) if r - l > 1: ans += len(set(s[l + 1 : r])) return ans
Solution
python
kamyu104__LeetCode-Solutions
Python/smallest-missing-non-negative-integer-after-operations.py
{ "start": 74, "end": 473 }
class ____(object): def findSmallestInteger(self, nums, value): """ :type nums: List[int] :type value: int :rtype: int """ cnt = collections.Counter(x%value for x in nums) mn = min((cnt[i], i) for i in xrange(value))[1] return value*cnt[mn]+mn # Time: O(n) # Space: O(k), k = value import collections # freq table
Solution
python
ray-project__ray
doc/source/_ext/queryparamrefs.py
{ "start": 274, "end": 867 }
class ____(nodes.paragraph): """A wrapper node for URL query param references. Sphinx will not build if you don't wrap a reference in a paragraph. And a <div> is needed anyway for styling purposes. """ def visit(self, node): if "class" not in node: raise ValueError( "'class' attribute must be set on the WrapperNode for a " "URL query parameter reference." ) self.body.append(self.starttag(node, "div", CLASS=node["class"])) def depart(self, node): self.body.append("</div>")
WrapperNode
python
TheAlgorithms__Python
maths/monte_carlo_dice.py
{ "start": 52, "end": 1260 }
class ____: NUM_SIDES = 6 def __init__(self): """Initialize a six sided dice""" self.sides = list(range(1, Dice.NUM_SIDES + 1)) def roll(self): return random.choice(self.sides) def throw_dice(num_throws: int, num_dice: int = 2) -> list[float]: """ Return probability list of all possible sums when throwing dice. >>> random.seed(0) >>> throw_dice(10, 1) [10.0, 0.0, 30.0, 50.0, 10.0, 0.0] >>> throw_dice(100, 1) [19.0, 17.0, 17.0, 11.0, 23.0, 13.0] >>> throw_dice(1000, 1) [18.8, 15.5, 16.3, 17.6, 14.2, 17.6] >>> throw_dice(10000, 1) [16.35, 16.89, 16.93, 16.6, 16.52, 16.71] >>> throw_dice(10000, 2) [2.74, 5.6, 7.99, 11.26, 13.92, 16.7, 14.44, 10.63, 8.05, 5.92, 2.75] """ dices = [Dice() for i in range(num_dice)] count_of_sum = [0] * (len(dices) * Dice.NUM_SIDES + 1) for _ in range(num_throws): count_of_sum[sum(dice.roll() for dice in dices)] += 1 probability = [round((count * 100) / num_throws, 2) for count in count_of_sum] return probability[num_dice:] # remove probability of sums that never appear if __name__ == "__main__": import doctest doctest.testmod()
Dice
python
ray-project__ray
python/ray/experimental/util/types.py
{ "start": 526, "end": 670 }
class ____(Enum): DEFAULT = "default" CPU = "cpu" GPU = "gpu" CUDA = "cuda" def __str__(self): return self.value
Device
python
neetcode-gh__leetcode
python/2215-find-the-difference-of-two-arrays.py
{ "start": 822, "end": 1148 }
class ____: def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: nums1_set = set(nums1) nums2_set = set(nums2) lst1 = [num for num in nums1_set if num not in nums2_set] lst2 = [num for num in nums2_set if num not in nums1_set] return [lst1, lst2]
Solution
python
django__django
tests/admin_inlines/admin.py
{ "start": 7045, "end": 7117 }
class ____(admin.TabularInline): model = ChildModel1
ChildModel1Inline
python
pytorch__pytorch
test/distributed/checkpoint/e2e/test_e2e_save_and_load.py
{ "start": 2875, "end": 3025 }
class ____(Enum): FSDP = auto() HSDP = auto() FSDP_TP = auto() DDP = auto() NONE = auto() # no parallelization @dataclass
ModelType
python
sphinx-doc__sphinx
sphinx/addnodes.py
{ "start": 14238, "end": 14536 }
class ____(nodes.Inline, nodes.Element): """Node for cross-references that cannot be resolved without complete information about all documents. These nodes are resolved before writing output, in BuildEnvironment.resolve_references. """ child_text_separator = ''
pending_xref
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 2178, "end": 3022 }
class ____(__config_flags): """ A cross-version compatibility configuration for pyparsing features that will be released in a future version. By setting values in this configuration to True, those features can be enabled in prior versions for compatibility development and testing. - ``collect_all_And_tokens`` - flag to enable fix for Issue #63 that fixes erroneous grouping of results names when an :class:`And` expression is nested within an :class:`Or` or :class:`MatchFirst`; maintained for compatibility, but setting to ``False`` no longer restores pre-2.3.1 behavior """ _type_desc = "compatibility" collect_all_And_tokens = True _all_names = [__ for __ in locals() if not __.startswith("_")] _fixed_names = """ collect_all_And_tokens """.split()
__compat__
python
huggingface__transformers
tests/models/mlcd/test_modeling_mlcd.py
{ "start": 4063, "end": 4944 }
class ____(ModelTesterMixin, unittest.TestCase): """ Model tester for `MLCDVisionModel`. """ all_model_classes = (MLCDVisionModel,) if is_torch_available() else () test_resize_embeddings = False test_torch_exportable = True def setUp(self): self.model_tester = MLCDVisionModelTester(self) self.config_tester = ConfigTester(self, config_class=MLCDVisionConfig, has_text_modality=False) def test_model_get_set_embeddings(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) self.assertIsInstance(model.get_input_embeddings(), (torch.nn.Module)) x = model.get_output_embeddings() self.assertTrue(x is None or isinstance(x, torch.nn.Linear)) @require_torch
MLCDVisionModelTest
python
tensorflow__tensorflow
tensorflow/lite/python/lite.py
{ "start": 115610, "end": 131716 }
class ____(TFLiteFrozenGraphConverter): """Convert a TensorFlow model into `output_format`. This is used to convert from a TensorFlow GraphDef, SavedModel or tf.keras model into either a TFLite FlatBuffer or graph visualization. Attributes: optimizations: Experimental flag, subject to change. Set of optimizations to apply. e.g {tf.lite.Optimize.DEFAULT}. (default None, must be None or a set of values of type `tf.lite.Optimize`) representative_dataset: A generator function used for integer quantization where each generated sample has the same order, type and shape as the inputs to the model. Usually, this is a small subset of a few hundred samples randomly chosen, in no particular order, from the training or evaluation dataset. This is an optional attribute, but required for full integer quantization, i.e, if `tf.int8` is the only supported type in `target_spec.supported_types`. Refer to `tf.lite.RepresentativeDataset`. (default None) target_spec: Experimental flag, subject to change. Specifications of target device, including supported ops set, supported types and a set of user's defined TensorFlow operators required in the TensorFlow Lite runtime. Refer to `tf.lite.TargetSpec`. inference_type: Data type of numeric arrays, excluding the input layer. (default tf.float32, must be in {tf.float32, tf.int8, tf.uint8}) inference_input_type: Data type of the numeric arrays in the input layer. If `inference_input_type` is in {tf.int8, tf.uint8}, then `quantized_input_stats` must be provided. (default is the value assigned to `inference_type`, must be in {tf.float32, tf.int8, tf.uint8}) inference_output_type: Data type of the numeric arrays in the output layer. (default is the value assigned to `inference_type`, must be in {tf.float32, tf.int8, tf.uint8}) quantized_input_stats: Map of input tensor names to a tuple of floats representing the mean and standard deviation of the training data. (e.g., {"foo" : (0., 1.)}). Required if `inference_input_type` is tf.int8 or tf.uint8. (default None) default_ranges_stats: Tuple of integers (min, max) representing range values for all numeric arrays without a specified range. Intended for experimenting with quantization via "dummy quantization". (default None) allow_custom_ops: Boolean indicating whether to allow custom operations. When False any unknown operation is an error. When True, custom ops are created for any op that is unknown. The developer will need to provide these to the TensorFlow Lite runtime with a custom resolver. (default False) drop_control_dependency: Boolean indicating whether to drop control dependencies silently. This is due to TFLite not supporting control dependencies. (default True) reorder_across_fake_quant: Boolean indicating whether to reorder FakeQuant nodes in unexpected locations. Used when the location of the FakeQuant nodes is preventing graph transformations necessary to convert the graph. Results in a graph that differs from the quantized training graph, potentially causing differing arithmetic behavior. (default False) change_concat_input_ranges: Boolean to change behavior of min/max ranges for inputs and outputs of the concat operator for quantized models. Changes the ranges of concat operator overlap when true. (default False) output_format: Output file format. (default tf.compat.v1.lite.constants.TFLITE, must be in {tf.compat.v1.lite.constants.TFLITE, tf.compat.v1.lite.constants.GRAPHVIZ_DOT}) dump_graphviz_dir: Full filepath of folder to dump the graphs at various stages of processing GraphViz .dot files. Preferred over `output_format=tf.compat.v1.lite.constants.GRAPHVIZ_DOT` in order to keep the requirements of the output file. (default None) dump_graphviz_video: Boolean indicating whether to dump the GraphViz .dot files after every graph transformation. Requires the `dump_graphviz_dir` flag to be specified. (default False) conversion_summary_dir: Full path of the directory to store conversion logs. (default None) exclude_conversion_metadata: Whether not to embed the conversion metadata into the converted model. (default False) target_ops: Deprecated. Please use `target_spec.supported_ops` instead. post_training_quantize: Deprecated. Please use `optimizations` instead and set it to `{tf.lite.Optimize.DEFAULT}`. (default False) experimental_new_converter: Experimental flag, subject to change. Enables MLIR-based conversion. (default True) experimental_new_quantizer: Experimental flag, subject to change. Enables MLIR-based quantization conversion instead of Flatbuffer-based conversion. (default True) Example usage: ```python # Converting a GraphDef from session. converter = tf.compat.v1.lite.TFLiteConverter.from_session( sess, in_tensors, out_tensors) tflite_model = converter.convert() open("converted_model.tflite", "wb").write(tflite_model) # Converting a GraphDef from file. converter = tf.compat.v1.lite.TFLiteConverter.from_frozen_graph( graph_def_file, input_arrays, output_arrays) tflite_model = converter.convert() open("converted_model.tflite", "wb").write(tflite_model) # Converting a SavedModel. converter = tf.compat.v1.lite.TFLiteConverter.from_saved_model( saved_model_dir) tflite_model = converter.convert() open("converted_model.tflite", "wb").write(tflite_model) # Converting a tf.keras model. converter = tf.compat.v1.lite.TFLiteConverter.from_keras_model_file( keras_model) tflite_model = converter.convert() open("converted_model.tflite", "wb").write(tflite_model) ``` """ # pylint: disable=useless-super-delegation def __init__( self, graph_def, input_tensors, output_tensors, input_arrays_with_shape=None, output_arrays=None, experimental_debug_info_func=None, ): """Constructor for TFLiteConverter. Args: graph_def: Frozen TensorFlow GraphDef. input_tensors: List of input tensors. Type and shape are computed using `foo.shape` and `foo.dtype`. output_tensors: List of output tensors (only .name is used from this). input_arrays_with_shape: Tuple of strings representing input tensor names and list of integers representing input shapes (e.g., [("foo" : [1, 16, 16, 3])]). Use only when graph cannot be loaded into TensorFlow and when `input_tensors` and `output_tensors` are None. (default None) output_arrays: List of output tensors to freeze graph with. Use only when graph cannot be loaded into TensorFlow and when `input_tensors` and `output_tensors` are None. (default None) experimental_debug_info_func: An experimental function to retrieve the graph debug info for a set of nodes from the `graph_def`. Raises: ValueError: Invalid arguments. """ super(TFLiteConverter, self).__init__( graph_def, input_tensors, output_tensors, input_arrays_with_shape, output_arrays, experimental_debug_info_func, ) @classmethod def from_session(cls, sess, input_tensors, output_tensors): """Creates a TFLiteConverter class from a TensorFlow Session. Args: sess: TensorFlow Session. input_tensors: List of input tensors. Type and shape are computed using `foo.shape` and `foo.dtype`. output_tensors: List of output tensors (only .name is used from this). Returns: TFLiteConverter class. """ # pylint: disable=protected-access TFLiteConverterBase._set_original_model_type( conversion_metadata_fb.ModelType.TF_SESSION ) # pylint: enable=protected-access graph_def = _freeze_graph(sess, input_tensors, output_tensors) return cls( graph_def, input_tensors, output_tensors, experimental_debug_info_func=_build_debug_info_func(sess.graph), ) @classmethod def from_frozen_graph( cls, graph_def_file, input_arrays, output_arrays, input_shapes=None ): """Creates a TFLiteConverter class from a file containing a frozen GraphDef. Args: graph_def_file: Full filepath of file containing frozen GraphDef. input_arrays: List of input tensors to freeze graph with. output_arrays: List of output tensors to freeze graph with. input_shapes: Dict of strings representing input tensor names to list of integers representing input shapes (e.g., {"foo" : [1, 16, 16, 3]}). Automatically determined when input shapes is None (e.g., {"foo" : None}). (default None) Returns: TFLiteConverter class. Raises: IOError: File not found. Unable to parse input file. ValueError: The graph is not frozen. input_arrays or output_arrays contains an invalid tensor name. input_shapes is not correctly defined when required """ # pylint: disable=protected-access TFLiteConverterBase._set_original_model_type( conversion_metadata_fb.ModelType.TF_GRAPH_DEF ) # pylint: enable=protected-access with _ops.Graph().as_default(): with _session.Session() as sess: # Read GraphDef from file. if not gfile.Exists(graph_def_file): raise IOError("File '{0}' does not exist.".format(graph_def_file)) with gfile.GFile(graph_def_file, "rb") as f: file_content = f.read() try: graph_def = _graph_pb2.GraphDef() graph_def.ParseFromString(file_content) except (_text_format.ParseError, DecodeError): try: print("Ignore 'tcmalloc: large alloc' warnings.") if not isinstance(file_content, str): file_content = file_content.decode("utf-8") graph_def = _graph_pb2.GraphDef() _text_format.Merge(file_content, graph_def) except (_text_format.ParseError, DecodeError): raise IOError( "Unable to parse input file '{}'.".format(graph_def_file) ) if sys.byteorder == "big": bst.swap_tensor_content_in_graph_node(graph_def, "little", "big") # Handles models with custom TFLite ops that cannot be resolved in # TensorFlow. load_model_in_session = True try: _import_graph_def(graph_def, name="") except _NotFoundError: load_model_in_session = False if load_model_in_session: # Check if graph is frozen. if not _is_frozen_graph(sess): raise ValueError("Please freeze the graph using freeze_graph.py.") # Get input and output tensors. input_tensors = _get_tensors_from_tensor_names( sess.graph, input_arrays ) output_tensors = _get_tensors_from_tensor_names( sess.graph, output_arrays ) _set_tensor_shapes(input_tensors, input_shapes) return cls(sess.graph_def, input_tensors, output_tensors) else: if not input_shapes: raise ValueError("input_shapes must be defined for this model.") if set(input_arrays) != set(input_shapes.keys()): raise ValueError( "input_shapes must contain a value for each item " "in input_array." ) input_arrays_with_shape = [ (name, input_shapes[name]) for name in input_arrays ] return cls( graph_def, input_tensors=None, output_tensors=None, input_arrays_with_shape=input_arrays_with_shape, output_arrays=output_arrays, ) @classmethod def from_saved_model( cls, saved_model_dir, input_arrays=None, input_shapes=None, output_arrays=None, tag_set=None, signature_key=None, ): """Creates a TFLiteConverter class from a SavedModel. Args: saved_model_dir: SavedModel directory to convert. input_arrays: List of input tensors to freeze graph with. Uses input arrays from SignatureDef when none are provided. (default None) input_shapes: Dict of strings representing input tensor names to list of integers representing input shapes (e.g., {"foo" : [1, 16, 16, 3]}). Automatically determined when input shapes is None (e.g., {"foo" : None}). (default None) output_arrays: List of output tensors to freeze graph with. Uses output arrays from SignatureDef when none are provided. (default None) tag_set: Set of tags identifying the MetaGraphDef within the SavedModel to analyze. All tags in the tag set must be present. (default {tf.saved_model.SERVING}) signature_key: Key identifying SignatureDef containing inputs and outputs. (default tf.saved_model.DEFAULT_SERVING_SIGNATURE_DEF_KEY) Returns: TFLiteConverter class. """ # pylint: disable=protected-access TFLiteConverterBase._set_original_model_type( conversion_metadata_fb.ModelType.TF_SAVED_MODEL ) # pylint: enable=protected-access if tag_set is None: tag_set = set([_tag_constants.SERVING]) if signature_key is None: signature_key = _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY saved_model_converter = TFLiteSavedModelConverter( saved_model_dir, tag_set, [signature_key] ) if saved_model_converter.saved_model_dir: return saved_model_converter result = _freeze_saved_model( saved_model_dir, input_arrays, input_shapes, output_arrays, tag_set, signature_key, ) return cls( graph_def=result[0], input_tensors=result[1], output_tensors=result[2], experimental_debug_info_func=_build_debug_info_func(result[3]), ) @classmethod def from_keras_model_file( cls, model_file, input_arrays=None, input_shapes=None, output_arrays=None, custom_objects=None, ): """Creates a TFLiteConverter class from a tf.keras model file. Args: model_file: Full filepath of HDF5 file containing the tf.keras model. input_arrays: List of input tensors to freeze graph with. Uses input arrays from SignatureDef when none are provided. (default None) input_shapes: Dict of strings representing input tensor names to list of integers representing input shapes (e.g., {"foo" : [1, 16, 16, 3]}). Automatically determined when input shapes is None (e.g., {"foo" : None}). (default None) output_arrays: List of output tensors to freeze graph with. Uses output arrays from SignatureDef when none are provided. (default None) custom_objects: Dict mapping names (strings) to custom classes or functions to be considered during model deserialization. (default None) Returns: TFLiteConverter class. """ # pylint: disable=protected-access TFLiteConverterBase._set_original_model_type( conversion_metadata_fb.ModelType.KERAS_MODEL ) # pylint: enable=protected-access return TFLiteKerasModelConverter( model_file, input_arrays, input_shapes, output_arrays, custom_objects ) # pylint: disable=useless-super-delegation def convert(self): """Converts a TensorFlow GraphDef based on instance variables. Returns: The converted data in serialized format, either a TFLite Flatbuffer or a Graphviz graph depending on value in `output_format`. Raises: ValueError: Input shape is not specified. None value for dimension in input_tensor. """ return super(TFLiteConverter, self).convert() @_tf_export(v1=["lite.TocoConverter"])
TFLiteConverter
python
davidhalter__jedi
test/completion/usages.py
{ "start": 2826, "end": 3101 }
class ____(object): #< 4 (0,4), (5,13), (7,21) class_v = 1 def a(self): class_v = 1 #< (-5,4), (0,13), (2,21) self.class_v #< (-7,4), (-2,13), (0,21) TestClassVar.class_v #< (0,8), (-7, 8) class_v
TestClassVar
python
bokeh__bokeh
src/bokeh/events.py
{ "start": 10535, "end": 10911 }
class ____(ModelEvent): ''' The base class for all events applicable to Plot models. ''' def __init__(self, model: Plot | None) -> None: from .models import Plot if model is not None and not isinstance(model, Plot): raise ValueError(f"{self.__class__.__name__} event only applies to Plot models") super().__init__(model)
PlotEvent
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 240405, "end": 242153 }
class ____(Response): """ Response of tasks.enqueue_many endpoint. :param enqueued: Number of tasks enqueued :type enqueued: int """ _service = "tasks" _action = "enqueue_many" _version = "2.13" _schema = { "definitions": {}, "failures": { "item": { "error": { "description": "Error info", "properties": { "codes": {"item": {"type": "integer"}, "type": "array"}, "data": {"additionalProperties": True, "type": "object"}, "msg": {"type": "string"}, }, "type": "object", }, "id": {"description": "ID of the failed entity", "type": "string"}, "type": "object", }, "type": "array", }, "properties": { "enqueued": { "description": "Number of tasks enqueued", "type": ["integer", "null"], } }, } def __init__(self, enqueued: Optional[int] = None, **kwargs: Any) -> None: super(EnqueueManyResponse, self).__init__(**kwargs) self.enqueued = enqueued @schema_property("enqueued") def enqueued(self) -> Optional[int]: return self._property_enqueued @enqueued.setter def enqueued(self, value: Optional[int]) -> None: if value is None: self._property_enqueued = None return if isinstance(value, float) and value.is_integer(): value = int(value) self.assert_isinstance(value, "enqueued", six.integer_types) self._property_enqueued = value
EnqueueManyResponse
python
crytic__slither
slither/slithir/operations/internal_call.py
{ "start": 664, "end": 3549 }
class ____(Call, OperationWithLValue): # pylint: disable=too-many-instance-attributes def __init__( self, function: Union[Function, Tuple[str, str]], nbr_arguments: int, result: Optional[ Union[TupleVariableSSA, TemporaryVariableSSA, TupleVariable, TemporaryVariable] ], type_call: str, names: Optional[List[str]] = None, ) -> None: # pylint: disable=too-many-arguments """ #### Parameters names - For calls of the form f({argName1 : arg1, ...}), the names of parameters listed in call order. Otherwise, None. """ super().__init__(names=names) self._contract_name = "" if isinstance(function, Function): self._function: Optional[Function] = function self._function_name = function.name if isinstance(function, FunctionContract): self._contract_name = function.contract_declarer.name else: self._function = None self._function_name, self._contract_name = function # self._contract = contract self._nbr_arguments = nbr_arguments self._type_call = type_call self._lvalue = result # function_candidates is only used as an helper to retrieve the "function" object # For top level function called through a import renamed # See SolidityImportPlaceHolder usages self.function_candidates: Optional[List[Function]] = None @property def read(self) -> List[Any]: return list(self._unroll(self.arguments)) @property def function(self) -> Optional[Function]: return self._function @function.setter def function(self, f): self._function = f @property def function_name(self) -> Constant: return self._function_name @property def contract_name(self) -> str: return self._contract_name @property def nbr_arguments(self) -> int: return self._nbr_arguments @property def type_call(self) -> str: return self._type_call @property def is_modifier_call(self): """ Check if the destination is a modifier :return: bool """ return isinstance(self.function, Modifier) def __str__(self): args = [str(a) for a in self.arguments] if not self.lvalue: lvalue = "" elif isinstance(self.lvalue.type, (list,)): lvalue = f"{self.lvalue}({','.join(str(x) for x in self.lvalue.type)}) = " else: lvalue = f"{self.lvalue}({self.lvalue.type}) = " if self.is_modifier_call: txt = "{}MODIFIER_CALL, {}({})" else: txt = "{}INTERNAL_CALL, {}({})" return txt.format(lvalue, self.function.canonical_name, ",".join(args))
InternalCall
python
zarr-developers__zarr-python
src/zarr/core/_info.py
{ "start": 2034, "end": 5015 }
class ____: """ Visual summary for an Array. Note that this method and its properties is not part of Zarr's public API. """ _type: Literal["Array"] = "Array" _zarr_format: ZarrFormat _data_type: ZDType[TBaseDType, TBaseScalar] _fill_value: object _shape: tuple[int, ...] _shard_shape: tuple[int, ...] | None = None _chunk_shape: tuple[int, ...] | None = None _order: Literal["C", "F"] _read_only: bool _store_type: str _filters: tuple[Numcodec, ...] | tuple[ArrayArrayCodec, ...] = () _serializer: ArrayBytesCodec | None = None _compressors: tuple[Numcodec, ...] | tuple[BytesBytesCodec, ...] = () _count_bytes: int | None = None _count_bytes_stored: int | None = None _count_chunks_initialized: int | None = None def __repr__(self) -> str: template = textwrap.dedent("""\ Type : {_type} Zarr format : {_zarr_format} Data type : {_data_type} Fill value : {_fill_value} Shape : {_shape}""") if self._shard_shape is not None: template += textwrap.dedent(""" Shard shape : {_shard_shape}""") template += textwrap.dedent(""" Chunk shape : {_chunk_shape} Order : {_order} Read-only : {_read_only} Store type : {_store_type}""") # We can't use dataclasses.asdict, because we only want a shallow dict kwargs = {field.name: getattr(self, field.name) for field in dataclasses.fields(self)} if self._chunk_shape is None: # for non-regular chunk grids kwargs["chunk_shape"] = "<variable>" template += "\nFilters : {_filters}" if self._serializer is not None: template += "\nSerializer : {_serializer}" template += "\nCompressors : {_compressors}" if self._count_bytes is not None: template += "\nNo. bytes : {_count_bytes}" kwargs["_count_bytes"] = byte_info(self._count_bytes) if self._count_bytes_stored is not None: template += "\nNo. bytes stored : {_count_bytes_stored}" kwargs["_count_bytes_stored"] = byte_info(self._count_bytes_stored) if ( self._count_bytes is not None and self._count_bytes_stored is not None and self._count_bytes_stored > 0 ): template += "\nStorage ratio : {_storage_ratio}" kwargs["_storage_ratio"] = f"{self._count_bytes / self._count_bytes_stored:.1f}" if self._count_chunks_initialized is not None: if self._shard_shape is not None: template += "\nShards Initialized : {_count_chunks_initialized}" else: template += "\nChunks Initialized : {_count_chunks_initialized}" return template.format(**kwargs)
ArrayInfo
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1042823, "end": 1043237 }
class ____(sgqlc.types.Type): """Autogenerated return type of UpdateRef""" __schema__ = github_schema __field_names__ = ("client_mutation_id", "ref") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation.""" ref = sgqlc.types.Field("Ref", graphql_name="ref") """The updated Ref."""
UpdateRefPayload
python
django__django
django/contrib/postgres/indexes.py
{ "start": 280, "end": 1326 }
class ____(CheckPostgresInstalledMixin, Index): @cached_property def max_name_length(self): # Allow an index name longer than 30 characters when the suffix is # longer than the usual 3 character limit. The 30 character limit for # cross-database compatibility isn't applicable to PostgreSQL-specific # indexes. return Index.max_name_length - len(Index.suffix) + len(self.suffix) def create_sql(self, model, schema_editor, using="", **kwargs): self.check_supported(schema_editor) statement = super().create_sql( model, schema_editor, using=" USING %s" % (using or self.suffix), **kwargs ) with_params = self.get_with_params() if with_params: statement.parts["extra"] = " WITH (%s)%s" % ( ", ".join(with_params), statement.parts["extra"], ) return statement def check_supported(self, schema_editor): pass def get_with_params(self): return []
PostgresIndex
python
numpy__numpy
numpy/distutils/system_info.py
{ "start": 23214, "end": 23403 }
class ____(NotFoundError): """ 64-bit Blas libraries not found. Known libraries in numpy/distutils/site.cfg file are: openblas64_, openblas_ilp64 """
BlasILP64NotFoundError
python
pennersr__django-allauth
allauth/socialaccount/providers/authentiq/provider.py
{ "start": 1187, "end": 3061 }
class ____(OAuth2Provider): id = "authentiq" name = "Authentiq" account_class = AuthentiqAccount oauth2_adapter_class = AuthentiqOAuth2Adapter def get_scope_from_request(self, request): scope = set(super().get_scope_from_request(request)) scope.add("openid") if Scope.EMAIL in scope: modifiers = "" if app_settings.EMAIL_REQUIRED: modifiers += "r" if app_settings.EMAIL_VERIFICATION: modifiers += "s" if modifiers: scope.add(Scope.EMAIL + "~" + modifiers) scope.remove(Scope.EMAIL) return list(scope) def get_default_scope(self): scope = [Scope.NAME, Scope.PUSH] if app_settings.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" return ret def extract_uid(self, data): return str(data["sub"]) def extract_common_fields(self, data): return dict( username=data.get("preferred_username", data.get("given_name")), email=data.get("email"), name=data.get("name"), first_name=data.get("given_name"), last_name=data.get("family_name"), ) def extract_extra_data(self, data): return {k: v for k, v in data.items() if k in IDENTITY_CLAIMS} def extract_email_addresses(self, data): ret = [] email = data.get("email") if email and data.get("email_verified"): ret.append(EmailAddress(email=email, verified=True, primary=True)) return ret provider_classes = [AuthentiqProvider]
AuthentiqProvider
python
sqlalchemy__sqlalchemy
test/orm/test_query.py
{ "start": 160433, "end": 169498 }
class ____( QueryTest, AssertsCompiledSQL, fixtures.DistinctOnFixture ): """a test suite that is obstensibly specific to the PostgreSQL-only DISTINCT ON clause, however is actually testing a few things: 1. the legacy query.distinct() feature's handling of this directly 2. PostgreSQL's distinct_on() extension 3. the ability for Query to use statement extensions in general 4. ORM compilation of statement extensions, with or without adaptations items 3 and 4 are universal to all statement extensions, with the PG distinct_on() extension serving as the test case. """ __dialect__ = "default" @testing.fixture def distinct_on_transform(self, distinct_on_fixture): def go(expr): def transform(query): return distinct_on_fixture(query, expr) return transform return go def test_distinct_on_definitely_adapted(self, distinct_on_transform): """there are few cases where a query-wide adapter is used on per-column expressions in SQLAlchemy 2 and greater. however the legacy query.union() case still relies on such an adapter, so make use of this codepath to exercise column adaptation for edge features such as "distinct_on" """ User, Address = self.classes.User, self.classes.Address sess = fixture_session() q = sess.query( User.id, User.name.label("foo"), Address.email_address, ).order_by(User.id, User.name) q2 = sess.query(User.id, User.name.label("foo"), Address.email_address) q3 = q.union(q2).with_transformation( distinct_on_transform(Address.email_address) ) self.assert_compile( q3, "SELECT DISTINCT ON (anon_1.addresses_email_address) " "anon_1.users_id AS anon_1_users_id, anon_1.foo AS anon_1_foo, " "anon_1.addresses_email_address AS anon_1_addresses_email_address " "FROM ((SELECT users.id AS users_id, users.name AS foo, " "addresses.email_address AS addresses_email_address FROM users, " "addresses ORDER BY users.id, users.name) " "UNION SELECT users.id AS users_id, users.name AS foo, " "addresses.email_address AS addresses_email_address " "FROM users, addresses) AS anon_1", dialect="postgresql", ) def test_columns_augmented_sql_union_two(self, distinct_on_transform): User, Address = self.classes.User, self.classes.Address sess = fixture_session() q = ( sess.query( User.id, User.name.label("foo"), Address.id, ) .with_transformation(distinct_on_transform(Address.email_address)) .order_by(User.id, User.name) ) q2 = sess.query(User.id, User.name.label("foo"), Address.id) self.assert_compile( q.union(q2), "SELECT anon_1.users_id AS anon_1_users_id, " "anon_1.foo AS anon_1_foo, anon_1.addresses_id AS " "anon_1_addresses_id FROM " "((SELECT DISTINCT ON (addresses.email_address) users.id " "AS users_id, users.name AS foo, " "addresses.id AS addresses_id FROM users, addresses " "ORDER BY users.id, users.name) " "UNION SELECT users.id AS users_id, users.name AS foo, " "addresses.id AS addresses_id FROM users, addresses) AS anon_1", dialect="postgresql", ) def test_columns_augmented_three(self, distinct_on_transform): User, Address = self.classes.User, self.classes.Address sess = fixture_session() q = ( sess.query(User.id, User.name.label("foo"), Address.id) .with_transformation(distinct_on_transform(User.name)) .order_by(User.id, User.name, Address.email_address) ) # no columns are added when DISTINCT ON is used self.assert_compile( q, "SELECT DISTINCT ON (users.name) users.id AS users_id, " "users.name AS foo, addresses.id AS addresses_id FROM users, " "addresses ORDER BY users.id, users.name, addresses.email_address", dialect="postgresql", ) def test_columns_augmented_four(self, distinct_on_transform): User, Address = self.classes.User, self.classes.Address sess = fixture_session() subq = ( sess.query( User.id, User.name.label("foo"), Address.id, Address.email_address, ) .with_transformation(distinct_on_transform(Address.email_address)) .order_by(User.id, User.name, Address.email_address) .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) .subquery() ) ua = aliased(User, subq) aa = aliased(Address, subq) q = sess.query(ua.id, ua.name.label("foo"), aa.id) # Address.email_address is added because of DISTINCT, # however User.id, User.name are not b.c. they're already there, # even though User.name is labeled self.assert_compile( q, "SELECT anon_1.users_id AS anon_1_users_id, anon_1.foo AS foo, " "anon_1.addresses_id AS anon_1_addresses_id " "FROM (" "SELECT DISTINCT ON (addresses.email_address) " "users.id AS users_id, users.name AS foo, " "addresses.id AS addresses_id, addresses.email_address AS " "addresses_email_address FROM users, addresses ORDER BY " "users.id, users.name, addresses.email_address" ") AS anon_1", dialect="postgresql", ) def test_legacy_columns_augmented_sql_three_using_label_reference(self): User, Address = self.classes.User, self.classes.Address sess = fixture_session() with expect_deprecated("Passing expression to"): q = ( sess.query(User.id, User.name.label("foo"), Address.id) .distinct("name") .order_by(User.id, User.name, Address.email_address) ) # no columns are added when DISTINCT ON is used self.assert_compile( q, "SELECT DISTINCT ON (users.name) users.id AS users_id, " "users.name AS foo, addresses.id AS addresses_id FROM users, " "addresses ORDER BY users.id, users.name, addresses.email_address", dialect="postgresql", ) def test_legacy_columns_augmented_sql_illegal_label_reference(self): User, Address = self.classes.User, self.classes.Address sess = fixture_session() with expect_deprecated("Passing expression to"): q = sess.query( User.id, User.name.label("foo"), Address.id ).distinct("not a label") from sqlalchemy.dialects import postgresql assert_raises_message( sa_exc.CompileError, "Can't resolve label reference for ORDER BY / " "GROUP BY / DISTINCT etc.", q.set_label_style( LABEL_STYLE_TABLENAME_PLUS_COL ).statement.compile, dialect=postgresql.dialect(), ) def test_columns_augmented_sql_four(self, distinct_on_transform): User, Address = self.classes.User, self.classes.Address sess = fixture_session() q = ( sess.query(User) .join(User.addresses) .with_transformation(distinct_on_transform(Address.email_address)) .options(joinedload(User.addresses)) .order_by(desc(Address.email_address)) .limit(2) ) # but for the subquery / eager load case, we still need to make # the inner columns available for the ORDER BY even though its # a DISTINCT ON self.assert_compile( q, "SELECT anon_1.users_id AS anon_1_users_id, " "anon_1.users_name AS anon_1_users_name, " "anon_1.addresses_email_address AS " "anon_1_addresses_email_address, " "addresses_1.id AS addresses_1_id, " "addresses_1.user_id AS addresses_1_user_id, " "addresses_1.email_address AS addresses_1_email_address " "FROM (SELECT DISTINCT ON (addresses.email_address) " "users.id AS users_id, users.name AS users_name, " "addresses.email_address AS addresses_email_address " "FROM users JOIN addresses ON users.id = addresses.user_id " "ORDER BY addresses.email_address DESC " "LIMIT %(param_1)s) AS anon_1 " "LEFT OUTER JOIN addresses AS addresses_1 " "ON anon_1.users_id = addresses_1.user_id " "ORDER BY anon_1.addresses_email_address DESC, addresses_1.id", dialect="postgresql", )
DistinctOnTest
python
PrefectHQ__prefect
src/prefect/client/schemas/objects.py
{ "start": 33631, "end": 35470 }
class ____(ObjectBaseModel): """An ORM representation of a block document.""" name: Optional[BlockDocumentName] = Field( default=None, description=( "The block document's name. Not required for anonymous block documents." ), ) data: dict[str, Any] = Field( default_factory=dict, description="The block document's data" ) block_schema_id: UUID = Field(default=..., description="A block schema ID") block_schema: Optional[BlockSchema] = Field( default=None, description="The associated block schema" ) block_type_id: UUID = Field(default=..., description="A block type ID") block_type_name: Optional[str] = Field(None, description="A block type name") block_type: Optional[BlockType] = Field( default=None, description="The associated block type" ) block_document_references: dict[str, dict[str, Any]] = Field( default_factory=dict, description="Record of the block document's references" ) is_anonymous: bool = Field( default=False, description=( "Whether the block is anonymous (anonymous blocks are usually created by" " Prefect automatically)" ), ) @model_validator(mode="before") @classmethod def validate_name_is_present_if_not_anonymous( cls, values: dict[str, Any] ) -> dict[str, Any]: return validate_name_present_on_nonanonymous_blocks(values) @model_serializer(mode="wrap") def serialize_data( self, handler: SerializerFunctionWrapHandler, info: SerializationInfo ) -> Any: self.data = visit_collection( self.data, visit_fn=partial(handle_secret_render, context=info.context or {}), return_data=True, ) return handler(self)
BlockDocument
python
redis__redis-py
redis/commands/search/aggregation.py
{ "start": 417, "end": 1690 }
class ____: """ Base reducer object for all reducers. See the `redisearch.reducers` module for the actual reducers. """ NAME = None def __init__(self, *args: str) -> None: self._args: Tuple[str, ...] = args self._field: Optional[str] = None self._alias: Optional[str] = None def alias(self, alias: str) -> "Reducer": """ Set the alias for this reducer. ### Parameters - **alias**: The value of the alias for this reducer. If this is the special value `aggregation.FIELDNAME` then this reducer will be aliased using the same name as the field upon which it operates. Note that using `FIELDNAME` is only possible on reducers which operate on a single field value. This method returns the `Reducer` object making it suitable for chaining. """ if alias is FIELDNAME: if not self._field: raise ValueError("Cannot use FIELDNAME alias with no field") else: # Chop off initial '@' alias = self._field[1:] self._alias = alias return self @property def args(self) -> Tuple[str, ...]: return self._args
Reducer
python
getsentry__sentry
tests/sentry/issues/endpoints/test_organization_shortid.py
{ "start": 163, "end": 1713 }
class ____(APITestCase): def setUp(self) -> None: self.group = self.create_group(project=self.project, short_id=self.project.next_short_id()) self.url = reverse( "sentry-api-0-short-id-lookup", kwargs={ "organization_id_or_slug": self.organization.slug, "issue_id": self.group.qualified_short_id, }, ) def test_simple(self) -> None: self.login_as(user=self.user) response = self.client.get(self.url, format="json") assert response.status_code == 200, response.content assert response.data["organizationSlug"] == self.organization.slug assert response.data["projectSlug"] == self.project.slug assert response.data["groupId"] == str(self.group.id) assert response.data["group"]["id"] == str(self.group.id) def test_access_non_member_project(self) -> None: # disable Open Membership self.organization.flags.allow_joinleave = False self.organization.save() # user has no access to the first project user_no_team = self.create_user(is_superuser=False) self.create_member( user=user_no_team, organization=self.organization, role="member", teams=[] ) self.login_as(user_no_team) response = self.client.get(self.url, format="json") assert response.status_code == 403, response.content assert response.data["detail"] == "You do not have permission to perform this action."
ShortIdLookupEndpointTest
python
sqlalchemy__sqlalchemy
test/dialect/oracle/test_dialect.py
{ "start": 29542, "end": 30562 }
class ____(fixtures.TestBase): __only_on__ = "oracle" __backend__ = True def test_quoted_column_non_unicode(self, metadata, connection): table = Table( "atable", metadata, Column("_underscorecolumn", Unicode(255), primary_key=True), ) metadata.create_all(connection) connection.execute(table.insert(), {"_underscorecolumn": "’é"}) result = connection.execute( table.select().where(table.c._underscorecolumn == "’é") ).scalar() eq_(result, "’é") def test_quoted_column_unicode(self, metadata, connection): table = Table( "atable", metadata, Column("méil", Unicode(255), primary_key=True), ) metadata.create_all(connection) connection.execute(table.insert(), {"méil": "’é"}) result = connection.execute( table.select().where(table.c["méil"] == "’é") ).scalar() eq_(result, "’é")
UnicodeSchemaTest
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/trigger_external_non_default_variant/package.py
{ "start": 216, "end": 524 }
class ____(Package): """This ackage depends on an external with a non-default variant""" homepage = "http://www.example.com" url = "http://www.someurl.tar.gz" version("1.0", md5="0123456789abcdef0123456789abcdef") depends_on("external-non-default-variant")
TriggerExternalNonDefaultVariant
python
ray-project__ray
python/ray/actor.py
{ "start": 2710, "end": 2970 }
class ____(Generic[_Ret, _T0, _T1]): def remote( self, __arg0: "Union[_T0, ObjectRef[_T0]]", __arg1: "Union[_T1, ObjectRef[_T1]]" ) -> "ObjectRef[_Ret]": ... def bind(self, __arg0: _T0, __arg1: _T1) -> Any: ...
_RemoteMethod1
python
django__django
tests/file_storage/models.py
{ "start": 990, "end": 2903 }
class ____(models.Model): def custom_upload_to(self, filename): return "foo" def random_upload_to(self, filename): # This returns a different result each time, # to make sure it only gets called once. return "%s/%s" % (random.randint(100, 999), filename) def pathlib_upload_to(self, filename): return Path("bar") / filename normal = models.FileField(storage=temp_storage, upload_to="tests") custom = models.FileField(storage=temp_storage, upload_to=custom_upload_to) pathlib_callable = models.FileField( storage=temp_storage, upload_to=pathlib_upload_to ) pathlib_direct = models.FileField(storage=temp_storage, upload_to=Path("bar")) random = models.FileField(storage=temp_storage, upload_to=random_upload_to) custom_valid_name = models.FileField( storage=CustomValidNameStorage(location=temp_storage_location), upload_to=random_upload_to, ) storage_callable = models.FileField( storage=callable_storage, upload_to="storage_callable" ) storage_callable_class = models.FileField( storage=CallableStorage, upload_to="storage_callable_class" ) storage_callable_default = models.FileField( storage=callable_default_storage, upload_to="storage_callable_default" ) default = models.FileField( storage=temp_storage, upload_to="tests", default="tests/default.txt" ) db_default = models.FileField( storage=temp_storage, upload_to="tests", db_default="tests/db_default.txt" ) empty = models.FileField(storage=temp_storage) limited_length = models.FileField( storage=temp_storage, upload_to="tests", max_length=20 ) extended_length = models.FileField( storage=temp_storage, upload_to="tests", max_length=1024 ) lazy_storage = models.FileField(storage=LazyTempStorage(), upload_to="tests")
Storage
python
spyder-ide__spyder
spyder/plugins/variableexplorer/widgets/dataframeeditor.py
{ "start": 4791, "end": 4947 }
class ____: Edit = 'edit_section' Row = 'row_section' Column = 'column_section' Convert = 'convert_section'
DataframeEditorContextMenuSections
python
pytorch__pytorch
torch/_export/db/examples/dynamic_shape_constructor.py
{ "start": 41, "end": 396 }
class ____(torch.nn.Module): """ Tensor constructors should be captured with dynamic shape inputs rather than being baked in with static shape. """ def forward(self, x): return torch.zeros(x.shape[0] * 2) example_args = (torch.randn(3, 2),) tags = {"torch.dynamic-shape"} model = DynamicShapeConstructor()
DynamicShapeConstructor
python
keras-team__keras
keras/src/ops/nn.py
{ "start": 9191, "end": 10017 }
class ____(Operation): def call(self, x): return backend.nn.log_sigmoid(x) def compute_output_spec(self, x): return KerasTensor(x.shape, dtype=x.dtype) @keras_export( [ "keras.ops.log_sigmoid", "keras.ops.nn.log_sigmoid", ] ) def log_sigmoid(x): """Logarithm of the sigmoid activation function. It is defined as `f(x) = log(1 / (1 + exp(-x)))`. Args: x: Input tensor. Returns: A tensor with the same shape as `x`. Example: >>> x = keras.ops.convert_to_tensor([-0.541391, 0.0, 0.50, 5.0]) >>> keras.ops.log_sigmoid(x) array([-1.0000418, -0.6931472, -0.474077, -0.00671535], dtype=float32) """ if any_symbolic_tensors((x,)): return LogSigmoid().symbolic_call(x) return backend.nn.log_sigmoid(x)
LogSigmoid
python
pypa__installer
tests/test_destinations.py
{ "start": 254, "end": 959 }
class ____: def test_takes_no_arguments(self): WheelDestination() def test_raises_not_implemented_error(self): destination = WheelDestination() with pytest.raises(NotImplementedError): destination.write_script(name=None, module=None, attr=None, section=None) with pytest.raises(NotImplementedError): destination.write_file( scheme=None, path=None, stream=None, is_executable=False ) with pytest.raises(NotImplementedError): destination.finalize_installation( scheme=None, record_file_path=None, records=None, )
TestWheelDestination
python
Pylons__pyramid
tests/test_renderers.py
{ "start": 24040, "end": 26063 }
class ____(unittest.TestCase): def _makeOne(self, param_name='callback'): from pyramid.renderers import JSONP return JSONP(param_name) def test_render_to_jsonp(self): renderer_factory = self._makeOne() renderer = renderer_factory(None) request = testing.DummyRequest() request.GET['callback'] = 'callback' result = renderer({'a': '1'}, {'request': request}) self.assertEqual(result, '/**/callback({"a": "1"});') self.assertEqual( request.response.content_type, 'application/javascript' ) def test_render_to_jsonp_with_dot(self): renderer_factory = self._makeOne() renderer = renderer_factory(None) request = testing.DummyRequest() request.GET['callback'] = 'angular.callbacks._0' result = renderer({'a': '1'}, {'request': request}) self.assertEqual(result, '/**/angular.callbacks._0({"a": "1"});') self.assertEqual( request.response.content_type, 'application/javascript' ) def test_render_to_json(self): renderer_factory = self._makeOne() renderer = renderer_factory(None) request = testing.DummyRequest() result = renderer({'a': '1'}, {'request': request}) self.assertEqual(result, '{"a": "1"}') self.assertEqual(request.response.content_type, 'application/json') def test_render_without_request(self): renderer_factory = self._makeOne() renderer = renderer_factory(None) result = renderer({'a': '1'}, {}) self.assertEqual(result, '{"a": "1"}') def test_render_to_jsonp_invalid_callback(self): from pyramid.httpexceptions import HTTPBadRequest renderer_factory = self._makeOne() renderer = renderer_factory(None) request = testing.DummyRequest() request.GET['callback'] = '78mycallback' self.assertRaises( HTTPBadRequest, renderer, {'a': '1'}, {'request': request} )
TestJSONP
python
huggingface__transformers
tests/models/blip/test_modeling_blip.py
{ "start": 18977, "end": 21075 }
class ____: def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True): if text_kwargs is None: text_kwargs = {} if vision_kwargs is None: vision_kwargs = {} self.parent = parent self.text_model_tester = BlipTextModelTester(parent, **text_kwargs) self.vision_model_tester = BlipVisionModelTester(parent, **vision_kwargs) self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test self.is_training = is_training def prepare_config_and_inputs(self): text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs() vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs() config = self.get_config() return config, input_ids, attention_mask, pixel_values def get_config(self): return BlipConfig( text_config=self.text_model_tester.get_config().to_dict(), vision_config=self.vision_model_tester.get_config().to_dict(), projection_dim=64, ) def create_and_check_model(self, config, input_ids, attention_mask, pixel_values): model = BlipModel(config).to(torch_device).eval() with torch.no_grad(): result = model(input_ids, pixel_values, attention_mask) self.parent.assertEqual( result.logits_per_image.shape, (self.vision_model_tester.batch_size, self.text_model_tester.batch_size) ) self.parent.assertEqual( result.logits_per_text.shape, (self.text_model_tester.batch_size, self.vision_model_tester.batch_size) ) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, input_ids, attention_mask, pixel_values = config_and_inputs inputs_dict = { "input_ids": input_ids, "attention_mask": attention_mask, "pixel_values": pixel_values, } return config, inputs_dict
BlipTextRetrievalModelTester
python
sqlalchemy__sqlalchemy
test/sql/test_type_expressions.py
{ "start": 3560, "end": 12143 }
class ____(_ExprFixture, fixtures.TestBase, AssertsCompiledSQL): __dialect__ = "default" def test_select_cols(self): table = self._fixture() self.assert_compile( select(table), "SELECT test_table.x, lower(test_table.y) AS y FROM test_table", ) def test_anonymous_expr(self): table = self._fixture() self.assert_compile( select(cast(table.c.y, String)), "SELECT CAST(test_table.y AS VARCHAR) AS y FROM test_table", ) def test_select_cols_use_labels(self): table = self._fixture() self.assert_compile( select(table).set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL), "SELECT test_table.x AS test_table_x, " "lower(test_table.y) AS test_table_y FROM test_table", ) def test_select_cols_use_labels_result_map_targeting(self): table = self._fixture() compiled = ( select(table) .set_label_style(LABEL_STYLE_TABLENAME_PLUS_COL) .compile() ) assert table.c.y in compiled._create_result_map()["test_table_y"][1] assert table.c.x in compiled._create_result_map()["test_table_x"][1] # the lower() function goes into the result_map, we don't really # need this but it's fine self.assert_compile( compiled._create_result_map()["test_table_y"][1][3], "lower(test_table.y)", ) # then the original column gets put in there as well. # as of 1.1 it's important that it is first as this is # taken as significant by the result processor. self.assert_compile( compiled._create_result_map()["test_table_y"][1][0], "test_table.y" ) def test_insert_binds(self): table = self._fixture() self.assert_compile( table.insert(), "INSERT INTO test_table (x, y) VALUES (:x, lower(:y))", ) self.assert_compile( table.insert().values(y="hi"), "INSERT INTO test_table (y) VALUES (lower(:y))", ) def test_select_binds(self): table = self._fixture() self.assert_compile( select(table).where(table.c.y == "hi"), "SELECT test_table.x, lower(test_table.y) AS y FROM " "test_table WHERE test_table.y = lower(:y_1)", ) @testing.variation( "compile_opt", ["plain", "postcompile", "literal_binds"] ) def test_in_binds(self, compile_opt): table = self._fixture() stmt = select(table).where( table.c.y.in_(["hi", "there", "some", "expr"]) ) if compile_opt.plain: self.assert_compile( stmt, "SELECT test_table.x, lower(test_table.y) AS y FROM " "test_table WHERE test_table.y IN " "(__[POSTCOMPILE_y_1~~lower(~~REPL~~)~~])", render_postcompile=False, ) elif compile_opt.postcompile: self.assert_compile( stmt, "SELECT test_table.x, lower(test_table.y) AS y FROM " "test_table WHERE test_table.y IN " "(lower(:y_1_1), lower(:y_1_2), lower(:y_1_3), lower(:y_1_4))", render_postcompile=True, ) elif compile_opt.literal_binds: self.assert_compile( stmt, "SELECT test_table.x, lower(test_table.y) AS y FROM " "test_table WHERE test_table.y IN " "(lower('hi'), lower('there'), lower('some'), lower('expr'))", literal_binds=True, ) def test_dialect(self): table = self._fixture() dialect = self._dialect_level_fixture() # 'x' is straight String self.assert_compile( select(table.c.x).where(table.c.x == "hi"), "SELECT dialect_colexpr(test_table.x) AS x " "FROM test_table WHERE test_table.x = dialect_bind(:x_1)", dialect=dialect, ) def test_type_decorator_inner(self): table = self._type_decorator_inside_fixture() self.assert_compile( select(table).where(table.c.y == "hi"), "SELECT test_table.x, inside_colexpr(test_table.y) AS y " "FROM test_table WHERE test_table.y = inside_bind(:y_1)", ) def test_type_decorator_inner_plus_dialect(self): table = self._type_decorator_inside_fixture() dialect = self._dialect_level_fixture() # for "inner", the MyStringImpl is a subclass of String, # # so a dialect-level # implementation supersedes that, which is the same as with other # processor functions self.assert_compile( select(table).where(table.c.y == "hi"), "SELECT dialect_colexpr(test_table.x) AS x, " "dialect_colexpr(test_table.y) AS y FROM test_table " "WHERE test_table.y = dialect_bind(:y_1)", dialect=dialect, ) def test_type_decorator_outer(self): table = self._type_decorator_outside_fixture() self.assert_compile( select(table).where(table.c.y == "hi"), "SELECT test_table.x, outside_colexpr(test_table.y) AS y " "FROM test_table WHERE test_table.y = outside_bind(:y_1)", ) def test_type_decorator_outer_plus_dialect(self): table = self._type_decorator_outside_fixture() dialect = self._dialect_level_fixture() # for "outer", the MyString isn't calling the "impl" functions, # so we don't get the "impl" self.assert_compile( select(table).where(table.c.y == "hi"), "SELECT dialect_colexpr(test_table.x) AS x, " "outside_colexpr(test_table.y) AS y " "FROM test_table WHERE test_table.y = outside_bind(:y_1)", dialect=dialect, ) def test_type_decorator_both(self): table = self._type_decorator_both_fixture() self.assert_compile( select(table).where(table.c.y == "hi"), "SELECT test_table.x, " "outside_colexpr(inside_colexpr(test_table.y)) AS y " "FROM test_table WHERE " "test_table.y = outside_bind(inside_bind(:y_1))", ) def test_type_decorator_both_plus_dialect(self): table = self._type_decorator_both_fixture() dialect = self._dialect_level_fixture() # for "inner", the MyStringImpl is a subclass of String, # so a dialect-level # implementation supersedes that, which is the same as with other # processor functions self.assert_compile( select(table).where(table.c.y == "hi"), "SELECT dialect_colexpr(test_table.x) AS x, " "outside_colexpr(dialect_colexpr(test_table.y)) AS y " "FROM test_table WHERE " "test_table.y = outside_bind(dialect_bind(:y_1))", dialect=dialect, ) def test_type_decorator_both_w_variant(self): table = self._variant_fixture(self._type_decorator_both_fixture()) self.assert_compile( select(table).where(table.c.y == "hi"), "SELECT test_table.x, " "outside_colexpr(inside_colexpr(test_table.y)) AS y " "FROM test_table WHERE " "test_table.y = outside_bind(inside_bind(:y_1))", ) def test_compound_select(self): table = self._fixture() s1 = select(table).where(table.c.y == "hi") s2 = select(table).where(table.c.y == "there") self.assert_compile( union(s1, s2), "SELECT test_table.x, lower(test_table.y) AS y " "FROM test_table WHERE test_table.y = lower(:y_1) " "UNION SELECT test_table.x, lower(test_table.y) AS y " "FROM test_table WHERE test_table.y = lower(:y_2)", ) def test_select_of_compound_select(self): table = self._fixture() s1 = select(table).where(table.c.y == "hi") s2 = select(table).where(table.c.y == "there") self.assert_compile( union(s1, s2).alias().select(), "SELECT anon_1.x, lower(anon_1.y) AS y FROM " "(SELECT test_table.x AS x, test_table.y AS y " "FROM test_table WHERE test_table.y = lower(:y_1) " "UNION SELECT test_table.x AS x, test_table.y AS y " "FROM test_table WHERE test_table.y = lower(:y_2)) AS anon_1", )
SelectTest
python
kamyu104__LeetCode-Solutions
Python/data-stream-as-disjoint-intervals.py
{ "start": 97, "end": 201 }
class ____(object): def __init__(self, s=0, e=0): self.start = s self.end = e
Interval
python
PyCQA__pylint
pylint/pyreverse/diagrams.py
{ "start": 685, "end": 1113 }
class ____(Figure): """A relationship from an object in the diagram to another.""" def __init__( self, from_object: DiagramEntity, to_object: DiagramEntity, relation_type: str, name: str | None = None, ): super().__init__() self.from_object = from_object self.to_object = to_object self.type = relation_type self.name = name
Relationship
python
getsentry__sentry-python
sentry_sdk/integrations/_wsgi_common.py
{ "start": 1801, "end": 7073 }
class ____: """ Base class for request extraction. """ # It does not make sense to make this class an ABC because it is not used # for typing, only so that child classes can inherit common methods from # it. Only some child classes implement all methods that raise # NotImplementedError in this class. def __init__(self, request): # type: (Any) -> None self.request = request def extract_into_event(self, event): # type: (Event) -> None client = sentry_sdk.get_client() if not client.is_active(): return data = None # type: Optional[Union[AnnotatedValue, Dict[str, Any]]] content_length = self.content_length() request_info = event.get("request", {}) if should_send_default_pii(): request_info["cookies"] = dict(self.cookies()) if not request_body_within_bounds(client, content_length): data = AnnotatedValue.removed_because_over_size_limit() else: # First read the raw body data # It is important to read this first because if it is Django # it will cache the body and then we can read the cached version # again in parsed_body() (or json() or wherever). raw_data = None try: raw_data = self.raw_data() except (RawPostDataException, ValueError): # If DjangoRestFramework is used it already read the body for us # so reading it here will fail. We can ignore this. pass parsed_body = self.parsed_body() if parsed_body is not None: data = parsed_body elif raw_data: data = AnnotatedValue.removed_because_raw_data() else: data = None if data is not None: request_info["data"] = data event["request"] = deepcopy(request_info) def content_length(self): # type: () -> int try: return int(self.env().get("CONTENT_LENGTH", 0)) except ValueError: return 0 def cookies(self): # type: () -> MutableMapping[str, Any] raise NotImplementedError() def raw_data(self): # type: () -> Optional[Union[str, bytes]] raise NotImplementedError() def form(self): # type: () -> Optional[Dict[str, Any]] raise NotImplementedError() def parsed_body(self): # type: () -> Optional[Dict[str, Any]] try: form = self.form() except Exception: form = None try: files = self.files() except Exception: files = None if form or files: data = {} if form: data = dict(form.items()) if files: for key in files.keys(): data[key] = AnnotatedValue.removed_because_raw_data() return data return self.json() def is_json(self): # type: () -> bool return _is_json_content_type(self.env().get("CONTENT_TYPE")) def json(self): # type: () -> Optional[Any] try: if not self.is_json(): return None try: raw_data = self.raw_data() except (RawPostDataException, ValueError): # The body might have already been read, in which case this will # fail raw_data = None if raw_data is None: return None if isinstance(raw_data, str): return json.loads(raw_data) else: return json.loads(raw_data.decode("utf-8")) except ValueError: pass return None def files(self): # type: () -> Optional[Dict[str, Any]] raise NotImplementedError() def size_of_file(self, file): # type: (Any) -> int raise NotImplementedError() def env(self): # type: () -> Dict[str, Any] raise NotImplementedError() def _is_json_content_type(ct): # type: (Optional[str]) -> bool mt = (ct or "").split(";", 1)[0] return ( mt == "application/json" or (mt.startswith("application/")) and mt.endswith("+json") ) def _filter_headers(headers): # type: (Mapping[str, str]) -> Mapping[str, Union[AnnotatedValue, str]] if should_send_default_pii(): return headers return { k: ( v if k.upper().replace("-", "_") not in SENSITIVE_HEADERS else AnnotatedValue.removed_because_over_size_limit() ) for k, v in headers.items() } def _in_http_status_code_range(code, code_ranges): # type: (object, list[HttpStatusCodeRange]) -> bool for target in code_ranges: if isinstance(target, int): if code == target: return True continue try: if code in target: return True except TypeError: logger.warning( "failed_request_status_codes has to be a list of integers or containers" ) return False
RequestExtractor
python
run-llama__llama_index
llama-index-core/llama_index/core/program/function_program.py
{ "start": 1778, "end": 12736 }
class ____(BasePydanticProgram[Model]): """ Function Calling Program. Uses function calling LLMs to obtain a structured output. """ def __init__( self, output_cls: Type[Model], llm: FunctionCallingLLM, prompt: BasePromptTemplate, tool_choice: Optional[Union[str, Dict[str, Any]]] = None, allow_parallel_tool_calls: bool = False, tool_required: bool = True, verbose: bool = False, ) -> None: """Init params.""" self._output_cls = output_cls self._llm = llm self._prompt = prompt self._verbose = verbose self._allow_parallel_tool_calls = allow_parallel_tool_calls self._tool_choice = tool_choice self._tool_required = tool_required @classmethod def from_defaults( cls, output_cls: Type[Model], prompt_template_str: Optional[str] = None, prompt: Optional[BasePromptTemplate] = None, llm: Optional[LLM] = None, verbose: bool = False, allow_parallel_tool_calls: bool = False, tool_choice: Optional[Union[str, Dict[str, Any]]] = None, tool_required: bool = True, **kwargs: Any, ) -> "FunctionCallingProgram": llm = llm or Settings.llm # type: ignore assert llm is not None if not llm.metadata.is_function_calling_model: raise ValueError( f"Model name {llm.metadata.model_name} does not support " "function calling API. " ) if prompt is None and prompt_template_str is None: raise ValueError("Must provide either prompt or prompt_template_str.") if prompt is not None and prompt_template_str is not None: raise ValueError("Must provide either prompt or prompt_template_str.") if prompt_template_str is not None: prompt = PromptTemplate(prompt_template_str) return cls( output_cls=output_cls, llm=llm, # type: ignore prompt=cast(PromptTemplate, prompt), tool_choice=tool_choice, allow_parallel_tool_calls=allow_parallel_tool_calls, tool_required=tool_required, verbose=verbose, ) @property def output_cls(self) -> Type[Model]: return self._output_cls @property def prompt(self) -> BasePromptTemplate: return self._prompt @prompt.setter def prompt(self, prompt: BasePromptTemplate) -> None: self._prompt = prompt def __call__( self, *args: Any, llm_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> Union[Model, List[Model]]: # avoid passing in duplicate kwargs llm_kwargs = llm_kwargs or {} llm_kwargs.pop("tool_required", None) llm_kwargs.pop("tool_choice", None) llm_kwargs.pop("allow_parallel_tool_calls", None) tool = get_function_tool(self._output_cls) messages = self._prompt.format_messages(llm=self._llm, **kwargs) messages = self._llm._extend_messages(messages) agent_response = self._llm.predict_and_call( [tool], chat_history=messages, verbose=self._verbose, allow_parallel_tool_calls=self._allow_parallel_tool_calls, tool_required=self._tool_required, **llm_kwargs, ) return self._parse_tool_outputs( agent_response, allow_parallel_tool_calls=self._allow_parallel_tool_calls, ) async def acall( self, *args: Any, llm_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> Union[Model, List[Model]]: # avoid passing in duplicate kwargs llm_kwargs = llm_kwargs or {} llm_kwargs.pop("tool_required", None) llm_kwargs.pop("tool_choice", None) llm_kwargs.pop("allow_parallel_tool_calls", None) tool = get_function_tool(self._output_cls) agent_response = await self._llm.apredict_and_call( [tool], chat_history=self._prompt.format_messages(llm=self._llm, **kwargs), verbose=self._verbose, allow_parallel_tool_calls=self._allow_parallel_tool_calls, tool_required=self._tool_required, **llm_kwargs, ) return self._parse_tool_outputs( agent_response, allow_parallel_tool_calls=self._allow_parallel_tool_calls, ) def _parse_tool_outputs( self, agent_response: AgentChatResponse, allow_parallel_tool_calls: bool = False, ) -> Union[Model, List[Model]]: """Parse tool outputs.""" outputs = [cast(Model, s.raw_output) for s in agent_response.sources] if allow_parallel_tool_calls: return outputs else: if len(outputs) > 1: _logger.warning( "Multiple outputs found, returning first one. " "If you want to return all outputs, set output_multiple=True." ) return outputs[0] def _process_objects( self, chat_response: ChatResponse, output_cls: Type[Model], cur_objects: Optional[List[Model]] = None, ) -> Union[Model, List[Model]]: """Process stream.""" tool_calls = self._llm.get_tool_calls_from_response( chat_response, # error_on_no_tool_call=True error_on_no_tool_call=False, ) # TODO: change if len(tool_calls) == 0: # if no tool calls, return single blank output_class return output_cls() tool_fn_args = [call.tool_kwargs for call in tool_calls] objects = [ output_cls.model_validate(tool_fn_arg) for tool_fn_arg in tool_fn_args ] if cur_objects is None or num_valid_fields(objects) > num_valid_fields( cur_objects ): cur_objects = objects # right now the objects are typed according to a flexible schema # try to do a pass to convert the objects to the output_cls new_cur_objects = [] for obj in cur_objects: try: new_obj = self._output_cls.model_validate(obj.model_dump()) except ValidationError as e: _logger.warning(f"Failed to parse object: {e}") new_obj = obj new_cur_objects.append(new_obj) if self._allow_parallel_tool_calls: return new_cur_objects else: if len(new_cur_objects) > 1: _logger.warning( "Multiple outputs found, returning first one. " "If you want to return all outputs, set output_multiple=True." ) return new_cur_objects[0] def stream_call( self, *args: Any, llm_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any ) -> Generator[ Union[Model, List[Model], FlexibleModel, List[FlexibleModel]], None, None ]: """ Stream object. Returns a generator returning partials of the same object or a list of objects until it returns. """ # TODO: we can extend this to non-function calling LLMs as well, coming soon if not isinstance(self._llm, FunctionCallingLLM): raise ValueError("stream_call is only supported for LLMs.") # avoid passing in duplicate kwargs llm_kwargs = llm_kwargs or {} llm_kwargs.pop("tool_required", None) llm_kwargs.pop("tool_choice", None) llm_kwargs.pop("allow_parallel_tool_calls", None) tool = get_function_tool(self._output_cls) messages = self._prompt.format_messages(llm=self._llm, **kwargs) messages = self._llm._extend_messages(messages) chat_response_gen = self._llm.stream_chat_with_tools( [tool], chat_history=messages, verbose=self._verbose, allow_parallel_tool_calls=self._allow_parallel_tool_calls, **llm_kwargs, ) cur_objects = None for partial_resp in chat_response_gen: try: objects = process_streaming_objects( partial_resp, self._output_cls, cur_objects=cur_objects, allow_parallel_tool_calls=self._allow_parallel_tool_calls, flexible_mode=True, llm=self._llm, ) cur_objects = objects if isinstance(objects, list) else [objects] yield objects except Exception as e: _logger.warning(f"Failed to parse streaming response: {e}") continue async def astream_call( self, *args: Any, llm_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any ) -> AsyncGenerator[ Union[Model, List[Model], FlexibleModel, List[FlexibleModel]], None ]: """ Stream objects. Returns a generator returning partials of the same object or a list of objects until it returns. """ if not isinstance(self._llm, FunctionCallingLLM): raise ValueError("stream_call is only supported for LLMs.") # avoid passing in duplicate kwargs llm_kwargs = llm_kwargs or {} llm_kwargs.pop("tool_required", None) llm_kwargs.pop("tool_choice", None) llm_kwargs.pop("allow_parallel_tool_calls", None) tool = get_function_tool(self._output_cls) messages = self._prompt.format_messages(llm=self._llm, **kwargs) messages = self._llm._extend_messages(messages) chat_response_gen = await self._llm.astream_chat_with_tools( [tool], chat_history=messages, verbose=self._verbose, allow_parallel_tool_calls=self._allow_parallel_tool_calls, **llm_kwargs, ) async def gen() -> AsyncGenerator[ Union[Model, List[Model], FlexibleModel, List[FlexibleModel]], None ]: cur_objects = None async for partial_resp in chat_response_gen: try: objects = process_streaming_objects( partial_resp, self._output_cls, cur_objects=cur_objects, allow_parallel_tool_calls=self._allow_parallel_tool_calls, flexible_mode=True, llm=self._llm, ) cur_objects = objects if isinstance(objects, list) else [objects] yield objects except Exception as e: _logger.warning(f"Failed to parse streaming response: {e}") continue return gen()
FunctionCallingProgram
python
pydantic__pydantic
tests/mypy/modules/plugin_fail.py
{ "start": 4716, "end": 5088 }
class ____(BaseModel): name: str @field_validator('name') def noop_validator_with_annotations(self, name: str) -> str: # This is a mistake: the first argument to a validator is the class itself, # like a classmethod. self.instance_method() return name def instance_method(self) -> None: ...
ModelWithAnnotatedValidator
python
scipy__scipy
scipy/sparse/tests/test_base.py
{ "start": 93835, "end": 97483 }
class ____: def test_inplace_dense(self): a = np.ones((3, 4)) b = self.spcreator(a) x = a.copy() y = a.copy() x += a y += b assert_array_equal(x, y) x = a.copy() y = a.copy() x -= a y -= b assert_array_equal(x, y) if self.is_array_test: # Elementwise multiply from sparray.__rmul__ x = a.copy() y = a.copy() with assert_raises(ValueError, match="inconsistent shapes"): x *= b.T x = x * a y *= b assert_array_equal(x, y.toarray()) else: # Matrix multiply from spmatrix.__rmul__ x = a.copy() y = a.copy() with assert_raises(ValueError, match="dimension mismatch"): x *= b x = x.dot(a.T) y *= b.T assert_array_equal(x, y) # Matrix multiply from __rmatmul__ y = a.copy() y @= b.T x = a.copy() y = a.copy() with assert_raises(ValueError, match="dimension mismatch"): x @= b x = x.dot(a.T) y @= b.T assert_array_equal(x, y) # Floor division is not supported with assert_raises(TypeError, match="unsupported operand"): x //= b def test_imul_scalar(self): def check(dtype): dat = self.dat_dtypes[dtype] datsp = self.datsp_dtypes[dtype] # Avoid implicit casting. if np.can_cast(int, dtype, casting='same_kind'): a = datsp.copy() a *= 2 b = dat.copy() b *= 2 assert_array_equal(b, a.toarray()) if np.can_cast(float, dtype, casting='same_kind'): a = datsp.copy() a *= 17.3 b = dat.copy() b *= 17.3 assert_array_equal(b, a.toarray()) for dtype in self.math_dtypes: check(dtype) def test_idiv_scalar(self): def check(dtype): dat = self.dat_dtypes[dtype] datsp = self.datsp_dtypes[dtype] if np.can_cast(int, dtype, casting='same_kind'): a = datsp.copy() a /= 2 b = dat.copy() b /= 2 assert_array_equal(b, a.toarray()) if np.can_cast(float, dtype, casting='same_kind'): a = datsp.copy() a /= 17.3 b = dat.copy() b /= 17.3 assert_array_equal(b, a.toarray()) for dtype in self.math_dtypes: # /= should only be used with float dtypes to avoid implicit # casting. if not np.can_cast(dtype, np.dtype(int)): check(dtype) def test_inplace_success(self): # Inplace ops should work even if a specialized version is not # implemented, falling back to x = x <op> y a = self.spcreator(np.eye(5)) b = self.spcreator(np.eye(5)) bp = self.spcreator(np.eye(5)) b += a bp = bp + a assert_allclose(b.toarray(), bp.toarray()) if self.is_array_test: b *= a bp = bp * a assert_allclose(b.toarray(), bp.toarray()) b @= a bp = bp @ a assert_allclose(b.toarray(), bp.toarray()) b -= a bp = bp - a assert_allclose(b.toarray(), bp.toarray()) with assert_raises(TypeError, match="unsupported operand"): a //= b
_TestInplaceArithmetic
python
fastai__fastai
fastai/callback/training.py
{ "start": 458, "end": 870 }
class ____(Callback): "Fit just `pct` of an epoch, then stop" def __init__(self,pct=0.01,short_valid=True): self.pct,self.short_valid = pct,short_valid def after_batch(self): if self.iter/self.n_iter < self.pct: return if self.training: raise CancelTrainException if self.short_valid: raise CancelValidException # %% ../../nbs/18a_callback.training.ipynb 10
ShortEpochCallback
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/dataclass_taint.py
{ "start": 1481, "end": 1719 }
class ____: tainted: int not_tainted: str def test_dataclass_with_source(context: DataClassWithSource) -> None: _test_sink(context.tainted) _test_sink(context.not_tainted) @final @dataclass(frozen=True)
DataClassWithSource
python
bokeh__bokeh
src/bokeh/models/expressions.py
{ "start": 6684, "end": 7007 }
class ____(ScalarExpression): """ Computes minimum value of a data source's column. """ # explicit __init__ to support Init signatures def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) field = Required(String) initial = Nullable(Float, default=inf)
Minimum
python
apache__airflow
airflow-core/src/airflow/api_fastapi/common/parameters.py
{ "start": 18232, "end": 19306 }
class ____(BaseParam[list[str]]): """Search on dag_id.""" def __init__(self, skip_none: bool = True) -> None: super().__init__(skip_none=skip_none) @classmethod def depends(cls, dag_ids: list[str] = Query(None)) -> _DagIdAssetReferenceFilter: # needed to handle cases where dag_ids=a1,b1 if dag_ids and len(dag_ids) == 1 and "," in dag_ids[0]: dag_ids = dag_ids[0].split(",") return cls().set_value(dag_ids) def to_orm(self, select: Select) -> Select: if self.value is None and self.skip_none: return select # At this point, self.value is either a list[str] or None -> coerce falsy None to an empty list dag_ids = self.value or [] return select.where( (AssetModel.scheduled_dags.any(DagScheduleAssetReference.dag_id.in_(dag_ids))) | (AssetModel.producing_tasks.any(TaskOutletAssetReference.dag_id.in_(dag_ids))) | (AssetModel.consuming_tasks.any(TaskInletAssetReference.dag_id.in_(dag_ids))) )
_DagIdAssetReferenceFilter
python
wandb__wandb
wandb/vendor/pygments/lexers/data.py
{ "start": 17795, "end": 18269 }
class ____(JsonLexer): """ For JSON data structures (with missing object curly braces). .. versionadded:: 2.2 """ name = 'JSONBareObject' aliases = ['json-object'] filenames = [] mimetypes = ['application/json-object'] tokens = { 'root': [ (r'\}', Error), include('objectvalue'), ], 'objectattribute': [ (r'\}', Error), inherit, ], }
JsonBareObjectLexer
python
scrapy__scrapy
scrapy/pqueues.py
{ "start": 1110, "end": 1374 }
class ____(Protocol): """Protocol for downstream queues of ``ScrapyPriorityQueue``.""" def push(self, request: Request) -> None: ... def pop(self) -> Request | None: ... def close(self) -> None: ... def __len__(self) -> int: ...
QueueProtocol
python
tensorflow__tensorflow
tensorflow/python/util/decorator_utils_test.py
{ "start": 1325, "end": 3429 }
class ____(test.TestCase): def _check(self, doc, expected): self.assertEqual( decorator_utils.add_notice_to_docstring( doc=doc, instructions="Instructions", no_doc_str="Nothing here", suffix_str="(suffix)", notice=["Go away"]), expected) def test_regular(self): expected = ( "Brief (suffix)\n\nWarning: Go away\nInstructions\n\nDocstring\n\n" "Args:\n arg1: desc") # No indent for main docstring self._check("Brief\n\nDocstring\n\nArgs:\n arg1: desc", expected) # 2 space indent for main docstring, blank lines not indented self._check("Brief\n\n Docstring\n\n Args:\n arg1: desc", expected) # 2 space indent for main docstring, blank lines indented as well. self._check("Brief\n \n Docstring\n \n Args:\n arg1: desc", expected) # No indent for main docstring, first line blank. self._check("\n Brief\n \n Docstring\n \n Args:\n arg1: desc", expected) # 2 space indent, first line blank. self._check("\n Brief\n \n Docstring\n \n Args:\n arg1: desc", expected) def test_brief_only(self): expected = "Brief (suffix)\n\nWarning: Go away\nInstructions" self._check("Brief", expected) self._check("Brief\n", expected) self._check("Brief\n ", expected) self._check("\nBrief\n ", expected) self._check("\n Brief\n ", expected) def test_no_docstring(self): expected = "Nothing here\n\nWarning: Go away\nInstructions" self._check(None, expected) self._check("", expected) def test_no_empty_line(self): expected = "Brief (suffix)\n\nWarning: Go away\nInstructions\n\nDocstring" # No second line indent self._check("Brief\nDocstring", expected) # 2 space second line indent self._check("Brief\n Docstring", expected) # No second line indent, first line blank self._check("\nBrief\nDocstring", expected) # 2 space second line indent, first line blank self._check("\n Brief\n Docstring", expected)
AddNoticeToDocstringTest
python
doocs__leetcode
solution/3300-3399/3360.Stone Removal Game/Solution.py
{ "start": 0, "end": 185 }
class ____: def canAliceWin(self, n: int) -> bool: x, k = 10, 0 while n >= x: n -= x x -= 1 k += 1 return k % 2 == 1
Solution
python
scipy__scipy
scipy/special/tests/test_spherical_bessel.py
{ "start": 9801, "end": 10200 }
class ____(SphericalDerivativesTestCase): def f(self, n, z): return spherical_jn(n, z) def df(self, n, z): return spherical_jn(n, z, derivative=True) def test_spherical_jn_d_zero(self): n = np.array([0, 1, 2, 3, 7, 15]) assert_allclose(spherical_jn(n, 0, derivative=True), np.array([0, 1/3, 0, 0, 0, 0]))
TestSphericalJnDerivatives
python
kamyu104__LeetCode-Solutions
Python/distribute-money-to-maximum-children.py
{ "start": 38, "end": 467 }
class ____(object): def distMoney(self, money, children): """ :type money: int :type children: int :rtype: int """ if money < children*1: return -1 money -= children*1 q, r = divmod(money, 7) return min(q, children) - int(q > children or (q == children and r != 0) or (q == children-1 and r == 3)) # Time: O(1) # Space: O(1) # greedy
Solution
python
Textualize__textual
tests/snapshot_tests/snapshot_apps/multiple_css/multiple_css.py
{ "start": 722, "end": 1036 }
class ____(App): CSS = """ #one { background: red; } """ def compose(self) -> ComposeResult: yield Static("#one", id="one") yield Static("#two", id="two") app = MultipleCSSApp(css_path=["first.tcss", "second.tcss"]) if __name__ == "__main__": app.run()
MultipleCSSApp
python
networkx__networkx
networkx/algorithms/tree/branchings.py
{ "start": 26228, "end": 34336 }
class ____: """ Iterate over all spanning arborescences of a graph in either increasing or decreasing cost. Notes ----- This iterator uses the partition scheme from [1]_ (included edges, excluded edges and open edges). It generates minimum spanning arborescences using a modified Edmonds' Algorithm which respects the partition of edges. For arborescences with the same weight, ties are broken arbitrarily. References ---------- .. [1] G.K. Janssens, K. Sörensen, An algorithm to generate all spanning trees in order of increasing cost, Pesquisa Operacional, 2005-08, Vol. 25 (2), p. 219-229, https://www.scielo.br/j/pope/a/XHswBwRwJyrfL88dmMwYNWp/?lang=en """ @dataclass(order=True) class Partition: """ This dataclass represents a partition and stores a dict with the edge data and the weight of the minimum spanning arborescence of the partition dict. """ mst_weight: float partition_dict: dict = field(compare=False) def __copy__(self): return ArborescenceIterator.Partition( self.mst_weight, self.partition_dict.copy() ) def __init__(self, G, weight="weight", minimum=True, init_partition=None): """ Initialize the iterator Parameters ---------- G : nx.DiGraph The directed graph which we need to iterate trees over weight : String, default = "weight" The edge attribute used to store the weight of the edge minimum : bool, default = True Return the trees in increasing order while true and decreasing order while false. init_partition : tuple, default = None In the case that certain edges have to be included or excluded from the arborescences, `init_partition` should be in the form `(included_edges, excluded_edges)` where each edges is a `(u, v)`-tuple inside an iterable such as a list or set. """ self.G = G.copy() self.weight = weight self.minimum = minimum self.method = ( minimum_spanning_arborescence if minimum else maximum_spanning_arborescence ) # Randomly create a key for an edge attribute to hold the partition data self.partition_key = ( "ArborescenceIterators super secret partition attribute name" ) if init_partition is not None: partition_dict = {} for e in init_partition[0]: partition_dict[e] = nx.EdgePartition.INCLUDED for e in init_partition[1]: partition_dict[e] = nx.EdgePartition.EXCLUDED self.init_partition = ArborescenceIterator.Partition(0, partition_dict) else: self.init_partition = None def __iter__(self): """ Returns ------- ArborescenceIterator The iterator object for this graph """ self.partition_queue = PriorityQueue() self._clear_partition(self.G) # Write the initial partition if it exists. if self.init_partition is not None: self._write_partition(self.init_partition) mst_weight = self.method( self.G, self.weight, partition=self.partition_key, preserve_attrs=True, ).size(weight=self.weight) self.partition_queue.put( self.Partition( mst_weight if self.minimum else -mst_weight, ( {} if self.init_partition is None else self.init_partition.partition_dict ), ) ) return self def __next__(self): """ Returns ------- (multi)Graph The spanning tree of next greatest weight, which ties broken arbitrarily. """ if self.partition_queue.empty(): del self.G, self.partition_queue raise StopIteration partition = self.partition_queue.get() self._write_partition(partition) next_arborescence = self.method( self.G, self.weight, partition=self.partition_key, preserve_attrs=True, ) self._partition(partition, next_arborescence) self._clear_partition(next_arborescence) return next_arborescence def _partition(self, partition, partition_arborescence): """ Create new partitions based of the minimum spanning tree of the current minimum partition. Parameters ---------- partition : Partition The Partition instance used to generate the current minimum spanning tree. partition_arborescence : nx.Graph The minimum spanning arborescence of the input partition. """ # create two new partitions with the data from the input partition dict p1 = self.Partition(0, partition.partition_dict.copy()) p2 = self.Partition(0, partition.partition_dict.copy()) for e in partition_arborescence.edges: # determine if the edge was open or included if e not in partition.partition_dict: # This is an open edge p1.partition_dict[e] = nx.EdgePartition.EXCLUDED p2.partition_dict[e] = nx.EdgePartition.INCLUDED self._write_partition(p1) try: p1_mst = self.method( self.G, self.weight, partition=self.partition_key, preserve_attrs=True, ) p1_mst_weight = p1_mst.size(weight=self.weight) p1.mst_weight = p1_mst_weight if self.minimum else -p1_mst_weight self.partition_queue.put(p1.__copy__()) except nx.NetworkXException: pass p1.partition_dict = p2.partition_dict.copy() def _write_partition(self, partition): """ Writes the desired partition into the graph to calculate the minimum spanning tree. Also, if one incoming edge is included, mark all others as excluded so that if that vertex is merged during Edmonds' algorithm we cannot still pick another of that vertex's included edges. Parameters ---------- partition : Partition A Partition dataclass describing a partition on the edges of the graph. """ for u, v, d in self.G.edges(data=True): if (u, v) in partition.partition_dict: d[self.partition_key] = partition.partition_dict[(u, v)] else: d[self.partition_key] = nx.EdgePartition.OPEN nx._clear_cache(self.G) for n in self.G: included_count = 0 excluded_count = 0 for u, v, d in self.G.in_edges(nbunch=n, data=True): if d.get(self.partition_key) == nx.EdgePartition.INCLUDED: included_count += 1 elif d.get(self.partition_key) == nx.EdgePartition.EXCLUDED: excluded_count += 1 # Check that if there is an included edges, all other incoming ones # are excluded. If not fix it! if included_count == 1 and excluded_count != self.G.in_degree(n) - 1: for u, v, d in self.G.in_edges(nbunch=n, data=True): if d.get(self.partition_key) != nx.EdgePartition.INCLUDED: d[self.partition_key] = nx.EdgePartition.EXCLUDED def _clear_partition(self, G): """ Removes partition data from the graph """ for u, v, d in G.edges(data=True): if self.partition_key in d: del d[self.partition_key] nx._clear_cache(self.G)
ArborescenceIterator
python
django__django
tests/serializers/models/data.py
{ "start": 4533, "end": 4634 }
class ____(models.Model): data = models.BooleanField(primary_key=True, default=False)
BooleanPKData
python
pypa__pipenv
pipenv/vendor/click/core.py
{ "start": 68664, "end": 74702 }
class ____(MultiCommand): """A group allows a command to have subcommands attached. This is the most common way to implement nesting in Click. :param name: The name of the group command. :param commands: A dict mapping names to :class:`Command` objects. Can also be a list of :class:`Command`, which will use :attr:`Command.name` to create the dict. :param attrs: Other command arguments described in :class:`MultiCommand`, :class:`Command`, and :class:`BaseCommand`. .. versionchanged:: 8.0 The ``commands`` argument can be a list of command objects. """ #: If set, this is used by the group's :meth:`command` decorator #: as the default :class:`Command` class. This is useful to make all #: subcommands use a custom command class. #: #: .. versionadded:: 8.0 command_class: t.Optional[t.Type[Command]] = None #: If set, this is used by the group's :meth:`group` decorator #: as the default :class:`Group` class. This is useful to make all #: subgroups use a custom group class. #: #: If set to the special value :class:`type` (literally #: ``group_class = type``), this group's class will be used as the #: default class. This makes a custom group class continue to make #: custom groups. #: #: .. versionadded:: 8.0 group_class: t.Optional[t.Union[t.Type["Group"], t.Type[type]]] = None # Literal[type] isn't valid, so use Type[type] def __init__( self, name: t.Optional[str] = None, commands: t.Optional[ t.Union[t.MutableMapping[str, Command], t.Sequence[Command]] ] = None, **attrs: t.Any, ) -> None: super().__init__(name, **attrs) if commands is None: commands = {} elif isinstance(commands, abc.Sequence): commands = {c.name: c for c in commands if c.name is not None} #: The registered subcommands by their exported names. self.commands: t.MutableMapping[str, Command] = commands def add_command(self, cmd: Command, name: t.Optional[str] = None) -> None: """Registers another :class:`Command` with this group. If the name is not provided, the name of the command is used. """ name = name or cmd.name if name is None: raise TypeError("Command has no name.") _check_multicommand(self, name, cmd, register=True) self.commands[name] = cmd @t.overload def command(self, __func: t.Callable[..., t.Any]) -> Command: ... @t.overload def command( self, *args: t.Any, **kwargs: t.Any ) -> t.Callable[[t.Callable[..., t.Any]], Command]: ... def command( self, *args: t.Any, **kwargs: t.Any ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], Command], Command]: """A shortcut decorator for declaring and attaching a command to the group. This takes the same arguments as :func:`command` and immediately registers the created command with this group by calling :meth:`add_command`. To customize the command class used, set the :attr:`command_class` attribute. .. versionchanged:: 8.1 This decorator can be applied without parentheses. .. versionchanged:: 8.0 Added the :attr:`command_class` attribute. """ from .decorators import command func: t.Optional[t.Callable[..., t.Any]] = None if args and callable(args[0]): assert ( len(args) == 1 and not kwargs ), "Use 'command(**kwargs)(callable)' to provide arguments." (func,) = args args = () if self.command_class and kwargs.get("cls") is None: kwargs["cls"] = self.command_class def decorator(f: t.Callable[..., t.Any]) -> Command: cmd: Command = command(*args, **kwargs)(f) self.add_command(cmd) return cmd if func is not None: return decorator(func) return decorator @t.overload def group(self, __func: t.Callable[..., t.Any]) -> "Group": ... @t.overload def group( self, *args: t.Any, **kwargs: t.Any ) -> t.Callable[[t.Callable[..., t.Any]], "Group"]: ... def group( self, *args: t.Any, **kwargs: t.Any ) -> t.Union[t.Callable[[t.Callable[..., t.Any]], "Group"], "Group"]: """A shortcut decorator for declaring and attaching a group to the group. This takes the same arguments as :func:`group` and immediately registers the created group with this group by calling :meth:`add_command`. To customize the group class used, set the :attr:`group_class` attribute. .. versionchanged:: 8.1 This decorator can be applied without parentheses. .. versionchanged:: 8.0 Added the :attr:`group_class` attribute. """ from .decorators import group func: t.Optional[t.Callable[..., t.Any]] = None if args and callable(args[0]): assert ( len(args) == 1 and not kwargs ), "Use 'group(**kwargs)(callable)' to provide arguments." (func,) = args args = () if self.group_class is not None and kwargs.get("cls") is None: if self.group_class is type: kwargs["cls"] = type(self) else: kwargs["cls"] = self.group_class def decorator(f: t.Callable[..., t.Any]) -> "Group": cmd: Group = group(*args, **kwargs)(f) self.add_command(cmd) return cmd if func is not None: return decorator(func) return decorator def get_command(self, ctx: Context, cmd_name: str) -> t.Optional[Command]: return self.commands.get(cmd_name) def list_commands(self, ctx: Context) -> t.List[str]: return sorted(self.commands)
Group
python
huggingface__transformers
tests/models/llama/test_tokenization_llama.py
{ "start": 242, "end": 2610 }
class ____(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = [ "hf-internal-testing/llama-tokenizer", "meta-llama/Llama-2-7b-hf", "meta-llama/Meta-Llama-3-8B", ] tokenizer_class = LlamaTokenizer from_pretrained_kwargs = {} # Integration test data - expected outputs for the default input string integration_expected_tokens = ["▁This", "▁is", "▁a", "▁test", "▁", "<0xF0>", "<0x9F>", "<0x98>", "<0x8A>", "<0x0A>", "I", "▁was", "▁born", "▁in", "▁", "9", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "als", "é", ".", "<0x0A>", "生", "活", "的", "真", "<0xE8>", "<0xB0>", "<0x9B>", "是", "<0x0A>", "Hi", "▁", "▁Hello", "<0x0A>", "Hi", "▁▁", "▁Hello", "<0x0A>", "<0x0A>", "▁", "<0x0A>", "▁▁", "<0x0A>", "▁Hello", "<0x0A>", "<s>", "<0x0A>", "hi", "<s>", "there", "<0x0A>", "The", "▁following", "▁string", "▁should", "▁be", "▁properly", "▁encoded", ":", "▁Hello", ".", "<0x0A>", "But", "▁", "ird", "▁and", "▁", "ป", "ี", "▁▁▁", "ird", "▁▁▁", "ด", "<0x0A>", "H", "ey", "▁how", "▁are", "▁you", "▁doing"] # fmt: skip integration_expected_token_ids = [910, 338, 263, 1243, 29871, 243, 162, 155, 141, 13, 29902, 471, 6345, 297, 29871, 29929, 29906, 29900, 29900, 29900, 29892, 322, 445, 338, 285, 1338, 29948, 29889, 13, 30486, 31704, 30210, 30848, 235, 179, 158, 30392, 13, 18567, 29871, 15043, 13, 18567, 259, 15043, 13, 13, 29871, 13, 259, 13, 15043, 13, 1, 13, 2918, 1, 12711, 13, 1576, 1494, 1347, 881, 367, 6284, 18511, 29901, 15043, 29889, 13, 6246, 29871, 1823, 322, 29871, 31010, 30691, 1678, 1823, 1678, 30718, 13, 29950, 1032, 920, 526, 366, 2599] # fmt: skip integration_expected_decoded_text = "This is a test 😊\nI was born in 92000, and this is falsé.\n生活的真谛是\nHi Hello\nHi Hello\n\n \n \n Hello\n<s>\nhi<s>there\nThe following string should be properly encoded: Hello.\nBut ird and ปี ird ด\nHey how are you doing" @classmethod def setUpClass(cls): super().setUpClass() from_pretrained_id = "hf-internal-testing/llama-tokenizer" tokenizer = LlamaTokenizer.from_pretrained(from_pretrained_id) tokenizer.pad_token = tokenizer.eos_token tokenizer.save_pretrained(cls.tmpdirname) def get_tokenizers(self, **kwargs): kwargs.setdefault("pad_token", "<PAD>") return super().get_tokenizers(**kwargs)
LlamaTokenizationTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/pylint/duplicate_bases.py
{ "start": 437, "end": 459 }
class ____(C): ...
D
python
charliermarsh__ruff
python/ruff-ecosystem/ruff_ecosystem/projects.py
{ "start": 535, "end": 1674 }
class ____(Serializable): """ An ecosystem target """ repo: Repository check_options: CheckOptions = field(default_factory=lambda: CheckOptions()) format_options: FormatOptions = field(default_factory=lambda: FormatOptions()) config_overrides: ConfigOverrides = field(default_factory=lambda: ConfigOverrides()) def with_preview_enabled(self: Self) -> Self: return type(self)( repo=self.repo, check_options=self.check_options.with_options(preview=True), format_options=self.format_options.with_options(preview=True), config_overrides=self.config_overrides, ) def __post_init__(self): # Convert bare dictionaries for `config_overrides` into the correct type if isinstance(self.config_overrides, dict): # Bypass the frozen attribute object.__setattr__( self, "config_overrides", ConfigOverrides(always=self.config_overrides) ) ALWAYS_CONFIG_OVERRIDES = { # Always unset the required version or we'll fail "required-version": None } @dataclass(frozen=True)
Project
python
pypa__hatch
tests/backend/metadata/test_core.py
{ "start": 68822, "end": 71710 }
class ____: def test_basic_persistence(self, temp_dir, helpers): metadata = ProjectMetadata( str(temp_dir), None, { "project": { "name": "My.App", "dynamic": ["version", "keywords"], "dependencies": ["foo==1"], "scripts": {"foo": "bar"}, }, }, ) pkg_info = temp_dir / "PKG-INFO" pkg_info.write_text( helpers.dedent( f""" Metadata-Version: {LATEST_METADATA_VERSION} Name: My.App Version: 0.0.1 Keywords: foo,bar Requires-Dist: bar==5 """ ) ) with temp_dir.as_cwd(): assert metadata.core.config == { "name": "My.App", "version": "0.0.1", "dependencies": ["foo==1"], "keywords": ["foo", "bar"], "scripts": {"foo": "bar"}, "dynamic": [], } def test_metadata_hooks(self, temp_dir, helpers): metadata = ProjectMetadata( str(temp_dir), PluginManager(), { "project": { "name": "My.App", "dynamic": ["version", "keywords", "description", "scripts"], "dependencies": ["foo==1"], }, "tool": {"hatch": {"metadata": {"hooks": {"custom": {}}}}}, }, ) build_script = temp_dir / DEFAULT_BUILD_SCRIPT build_script.write_text( helpers.dedent( """ from hatchling.metadata.plugin.interface import MetadataHookInterface class CustomHook(MetadataHookInterface): def update(self, metadata): metadata['description'] = metadata['name'] + ' bar' metadata['scripts'] = {'foo': 'bar'} """ ) ) pkg_info = temp_dir / "PKG-INFO" pkg_info.write_text( helpers.dedent( f""" Metadata-Version: {LATEST_METADATA_VERSION} Name: My.App Version: 0.0.1 Summary: My.App bar Keywords: foo,bar Requires-Dist: bar==5 """ ) ) with temp_dir.as_cwd(): assert metadata.core.config == { "name": "My.App", "version": "0.0.1", "description": "My.App bar", "dependencies": ["foo==1"], "keywords": ["foo", "bar"], "scripts": {"foo": "bar"}, "dynamic": ["scripts"], }
TestSourceDistributionMetadata
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_default_row01.py
{ "start": 315, "end": 882 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("default_row01.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.set_default_row(24) worksheet.write("A1", "Foo") worksheet.write("A10", "Bar") workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
ray-project__ray
python/ray/data/datasource/partitioning.py
{ "start": 16303, "end": 22253 }
class ____: """Partition filter for path-based partition formats. Used to explicitly keep or reject files based on a custom filter function that takes partition keys and values parsed from the file's path as input. """ @staticmethod def of( filter_fn: Callable[[Dict[str, str]], bool], style: PartitionStyle = PartitionStyle.HIVE, base_dir: Optional[str] = None, field_names: Optional[List[str]] = None, field_types: Optional[Dict[str, PartitionDataType]] = None, filesystem: Optional["pyarrow.fs.FileSystem"] = None, ) -> "PathPartitionFilter": """Creates a path-based partition filter using a flattened argument list. Args: filter_fn: Callback used to filter partitions. Takes a dictionary mapping partition keys to values as input. Unpartitioned files are denoted with an empty input dictionary. Returns `True` to read a file for that partition or `False` to skip it. Partition keys and values are always strings read from the filesystem path. For example, this removes all unpartitioned files: .. code:: python lambda d: True if d else False This raises an assertion error for any unpartitioned file found: .. code:: python def do_assert(val, msg): assert val, msg lambda d: do_assert(d, "Expected all files to be partitioned!") And this only reads files from January, 2022 partitions: .. code:: python lambda d: d["month"] == "January" and d["year"] == "2022" style: The partition style - may be either HIVE or DIRECTORY. base_dir: "/"-delimited base directory to start searching for partitions (exclusive). File paths outside of this directory will be considered unpartitioned. Specify `None` or an empty string to search for partitions in all file path directories. field_names: The partition key names. Required for DIRECTORY partitioning. Optional for HIVE partitioning. When non-empty, the order and length of partition key field names must match the order and length of partition directories discovered. Partition key field names are not required to exist in the dataset schema. field_types: A dictionary that maps partition key names to their desired data type. If not provided, the data type defaults to string. filesystem: Filesystem that will be used for partition path file I/O. Returns: The new path-based partition filter. """ scheme = Partitioning(style, base_dir, field_names, field_types, filesystem) path_partition_parser = PathPartitionParser(scheme) return PathPartitionFilter(path_partition_parser, filter_fn) def __init__( self, path_partition_parser: PathPartitionParser, filter_fn: Callable[[Dict[str, str]], bool], ): """Creates a new path-based partition filter based on a parser. Args: path_partition_parser: The path-based partition parser. filter_fn: Callback used to filter partitions. Takes a dictionary mapping partition keys to values as input. Unpartitioned files are denoted with an empty input dictionary. Returns `True` to read a file for that partition or `False` to skip it. Partition keys and values are always strings read from the filesystem path. For example, this removes all unpartitioned files: ``lambda d: True if d else False`` This raises an assertion error for any unpartitioned file found: ``lambda d: assert d, "Expected all files to be partitioned!"`` And this only reads files from January, 2022 partitions: ``lambda d: d["month"] == "January" and d["year"] == "2022"`` """ self._parser = path_partition_parser self._filter_fn = filter_fn def __call__(self, paths: List[str]) -> List[str]: """Returns all paths that pass this partition scheme's partition filter. If no partition filter is set, then returns all input paths. If a base directory is set, then only paths under this base directory will be parsed for partitions. All paths outside of this base directory will automatically be considered unpartitioned, and passed into the filter function as empty dictionaries. Also normalizes the partition base directory for compatibility with the given filesystem before applying the filter. Args: paths: Paths to pass through the partition filter function. All paths should be normalized for compatibility with the given filesystem. Returns: List of paths that pass the partition filter, or all paths if no partition filter is defined. """ filtered_paths = paths if self._filter_fn is not None: filtered_paths = [path for path in paths if self.apply(path)] return filtered_paths def apply(self, path: str) -> bool: return self._filter_fn(self._parser(path)) @property def parser(self) -> PathPartitionParser: """Returns the path partition parser for this filter.""" return self._parser def _cast_value(value: str, data_type: PartitionDataType) -> Any: if data_type is int: return int(value) elif data_type is float: return float(value) elif data_type is bool: return value.lower() == "true" else: return value
PathPartitionFilter
python
ray-project__ray
python/ray/serve/_private/common.py
{ "start": 25501, "end": 25601 }
class ____: is_available: bool running_replicas: List[RunningReplicaInfo]
DeploymentTargetInfo
python
tensorflow__tensorflow
tensorflow/python/framework/ops_test.py
{ "start": 132524, "end": 133103 }
class ____(composite_tensor.CompositeTensor): """`Tensor`-like `tuple`-like for custom `Tensor` conversion masquerading.""" def __init__(self, components): super(_TupleTensor, self).__init__() self._components = tuple(ops.convert_to_tensor(c) for c in components) @property def _type_spec(self): return _TupleTensorSpec(type_spec.from_value(c) for c in self._components) def __getitem__(self, key): return self._components[key] def __len__(self): return len(self._components) def __iter__(self): return iter(self._components)
_TupleTensor
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/strategies/_internal/misc.py
{ "start": 3187, "end": 4344 }
class ____(SearchStrategy["Never"]): def calc_is_empty(self, recur: RecurT) -> bool: return True def do_draw(self, data: ConjectureData) -> NoReturn: # This method should never be called because draw() will mark the # data as invalid immediately because is_empty is True. raise NotImplementedError("This should never happen") def calc_has_reusable_values(self, recur: RecurT) -> bool: return True def __repr__(self) -> str: return "nothing()" def map(self, pack: Callable[[Any], Any]) -> SearchStrategy["Never"]: return self def filter(self, condition: Callable[[Any], Any]) -> "SearchStrategy[Never]": return self def flatmap( self, expand: Callable[[Any], "SearchStrategy[Any]"] ) -> "SearchStrategy[Never]": return self NOTHING = Nothing() @cacheable @defines_strategy(eager=True) def nothing() -> SearchStrategy["Never"]: """This strategy never successfully draws a value and will always reject on an attempt to draw. Examples from this strategy do not shrink (because there are none). """ return NOTHING
Nothing
python
numpy__numpy
numpy/_core/tests/test_scalarinherit.py
{ "start": 368, "end": 409 }
class ____(np.float64, HasNew): pass
B1
python
google__pytype
pytype/tests/test_list2.py
{ "start": 69, "end": 798 }
class ____(test_base.BaseTest): """Basic tests for builtins.list in Python 3.""" def test_repeated_add(self): # At the time of this writing, this test completes in <5s. If it takes # significantly longer, there's been a performance regression. self.CheckWithErrors(""" from typing import List, Text, Tuple def f() -> Tuple[List[Text]]: x = ( ['' % __any_object__, ''] + [''] + [''] + [''.format()] + [''] + [['' % __any_object__, '', '']] ) return ([__any_object__] + [''] + x,) # bad-return-type """) def test_bad_comprehension(self): self.CheckWithErrors(""" x = None l = [y for y in x] # attribute-error """)
ListTestBasic
python
tensorflow__tensorflow
tensorflow/python/keras/layers/pooling.py
{ "start": 4170, "end": 7417 }
class ____(Pooling1D): """Max pooling operation for 1D temporal data. Downsamples the input representation by taking the maximum value over a spatial window of size `pool_size`. The window is shifted by `strides`. The resulting output, when using the `"valid"` padding option, has a shape of: `output_shape = (input_shape - pool_size + 1) / strides)` The resulting output shape when using the `"same"` padding option is: `output_shape = input_shape / strides` For example, for `strides=1` and `padding="valid"`: >>> x = tf.constant([1., 2., 3., 4., 5.]) >>> x = tf.reshape(x, [1, 5, 1]) >>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2, ... strides=1, padding='valid') >>> max_pool_1d(x) <tf.Tensor: shape=(1, 4, 1), dtype=float32, numpy= array([[[2.], [3.], [4.], [5.]]], dtype=float32)> For example, for `strides=2` and `padding="valid"`: >>> x = tf.constant([1., 2., 3., 4., 5.]) >>> x = tf.reshape(x, [1, 5, 1]) >>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2, ... strides=2, padding='valid') >>> max_pool_1d(x) <tf.Tensor: shape=(1, 2, 1), dtype=float32, numpy= array([[[2.], [4.]]], dtype=float32)> For example, for `strides=1` and `padding="same"`: >>> x = tf.constant([1., 2., 3., 4., 5.]) >>> x = tf.reshape(x, [1, 5, 1]) >>> max_pool_1d = tf.keras.layers.MaxPooling1D(pool_size=2, ... strides=1, padding='same') >>> max_pool_1d(x) <tf.Tensor: shape=(1, 5, 1), dtype=float32, numpy= array([[[2.], [3.], [4.], [5.], [5.]]], dtype=float32)> Args: pool_size: Integer, size of the max pooling window. strides: Integer, or None. Specifies how much the pooling window moves for each pooling step. If None, it will default to `pool_size`. padding: One of `"valid"` or `"same"` (case-insensitive). `"valid"` means no padding. `"same"` results in padding evenly to the left/right or up/down of the input such that output has the same height/width dimension as the input. data_format: A string, one of `channels_last` (default) or `channels_first`. The ordering of the dimensions in the inputs. `channels_last` corresponds to inputs with shape `(batch, steps, features)` while `channels_first` corresponds to inputs with shape `(batch, features, steps)`. Input shape: - If `data_format='channels_last'`: 3D tensor with shape `(batch_size, steps, features)`. - If `data_format='channels_first'`: 3D tensor with shape `(batch_size, features, steps)`. Output shape: - If `data_format='channels_last'`: 3D tensor with shape `(batch_size, downsampled_steps, features)`. - If `data_format='channels_first'`: 3D tensor with shape `(batch_size, features, downsampled_steps)`. """ def __init__(self, pool_size=2, strides=None, padding='valid', data_format='channels_last', **kwargs): super(MaxPooling1D, self).__init__( functools.partial(backend.pool2d, pool_mode='max'), pool_size=pool_size, strides=strides, padding=padding, data_format=data_format, **kwargs)
MaxPooling1D
python
gevent__gevent
src/gevent/tests/test__example_webproxy.py
{ "start": 252, "end": 807 }
class ____(test__example_wsgiserver.Test_wsgiserver): example = 'webproxy.py' def _run_all_tests(self): status, data = self.read('/') self.assertEqual(status, '200 OK') self.assertIn(b"gevent example", data) status, data = self.read('/http://www.google.com') self.assertEqual(status, '200 OK') self.assertIn(b'google', data.lower()) def test_a_blocking_client(self): # Not applicable raise SkipTest("Not applicable") if __name__ == '__main__': greentest.main()
Test_webproxy
python
huggingface__transformers
tests/models/clap/test_feature_extraction_clap.py
{ "start": 1643, "end": 3706 }
class ____: def __init__( self, parent, batch_size=7, min_seq_length=400, max_seq_length=2000, feature_size=10, hop_length=160, chunk_length=8, padding_value=0.0, sampling_rate=4_000, return_attention_mask=False, do_normalize=True, ): self.parent = parent self.batch_size = batch_size self.min_seq_length = min_seq_length self.max_seq_length = max_seq_length self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) self.padding_value = padding_value self.sampling_rate = sampling_rate self.return_attention_mask = return_attention_mask self.do_normalize = do_normalize self.feature_size = feature_size self.chunk_length = chunk_length self.hop_length = hop_length def prepare_feat_extract_dict(self): return { "feature_size": self.feature_size, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def prepare_inputs_for_common(self, equal_length=False, numpify=False): def _flatten(list_of_lists): return list(itertools.chain(*list_of_lists)) if equal_length: speech_inputs = [floats_list((self.max_seq_length, self.feature_size)) for _ in range(self.batch_size)] else: # make sure that inputs increase in size speech_inputs = [ floats_list((x, self.feature_size)) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff) ] if numpify: speech_inputs = [np.asarray(x) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio
ClapFeatureExtractionTester
python
gevent__gevent
src/gevent/tests/test__queue.py
{ "start": 3334, "end": 3976 }
class ____: def _getFUT(self): raise NotImplementedError def _makeOne(self, *args, **kwargs): return self._getFUT()(*args, **kwargs) def test_subscript(self): import queue as stdlib_queue kind = self._getFUT() try: stdlib_kind = getattr(stdlib_queue, kind.__name__) except AttributeError: assert kind.__name__ == 'Channel' import types self.assertIsInstance(kind[int], types.GenericAlias) else: self.assertIsNot(kind, stdlib_kind) self.assertIsInstance(kind[int], type(stdlib_kind[int]))
SubscriptMixin
python
pandas-dev__pandas
pandas/tests/indexes/period/methods/test_fillna.py
{ "start": 103, "end": 1125 }
class ____: def test_fillna_period(self): # GH#11343 idx = PeriodIndex(["2011-01-01 09:00", NaT, "2011-01-01 11:00"], freq="h") exp = PeriodIndex( ["2011-01-01 09:00", "2011-01-01 10:00", "2011-01-01 11:00"], freq="h" ) result = idx.fillna(Period("2011-01-01 10:00", freq="h")) tm.assert_index_equal(result, exp) exp = Index( [ Period("2011-01-01 09:00", freq="h"), "x", Period("2011-01-01 11:00", freq="h"), ], dtype=object, ) result = idx.fillna("x") tm.assert_index_equal(result, exp) exp = Index( [ Period("2011-01-01 09:00", freq="h"), Period("2011-01-01", freq="D"), Period("2011-01-01 11:00", freq="h"), ], dtype=object, ) result = idx.fillna(Period("2011-01-01", freq="D")) tm.assert_index_equal(result, exp)
TestFillNA