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
rq__rq
rq/local.py
{ "start": 6745, "end": 12818 }
class ____: """Acts as a proxy for a werkzeug local. Forwards all operations to a proxied object. The only operations not supported for forwarding are right handed operands and any kind of assignment. Example usage:: from werkzeug.local import Local l = Local() # these are proxies request = l('request') user = l('user') from werkzeug.local import LocalStack _response_local = LocalStack() # this is a proxy response = _response_local() Whenever something is bound to l.user / l.request the proxy objects will forward all operations. If no object is bound a :exc:`RuntimeError` will be raised. To create proxies to :class:`Local` or :class:`LocalStack` objects, call the object as shown above. If you want to have a proxy to an object looked up by a function, you can (as of Werkzeug 0.6.1) pass a function to the :class:`LocalProxy` constructor:: session = LocalProxy(lambda: get_current_request().session) .. versionchanged:: 0.6.1 The class can be instantiated with a callable as well now. """ __slots__ = ('__local', '__dict__', '__name__') def __init__(self, local, name=None): object.__setattr__(self, '_LocalProxy__local', local) object.__setattr__(self, '__name__', name) def _get_current_object(self): """Return the current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context. """ if not hasattr(self.__local, '__release_local__'): return self.__local() try: return getattr(self.__local, self.__name__) except AttributeError: raise RuntimeError('no object bound to %s' % self.__name__) @property def __dict__(self): try: return self._get_current_object().__dict__ except RuntimeError: raise AttributeError('__dict__') def __repr__(self): try: obj = self._get_current_object() except RuntimeError: return '<%s unbound>' % self.__class__.__name__ return repr(obj) def __dir__(self): try: return dir(self._get_current_object()) except RuntimeError: return [] def __getattr__(self, name): if name == '__members__': return dir(self._get_current_object()) return getattr(self._get_current_object(), name) def __setitem__(self, key, value): self._get_current_object()[key] = value def __delitem__(self, key): del self._get_current_object()[key] def __setattr__(self, name, value): setattr(self._get_current_object(), name, value) def __delattr__(self, name): return delattr(self._get_current_object(), name) def __str__(self): return str(self._get_current_object()) def __lt__(self, other): return self._get_current_object() < other def __le__(self, other): return self._get_current_object() <= other def __eq__(self, other): return self._get_current_object() == other def __ne__(self, other): return self._get_current_object() != other def __gt__(self, other): return self._get_current_object() > other def __ge__(self, other): return self._get_current_object() >= other def __hash__(self): return hash(self._get_current_object()) def __call__(self, *args, **kwargs): return self._get_current_object()(*args, **kwargs) def __len__(self): return len(self._get_current_object()) def __getitem__(self, i): return self._get_current_object()[i] def __iter__(self): return iter(self._get_current_object()) def __contains__(self, obj): return obj in self._get_current_object() def __add__(self, other): return self._get_current_object() + other def __sub__(self, other): return self._get_current_object() - other def __mul__(self, other): return self._get_current_object() * other def __floordiv__(self, other): return self._get_current_object() // other def __mod__(self, other): return self._get_current_object() % other def __divmod__(self, other): return self._get_current_object().__divmod__(other) def __pow__(self, other): return self._get_current_object() ** other def __lshift__(self, other): return self._get_current_object() << other def __rshift__(self, other): return self._get_current_object() >> other def __and__(self, other): return self._get_current_object() & other def __xor__(self, other): return self._get_current_object() ^ other def __or__(self, other): return self._get_current_object() | other def __div__(self, other): return self._get_current_object().__div__(other) def __truediv__(self, other): return self._get_current_object().__truediv__(other) def __neg__(self): return -(self._get_current_object()) def __pos__(self): return +(self._get_current_object()) def __abs__(self): return abs(self._get_current_object()) def __invert__(self): return ~(self._get_current_object()) def __complex__(self): return complex(self._get_current_object()) def __int__(self): return int(self._get_current_object()) def __float__(self): return float(self._get_current_object()) def __oct__(self): return oct(self._get_current_object()) def __hex__(self): return hex(self._get_current_object()) def __index__(self): return self._get_current_object().__index__() def __enter__(self): return self._get_current_object().__enter__() def __exit__(self, *args, **kwargs): return self._get_current_object().__exit__(*args, **kwargs)
LocalProxy
python
altair-viz__altair
tests/utils/test_core.py
{ "start": 1060, "end": 1168 }
class ____(FieldChannel, schemapi.SchemaBase): _schema = {json_schema_dict_str} _encoding_name = "x"
X
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/provision.py
{ "start": 738, "end": 17429 }
class ____: def __init__(self, decorator=None): self.fns = {} self.decorator = decorator @classmethod def init(cls, fn): return register().for_db("*")(fn) @classmethod def init_decorator(cls, decorator): return register(decorator).for_db("*") def for_db(self, *dbnames): def decorate(fn): if self.decorator: fn = self.decorator(fn) for dbname in dbnames: self.fns[dbname] = fn return self return decorate def call_original(self, cfg, *arg, **kw): return self.fns["*"](cfg, *arg, **kw) def __call__(self, cfg, *arg, **kw): if isinstance(cfg, str): url = sa_url.make_url(cfg) elif isinstance(cfg, sa_url.URL): url = cfg elif isinstance(cfg, (Engine, Connection)): url = cfg.engine.url else: url = cfg.db.url backend = url.get_backend_name() if backend in self.fns: return self.fns[backend](cfg, *arg, **kw) else: return self.fns["*"](cfg, *arg, **kw) def create_follower_db(follower_ident): for cfg in _configs_for_db_operation(): log.info("CREATE database %s, URI %r", follower_ident, cfg.db.url) create_db(cfg, cfg.db, follower_ident) def setup_config(db_url, options, file_config, follower_ident): # load the dialect, which should also have it set up its provision # hooks dialect = sa_url.make_url(db_url).get_dialect() dialect.load_provisioning() if follower_ident: db_url = follower_url_from_main(db_url, follower_ident) db_opts = {} update_db_opts(db_url, db_opts, options) db_opts["scope"] = "global" eng = engines.testing_engine(db_url, db_opts) post_configure_engine(db_url, eng, follower_ident) eng.connect().close() cfg = config.Config.register(eng, db_opts, options, file_config) # a symbolic name that tests can use if they need to disambiguate # names across databases if follower_ident: config.ident = follower_ident if follower_ident: configure_follower(cfg, follower_ident) return cfg def drop_follower_db(follower_ident): for cfg in _configs_for_db_operation(): log.info("DROP database %s, URI %r", follower_ident, cfg.db.url) drop_db(cfg, cfg.db, follower_ident) def generate_db_urls(db_urls, extra_drivers): """Generate a set of URLs to test given configured URLs plus additional driver names. Given: .. sourcecode:: text --dburi postgresql://db1 \ --dburi postgresql://db2 \ --dburi postgresql://db2 \ --dbdriver=psycopg2 --dbdriver=asyncpg Noting that the default postgresql driver is psycopg2, the output would be: .. sourcecode:: text postgresql+psycopg2://db1 postgresql+asyncpg://db1 postgresql+psycopg2://db2 postgresql+psycopg2://db3 That is, for the driver in a --dburi, we want to keep that and use that driver for each URL it's part of . For a driver that is only in --dbdrivers, we want to use it just once for one of the URLs. for a driver that is both coming from --dburi as well as --dbdrivers, we want to keep it in that dburi. Driver specific query options can be specified by added them to the driver name. For example, to a sample option the asyncpg: .. sourcecode:: text --dburi postgresql://db1 \ --dbdriver=asyncpg?some_option=a_value """ urls = set() backend_to_driver_we_already_have = collections.defaultdict(set) urls_plus_dialects = [ (url_obj, url_obj.get_dialect()) for url_obj in [sa_url.make_url(db_url) for db_url in db_urls] ] for url_obj, dialect in urls_plus_dialects: # use get_driver_name instead of dialect.driver to account for # "_async" virtual drivers like oracledb and psycopg driver_name = url_obj.get_driver_name() backend_to_driver_we_already_have[dialect.name].add(driver_name) backend_to_driver_we_need = {} for url_obj, dialect in urls_plus_dialects: backend = dialect.name dialect.load_provisioning() if backend not in backend_to_driver_we_need: backend_to_driver_we_need[backend] = extra_per_backend = set( extra_drivers ).difference(backend_to_driver_we_already_have[backend]) else: extra_per_backend = backend_to_driver_we_need[backend] for driver_url in _generate_driver_urls(url_obj, extra_per_backend): if driver_url in urls: continue urls.add(driver_url) yield driver_url def _generate_driver_urls(url, extra_drivers): main_driver = url.get_driver_name() extra_drivers.discard(main_driver) url = generate_driver_url(url, main_driver, "") yield url for drv in list(extra_drivers): if "?" in drv: driver_only, query_str = drv.split("?", 1) else: driver_only = drv query_str = None new_url = generate_driver_url(url, driver_only, query_str) if new_url: extra_drivers.remove(drv) yield new_url @register.init def is_preferred_driver(cfg, engine): """Return True if the engine's URL is on the "default" driver, or more generally the "preferred" driver to use for tests. Backends can override this to make a different driver the "prefeferred" driver that's not the default. """ return ( engine.url._get_entrypoint() is engine.url.set( drivername=engine.url.get_backend_name() )._get_entrypoint() ) @register.init def generate_driver_url(url, driver, query_str): backend = url.get_backend_name() new_url = url.set( drivername="%s+%s" % (backend, driver), ) if query_str: new_url = new_url.update_query_string(query_str) try: new_url.get_dialect() except exc.NoSuchModuleError: return None else: return new_url def _configs_for_db_operation(): hosts = set() for cfg in config.Config.all_configs(): cfg.db.dispose() for cfg in config.Config.all_configs(): url = cfg.db.url backend = url.get_backend_name() host_conf = (backend, url.username, url.host, url.database) if host_conf not in hosts: yield cfg hosts.add(host_conf) for cfg in config.Config.all_configs(): cfg.db.dispose() @register.init def drop_all_schema_objects_pre_tables(cfg, eng): pass @register.init def drop_all_schema_objects_post_tables(cfg, eng): pass def drop_all_schema_objects(cfg, eng): drop_all_schema_objects_pre_tables(cfg, eng) drop_views(cfg, eng) if config.requirements.materialized_views.enabled: drop_materialized_views(cfg, eng) inspector = inspect(eng) consider_schemas = (None,) if config.requirements.schemas.enabled_for_config(cfg): consider_schemas += (cfg.test_schema, cfg.test_schema_2) util.drop_all_tables(eng, inspector, consider_schemas=consider_schemas) drop_all_schema_objects_post_tables(cfg, eng) if config.requirements.sequences.enabled_for_config(cfg): with eng.begin() as conn: for seq in inspector.get_sequence_names(): conn.execute(ddl.DropSequence(schema.Sequence(seq))) if config.requirements.schemas.enabled_for_config(cfg): for schema_name in [cfg.test_schema, cfg.test_schema_2]: for seq in inspector.get_sequence_names( schema=schema_name ): conn.execute( ddl.DropSequence( schema.Sequence(seq, schema=schema_name) ) ) def drop_views(cfg, eng): inspector = inspect(eng) try: view_names = inspector.get_view_names() except NotImplementedError: pass else: with eng.begin() as conn: for vname in view_names: conn.execute( ddl.DropView(schema.Table(vname, schema.MetaData())) ) if config.requirements.schemas.enabled_for_config(cfg): try: view_names = inspector.get_view_names(schema=cfg.test_schema) except NotImplementedError: pass else: with eng.begin() as conn: for vname in view_names: conn.execute( ddl.DropView( schema.Table( vname, schema.MetaData(), schema=cfg.test_schema, ) ) ) def drop_materialized_views(cfg, eng): inspector = inspect(eng) mview_names = inspector.get_materialized_view_names() with eng.begin() as conn: for vname in mview_names: conn.exec_driver_sql(f"DROP MATERIALIZED VIEW {vname}") if config.requirements.schemas.enabled_for_config(cfg): mview_names = inspector.get_materialized_view_names( schema=cfg.test_schema ) with eng.begin() as conn: for vname in mview_names: conn.exec_driver_sql( f"DROP MATERIALIZED VIEW {cfg.test_schema}.{vname}" ) @register.init def create_db(cfg, eng, ident): """Dynamically create a database for testing. Used when a test run will employ multiple processes, e.g., when run via `tox` or `pytest -n4`. """ raise NotImplementedError( "no DB creation routine for cfg: %s" % (eng.url,) ) @register.init def drop_db(cfg, eng, ident): """Drop a database that we dynamically created for testing.""" raise NotImplementedError("no DB drop routine for cfg: %s" % (eng.url,)) def _adapt_update_db_opts(fn): insp = util.inspect_getfullargspec(fn) if len(insp.args) == 3: return fn else: return lambda db_url, db_opts, _options: fn(db_url, db_opts) @register.init_decorator(_adapt_update_db_opts) def update_db_opts(db_url, db_opts, options): """Set database options (db_opts) for a test database that we created.""" @register.init def post_configure_engine(url, engine, follower_ident): """Perform extra steps after configuring the main engine for testing. (For the internal dialects, currently only used by sqlite, oracle, mssql) """ @register.init def post_configure_testing_engine(url, engine, options, scope): """perform extra steps after configuring any engine within the testing_engine() function. this includes the main engine as well as most ad-hoc testing engines. steps here should not get in the way of test cases that are looking for events, etc. """ @register.init def follower_url_from_main(url, ident): """Create a connection URL for a dynamically-created test database. :param url: the connection URL specified when the test run was invoked :param ident: the pytest-xdist "worker identifier" to be used as the database name """ url = sa_url.make_url(url) return url.set(database=ident) @register.init def configure_follower(cfg, ident): """Create dialect-specific config settings for a follower database.""" pass @register.init def run_reap_dbs(url, ident): """Remove databases that were created during the test process, after the process has ended. This is an optional step that is invoked for certain backends that do not reliably release locks on the database as long as a process is still in use. For the internal dialects, this is currently only necessary for mssql and oracle. """ def reap_dbs(idents_file): log.info("Reaping databases...") urls = collections.defaultdict(set) idents = collections.defaultdict(set) dialects = {} with open(idents_file) as file_: for line in file_: line = line.strip() db_name, db_url = line.split(" ") url_obj = sa_url.make_url(db_url) if db_name not in dialects: dialects[db_name] = url_obj.get_dialect() dialects[db_name].load_provisioning() url_key = (url_obj.get_backend_name(), url_obj.host) urls[url_key].add(db_url) idents[url_key].add(db_name) for url_key in urls: url = list(urls[url_key])[0] ident = idents[url_key] run_reap_dbs(url, ident) @register.init def temp_table_keyword_args(cfg, eng): """Specify keyword arguments for creating a temporary Table. Dialect-specific implementations of this method will return the kwargs that are passed to the Table method when creating a temporary table for testing, e.g., in the define_temp_tables method of the ComponentReflectionTest class in suite/test_reflection.py """ raise NotImplementedError( "no temp table keyword args routine for cfg: %s" % (eng.url,) ) @register.init def prepare_for_drop_tables(config, connection): pass @register.init def stop_test_class_outside_fixtures(config, db, testcls): pass @register.init def get_temp_table_name(cfg, eng, base_name): """Specify table name for creating a temporary Table. Dialect-specific implementations of this method will return the name to use when creating a temporary table for testing, e.g., in the define_temp_tables method of the ComponentReflectionTest class in suite/test_reflection.py Default to just the base name since that's what most dialects will use. The mssql dialect's implementation will need a "#" prepended. """ return base_name @register.init def set_default_schema_on_connection(cfg, dbapi_connection, schema_name): raise NotImplementedError( "backend does not implement a schema name set function: %s" % (cfg.db.url,) ) @register.init def upsert( cfg, table, returning, *, set_lambda=None, sort_by_parameter_order=False ): """return the backends insert..on conflict / on dupe etc. construct. while we should add a backend-neutral upsert construct as well, such as insert().upsert(), it's important that we continue to test the backend-specific insert() constructs since if we do implement insert().upsert(), that would be using a different codepath for the things we need to test like insertmanyvalues, etc. """ raise NotImplementedError( f"backend does not include an upsert implementation: {cfg.db.url}" ) @register.init def normalize_sequence(cfg, sequence): """Normalize sequence parameters for dialect that don't start with 1 by default. The default implementation does nothing """ return sequence @register.init def allow_stale_update_impl(cfg): return contextlib.nullcontext() @decorator def allow_stale_updates(fn, *arg, **kw): """decorator around a test function that indicates the test will be UPDATING rows that have been read and are now stale. This normally doesn't require intervention except for mariadb 12 which now raises its own error for that, and we want to turn off that setting just within the scope of the test that needs it to be turned off (i.e. ORM stale version tests) """ with allow_stale_update_impl(config._current): return fn(*arg, **kw) @register.init def delete_from_all_tables(connection, cfg, metadata): """an absolutely foolproof delete from all tables routine. dialects should override this to add special instructions like disable constraints etc. """ savepoints = getattr(cfg.requirements, "savepoints", False) if savepoints: savepoints = savepoints.enabled inspector = inspect(connection) for table in reversed( [ t for (t, fks) in sort_tables_and_constraints( metadata.tables.values() ) if t is not None # remember that inspector.get_table_names() is cached, # so this emits SQL once per unique schema name and t.name in inspector.get_table_names(schema=t.schema) ] ): if savepoints: with connection.begin_nested(): connection.execute(table.delete()) else: connection.execute(table.delete())
register
python
pypa__packaging
tests/test_metadata.py
{ "start": 10761, "end": 31352 }
class ____: def _invalid_with_cause( self, meta: metadata.Metadata, attr: str, cause: type[BaseException] | None = None, *, field: str | None = None, ) -> None: if field is None: field = attr with pytest.raises(metadata.InvalidMetadata) as exc_info: getattr(meta, attr) exc = exc_info.value assert exc.field == field if cause is None: assert exc.__cause__ is None else: assert isinstance(exc.__cause__, cause) def test_from_email(self) -> None: metadata_version = "2.5" meta = metadata.Metadata.from_email( f"Metadata-Version: {metadata_version}", validate=False ) assert meta.metadata_version == metadata_version assert meta.import_names is None def test_from_email_empty_import_name(self) -> None: meta = metadata.Metadata.from_email( "Metadata-Version: 2.5\nImport-Name:\n", validate=False ) assert meta.import_names == [] def test_from_email_unparsed(self) -> None: with pytest.raises(ExceptionGroup) as exc_info: metadata.Metadata.from_email("Hello: PyPA") assert len(exc_info.value.exceptions) == 1 assert isinstance(exc_info.value.exceptions[0], metadata.InvalidMetadata) def test_from_email_validate(self) -> None: with pytest.raises(ExceptionGroup): # Lacking all required fields. metadata.Metadata.from_email("Name: packaging", validate=True) def test_from_email_unparsed_valid_field_name(self) -> None: with pytest.raises(ExceptionGroup): metadata.Metadata.from_email( "Project-URL: A, B\nProject-URL: A, C", validate=True ) def test_required_fields(self) -> None: meta = metadata.Metadata.from_raw(_RAW_EXAMPLE) assert meta.metadata_version == _RAW_EXAMPLE["metadata_version"] @pytest.mark.parametrize("field", list(_RAW_EXAMPLE.keys())) def test_required_fields_missing(self, field: str) -> None: required_fields = _RAW_EXAMPLE.copy() del required_fields[field] # type: ignore[misc] with pytest.raises(ExceptionGroup): metadata.Metadata.from_raw(required_fields) def test_raw_validate_unrecognized_field(self) -> None: raw: RawMetadata = { "metadata_version": "2.3", "name": "packaging", "version": "2023.0.0", } # Safety check (always true) assert metadata.Metadata.from_raw(raw, validate=True) # type: ignore[truthy-bool] # Misspelled; missing an "i": raw["dynamc"] = ["Obsoletes-Dist"] # type: ignore[typeddict-unknown-key] with pytest.raises(ExceptionGroup): metadata.Metadata.from_raw(raw, validate=True) def test_raw_data_not_mutated(self) -> None: raw = _RAW_EXAMPLE.copy() meta = metadata.Metadata.from_raw(raw, validate=True) assert meta.version == version.Version(_RAW_EXAMPLE["version"]) assert raw == _RAW_EXAMPLE def test_caching(self) -> None: meta = metadata.Metadata.from_raw(_RAW_EXAMPLE, validate=True) assert meta.version is meta.version def test_from_raw_validate(self) -> None: required_fields = _RAW_EXAMPLE.copy() required_fields["version"] = "-----" with pytest.raises(ExceptionGroup): # Multiple things to trigger a validation error: # invalid version, missing keys, etc. metadata.Metadata.from_raw(required_fields) @pytest.mark.parametrize("meta_version", ["2.2", "2.3"]) def test_metadata_version_field_introduction(self, meta_version: str) -> None: raw: RawMetadata = { "metadata_version": meta_version, "name": "packaging", "version": "2023.0.0", "dynamic": ["Obsoletes-Dist"], # Introduced in 2.2. } assert metadata.Metadata.from_raw(raw, validate=True) # type: ignore[truthy-bool] @pytest.mark.parametrize("meta_version", ["1.0", "1.1", "1.2", "2.1"]) def test_metadata_version_field_introduction_mismatch( self, meta_version: str ) -> None: raw: RawMetadata = { "metadata_version": meta_version, "name": "packaging", "version": "2023.0.0", "dynamic": ["Obsoletes-Dist"], # Introduced in 2.2. } with pytest.raises(ExceptionGroup): metadata.Metadata.from_raw(raw, validate=True) @pytest.mark.parametrize( "attribute", [ "description", "home_page", "download_url", "author", "author_email", "maintainer", "maintainer_email", "license", ], ) def test_single_value_unvalidated_attribute(self, attribute: str) -> None: value = "Not important" meta = metadata.Metadata.from_raw({attribute: value}, validate=False) # type: ignore[misc] assert getattr(meta, attribute) == value @pytest.mark.parametrize( "attribute", [ "supported_platforms", "platforms", "classifiers", "provides_dist", "obsoletes_dist", "requires", "provides", "obsoletes", ], ) def test_multi_value_unvalidated_attribute(self, attribute: str) -> None: values = ["Not important", "Still not important"] meta = metadata.Metadata.from_raw({attribute: values}, validate=False) # type: ignore[misc] assert getattr(meta, attribute) == values @pytest.mark.parametrize("version", ["1.0", "1.1", "1.2", "2.1", "2.2", "2.3"]) def test_valid_metadata_version(self, version: str) -> None: meta = metadata.Metadata.from_raw({"metadata_version": version}, validate=False) assert meta.metadata_version == version @pytest.mark.parametrize("version", ["1.3", "2.0"]) def test_invalid_metadata_version(self, version: str) -> None: meta = metadata.Metadata.from_raw({"metadata_version": version}, validate=False) with pytest.raises(metadata.InvalidMetadata): meta.metadata_version # noqa: B018 def test_valid_version(self) -> None: version_str = "1.2.3" meta = metadata.Metadata.from_raw({"version": version_str}, validate=False) assert meta.version == version.parse(version_str) def test_missing_version(self) -> None: meta = metadata.Metadata.from_raw({}, validate=False) with pytest.raises(metadata.InvalidMetadata) as exc_info: meta.version # noqa: B018 assert exc_info.value.field == "version" def test_invalid_version(self) -> None: meta = metadata.Metadata.from_raw({"version": "a.b.c"}, validate=False) self._invalid_with_cause(meta, "version", version.InvalidVersion) def test_valid_summary(self) -> None: summary = "Hello" meta = metadata.Metadata.from_raw({"summary": summary}, validate=False) assert meta.summary == summary def test_invalid_summary(self) -> None: meta = metadata.Metadata.from_raw( {"summary": "Hello\n Again"}, validate=False ) with pytest.raises(metadata.InvalidMetadata) as exc_info: meta.summary # noqa: B018 assert exc_info.value.field == "summary" def test_valid_name(self) -> None: name = "Hello_World" meta = metadata.Metadata.from_raw({"name": name}, validate=False) assert meta.name == name def test_invalid_name(self) -> None: meta = metadata.Metadata.from_raw({"name": "-not-legal"}, validate=False) self._invalid_with_cause(meta, "name", utils.InvalidName) @pytest.mark.parametrize( "content_type", [ "text/plain", "TEXT/PLAIN", "text/x-rst", "text/markdown", "text/plain; charset=UTF-8", "text/x-rst; charset=UTF-8", "text/markdown; charset=UTF-8; variant=GFM", "text/markdown; charset=UTF-8; variant=CommonMark", "text/markdown; variant=GFM", "text/markdown; variant=CommonMark", ], ) def test_valid_description_content_type(self, content_type: str) -> None: meta = metadata.Metadata.from_raw( {"description_content_type": content_type}, validate=False ) assert meta.description_content_type == content_type @pytest.mark.parametrize( "content_type", [ "application/json", "text/plain; charset=ascii", "text/plain; charset=utf-8", "text/markdown; variant=gfm", "text/markdown; variant=commonmark", ], ) def test_invalid_description_content_type(self, content_type: str) -> None: meta = metadata.Metadata.from_raw( {"description_content_type": content_type}, validate=False ) with pytest.raises(metadata.InvalidMetadata): meta.description_content_type # noqa: B018 def test_keywords(self) -> None: keywords = ["hello", "world"] meta = metadata.Metadata.from_raw({"keywords": keywords}, validate=False) assert meta.keywords == keywords def test_valid_project_urls(self) -> None: urls = { "Documentation": "https://example.com/BeagleVote", "Bug Tracker": "http://bitbucket.org/tarek/distribute/issues/", } meta = metadata.Metadata.from_raw({"project_urls": urls}, validate=False) assert meta.project_urls == urls @pytest.mark.parametrize("specifier", [">=3", ">2.6,!=3.0.*,!=3.1.*", "~=2.6"]) def test_valid_requires_python(self, specifier: str) -> None: expected = specifiers.SpecifierSet(specifier) meta = metadata.Metadata.from_raw( {"requires_python": specifier}, validate=False ) assert meta.requires_python == expected def test_invalid_requires_python(self) -> None: meta = metadata.Metadata.from_raw( {"requires_python": "NotReal"}, validate=False ) self._invalid_with_cause( meta, "requires_python", specifiers.InvalidSpecifier, field="requires-python", ) def test_requires_external(self) -> None: externals = [ "C", "libpng (>=1.5)", 'make; sys_platform != "win32"', "libjpeg (>6b)", ] meta = metadata.Metadata.from_raw( {"requires_external": externals}, validate=False ) assert meta.requires_external == externals def test_valid_provides_extra(self) -> None: extras = ["dev", "test"] meta = metadata.Metadata.from_raw({"provides_extra": extras}, validate=False) assert meta.provides_extra == extras def test_invalid_provides_extra(self) -> None: extras = ["pdf", "-Not-Valid", "ok"] meta = metadata.Metadata.from_raw({"provides_extra": extras}, validate=False) self._invalid_with_cause( meta, "provides_extra", utils.InvalidName, field="provides-extra" ) def test_valid_requires_dist(self) -> None: requires = [ "pkginfo", "PasteDeploy", "zope.interface (>3.5.0)", "pywin32 >1.0; sys_platform == 'win32'", ] expected_requires = list(map(requirements.Requirement, requires)) meta = metadata.Metadata.from_raw({"requires_dist": requires}, validate=False) assert meta.requires_dist == expected_requires def test_invalid_requires_dist(self) -> None: requires = ["pkginfo", "-not-real", "zope.interface (>3.5.0)"] meta = metadata.Metadata.from_raw({"requires_dist": requires}, validate=False) self._invalid_with_cause( meta, "requires_dist", requirements.InvalidRequirement, field="requires-dist", ) def test_valid_dynamic(self) -> None: dynamic = ["Keywords", "Home-Page", "Author"] meta = metadata.Metadata.from_raw({"dynamic": dynamic}, validate=False) assert meta.dynamic == [d.lower() for d in dynamic] def test_invalid_dynamic_value(self) -> None: dynamic = ["Keywords", "NotReal", "Author"] meta = metadata.Metadata.from_raw({"dynamic": dynamic}, validate=False) with pytest.raises(metadata.InvalidMetadata): meta.dynamic # noqa: B018 @pytest.mark.parametrize("field_name", ["name", "version", "metadata-version"]) def test_disallowed_dynamic(self, field_name: str) -> None: meta = metadata.Metadata.from_raw({"dynamic": [field_name]}, validate=False) message = f"{field_name!r} is not allowed" with pytest.raises(metadata.InvalidMetadata, match=message) as execinfo: meta.dynamic # noqa: B018 # The name of the specific offending field should be used, # not a list with all fields: assert "[" not in str(execinfo.value) @pytest.mark.parametrize( "field_name", sorted(metadata._RAW_TO_EMAIL_MAPPING.keys() - metadata._REQUIRED_ATTRS), ) def test_optional_defaults_to_none(self, field_name: str) -> None: meta = metadata.Metadata.from_raw({}, validate=False) assert getattr(meta, field_name) is None @pytest.mark.parametrize( ("license_expression", "expected"), [ ("MIT", "MIT"), ("mit", "MIT"), ("BSD-3-Clause", "BSD-3-Clause"), ("Bsd-3-clause", "BSD-3-Clause"), ( "MIT AND (Apache-2.0 OR BSD-2-Clause)", "MIT AND (Apache-2.0 OR BSD-2-Clause)", ), ( "mit and (apache-2.0 or bsd-2-clause)", "MIT AND (Apache-2.0 OR BSD-2-Clause)", ), ( "MIT OR GPL-2.0-or-later OR (FSFUL AND BSD-2-Clause)", "MIT OR GPL-2.0-or-later OR (FSFUL AND BSD-2-Clause)", ), ( "GPL-3.0-only WITH Classpath-exception-2.0 OR BSD-3-Clause", "GPL-3.0-only WITH Classpath-exception-2.0 OR BSD-3-Clause", ), ( "LicenseRef-Special-License OR CC0-1.0 OR Unlicense", "LicenseRef-Special-License OR CC0-1.0 OR Unlicense", ), ("mIt", "MIT"), (" mIt ", "MIT"), ("mit or apache-2.0", "MIT OR Apache-2.0"), ("mit and apache-2.0", "MIT AND Apache-2.0"), ( "gpl-2.0-or-later with bison-exception-2.2", "GPL-2.0-or-later WITH Bison-exception-2.2", ), ( "mit or apache-2.0 and (bsd-3-clause or mpl-2.0)", "MIT OR Apache-2.0 AND (BSD-3-Clause OR MPL-2.0)", ), ("mit and (apache-2.0+ or mpl-2.0+)", "MIT AND (Apache-2.0+ OR MPL-2.0+)"), ( "mit and ( apache-2.0+ or mpl-2.0+ )", "MIT AND (Apache-2.0+ OR MPL-2.0+)", ), # Valid non-SPDX values ("LicenseRef-Public-Domain", "LicenseRef-Public-Domain"), ("licenseref-public-domain", "LicenseRef-public-domain"), ("licenseref-proprietary", "LicenseRef-proprietary"), ("LicenseRef-Proprietary", "LicenseRef-Proprietary"), ("LicenseRef-Beerware-4.2", "LicenseRef-Beerware-4.2"), ("licenseref-beerware-4.2", "LicenseRef-beerware-4.2"), ( "(LicenseRef-Special-License OR LicenseRef-OtherLicense) OR Unlicense", "(LicenseRef-Special-License OR LicenseRef-OtherLicense) OR Unlicense", ), ( "(LicenseRef-Special-License OR licenseref-OtherLicense) OR unlicense", "(LicenseRef-Special-License OR LicenseRef-OtherLicense) OR Unlicense", ), # we don't canonicalize redundant parens, instead leaving them as-is # in the license expression. ("(MIT)", "(MIT)"), ("((MIT))", "((MIT))"), ("(( MIT ))", "((MIT))"), ("((MIT AND (MIT)))", "((MIT AND (MIT)))"), ], ) def test_valid_license_expression( self, license_expression: str, expected: str ) -> None: meta = metadata.Metadata.from_raw( {"license_expression": license_expression}, validate=False ) assert meta.license_expression == expected @pytest.mark.parametrize( "license_expression", [ "", "Use-it-after-midnight", "LicenseRef-License with spaces", "LicenseRef-License_with_underscores", "or", "and", "with", "mit or", "mit and", "mit with", "or mit", "and mit", "with mit", "(mit", "mit)", ") mit", "mit (", "mit or or apache-2.0", # Missing an operator before `(`. "mit or apache-2.0 (bsd-3-clause and MPL-2.0)", # "2-BSD-Clause is not a valid license. "Apache-2.0 OR 2-BSD-Clause", # Empty parenthesis. "()", "( ) or mit", "mit and ( )", "( ) or mit and ( )", "( ) with ( ) or mit", "mit with ( ) with ( ) or mit", ], ) def test_invalid_license_expression(self, license_expression: str) -> None: meta = metadata.Metadata.from_raw( {"license_expression": license_expression}, validate=False ) with pytest.raises(metadata.InvalidMetadata): meta.license_expression # noqa: B018 @pytest.mark.parametrize( "license_files", [ [], ["licenses/LICENSE.MIT", "licenses/LICENSE.CC0"], ["LICENSE"], ], ) def test_valid_license_files(self, license_files: list[str]) -> None: meta = metadata.Metadata.from_raw( {"license_files": license_files}, validate=False ) assert meta.license_files == license_files @pytest.mark.parametrize( "license_files", [ # Can't escape out of the project's directory. ["../LICENSE"], ["./../LICENSE"], # Paths should be resolved. ["licenses/../LICENSE"], # Absolute paths are not allowed. ["/licenses/LICENSE"], # Paths must be valid # (i.e. glob pattern didn't escape out of pyproject.toml.) ["licenses/*"], # Paths must use / delimiter ["licenses\\LICENSE"], ], ) def test_invalid_license_files(self, license_files: list[str]) -> None: meta = metadata.Metadata.from_raw( {"license_files": license_files}, validate=False ) with pytest.raises(metadata.InvalidMetadata): meta.license_files # noqa: B018 @pytest.mark.parametrize("key", ["import_namespaces", "import_names"]) def test_valid_import_names(self, key: str) -> None: import_names = [ "packaging", "packaging.metadata", "_utils ; private", "_stuff;private", ] meta = metadata.Metadata.from_raw({key: import_names}, validate=False) # type: ignore[misc] assert getattr(meta, key) == import_names @pytest.mark.parametrize("key", ["import_namespaces", "import_names"]) @pytest.mark.parametrize( "name", ["not-valid", "still.not-valid", "stuff;", "stuff; extra"] ) def test_invalid_import_names_identifier(self, key: str, name: str) -> None: meta = metadata.Metadata.from_raw({key: [name]}, validate=False) # type: ignore[misc] with pytest.raises(metadata.InvalidMetadata): getattr(meta, key) @pytest.mark.parametrize("key", ["import_namespaces", "import_names"]) def test_invalid_import_names_keyword(self, key: str) -> None: import_names = ["class"] meta = metadata.Metadata.from_raw({key: import_names}, validate=False) # type: ignore[misc] with pytest.raises(metadata.InvalidMetadata): getattr(meta, key)
TestMetadata
python
scrapy__scrapy
tests/AsyncCrawlerProcess/twisted_reactor_asyncio.py
{ "start": 63, "end": 328 }
class ____(scrapy.Spider): name = "asyncio_reactor" process = AsyncCrawlerProcess( settings={ "TWISTED_REACTOR": "twisted.internet.asyncioreactor.AsyncioSelectorReactor", } ) process.crawl(AsyncioReactorSpider) process.start()
AsyncioReactorSpider
python
ray-project__ray
python/ray/actor.py
{ "start": 2520, "end": 2710 }
class ____(Generic[_Ret, _T0]): def remote(self, __arg0: "Union[_T0, ObjectRef[_T0]]") -> "ObjectRef[_Ret]": ... def bind(self, __arg0: _T0) -> Any: ...
_RemoteMethod0
python
pdm-project__pdm
src/pdm/cli/commands/venv/utils.py
{ "start": 1828, "end": 2652 }
class ____(BaseProvider): """A Python provider for project venv pythons""" def __init__(self, project: Project) -> None: self.project = project @classmethod def create(cls) -> t.Self | None: return None def find_pythons(self) -> t.Iterable[PythonVersion]: for _, venv in iter_venvs(self.project): yield PythonVersion(venv.interpreter, _interpreter=venv.interpreter, keep_symlink=True) def get_venv_with_name(project: Project, name: str) -> VirtualEnv: all_venvs = dict(iter_venvs(project)) try: return all_venvs[name] except KeyError: raise PdmUsageError( f"No virtualenv with key '{name}' is found, must be one of {list(all_venvs)}.\n" "You can create one with 'pdm venv create'.", ) from None
VenvProvider
python
euske__pdfminer
pdfminer/cmapdb.py
{ "start": 738, "end": 1173 }
class ____: debug = 0 def __init__(self, **kwargs): self.attrs = kwargs.copy() return def is_vertical(self): return self.attrs.get('WMode', 0) != 0 def set_attr(self, k, v): self.attrs[k] = v return def add_code2cid(self, code, cid): return def add_cid2unichr(self, cid, code): return def use_cmap(self, cmap): return ## CMap ##
CMapBase
python
networkx__networkx
networkx/readwrite/tests/test_adjlist.py
{ "start": 2711, "end": 7601 }
class ____: @classmethod def setup_class(cls): cls.G = nx.Graph(name="test") e = [("a", "b"), ("b", "c"), ("c", "d"), ("d", "e"), ("e", "f"), ("a", "f")] cls.G.add_edges_from(e) cls.G.add_node("g") cls.DG = nx.DiGraph(cls.G) cls.XG = nx.MultiGraph() cls.XG.add_weighted_edges_from([(1, 2, 5), (1, 2, 5), (1, 2, 1), (3, 3, 42)]) cls.XDG = nx.MultiDiGraph(cls.XG) def test_read_multiline_adjlist_1(self): # Unit test for https://networkx.lanl.gov/trac/ticket/252 s = b"""# comment line 1 2 # comment line 2 3 """ bytesIO = io.BytesIO(s) G = nx.read_multiline_adjlist(bytesIO) adj = {"1": {"3": {}, "2": {}}, "3": {"1": {}}, "2": {"1": {}}} assert graphs_equal(G, nx.Graph(adj)) def test_unicode(self, tmp_path): G = nx.Graph() name1 = chr(2344) + chr(123) + chr(6543) name2 = chr(5543) + chr(1543) + chr(324) G.add_edge(name1, "Radiohead", **{name2: 3}) fname = tmp_path / "adjlist.txt" nx.write_multiline_adjlist(G, fname) H = nx.read_multiline_adjlist(fname) assert graphs_equal(G, H) def test_latin1_err(self, tmp_path): G = nx.Graph() name1 = chr(2344) + chr(123) + chr(6543) name2 = chr(5543) + chr(1543) + chr(324) G.add_edge(name1, "Radiohead", **{name2: 3}) fname = tmp_path / "adjlist.txt" with pytest.raises(UnicodeEncodeError): nx.write_multiline_adjlist(G, fname, encoding="latin-1") def test_latin1(self, tmp_path): G = nx.Graph() name1 = "Bj" + chr(246) + "rk" name2 = chr(220) + "ber" G.add_edge(name1, "Radiohead", **{name2: 3}) fname = tmp_path / "adjlist.txt" nx.write_multiline_adjlist(G, fname, encoding="latin-1") H = nx.read_multiline_adjlist(fname, encoding="latin-1") assert graphs_equal(G, H) def test_parse_adjlist(self): lines = ["1 2 5", "2 3 4", "3 5", "4", "5"] nx.parse_adjlist(lines, nodetype=int) # smoke test with pytest.raises(TypeError): nx.parse_adjlist(lines, nodetype="int") lines = ["1 2 5", "2 b", "c"] with pytest.raises(TypeError): nx.parse_adjlist(lines, nodetype=int) def test_adjlist_graph(self, tmp_path): G = self.G fname = tmp_path / "adjlist.txt" nx.write_adjlist(G, fname) H = nx.read_adjlist(fname) H2 = nx.read_adjlist(fname) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges())) def test_adjlist_digraph(self, tmp_path): G = self.DG fname = tmp_path / "adjlist.txt" nx.write_adjlist(G, fname) H = nx.read_adjlist(fname, create_using=nx.DiGraph()) H2 = nx.read_adjlist(fname, create_using=nx.DiGraph()) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()), directed=True) def test_adjlist_integers(self, tmp_path): fname = tmp_path / "adjlist.txt" G = nx.convert_node_labels_to_integers(self.G) nx.write_adjlist(G, fname) H = nx.read_adjlist(fname, nodetype=int) H2 = nx.read_adjlist(fname, nodetype=int) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges())) def test_adjlist_multigraph(self, tmp_path): G = self.XG fname = tmp_path / "adjlist.txt" nx.write_adjlist(G, fname) H = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiGraph()) H2 = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiGraph()) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges())) def test_adjlist_multidigraph(self, tmp_path): G = self.XDG fname = tmp_path / "adjlist.txt" nx.write_adjlist(G, fname) H = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiDiGraph()) H2 = nx.read_adjlist(fname, nodetype=int, create_using=nx.MultiDiGraph()) assert H is not H2 # they should be different graphs assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()), directed=True) def test_adjlist_delimiter(self): fh = io.BytesIO() G = nx.path_graph(3) nx.write_adjlist(G, fh, delimiter=":") fh.seek(0) H = nx.read_adjlist(fh, nodetype=int, delimiter=":") assert nodes_equal(list(H), list(G)) assert edges_equal(list(H.edges()), list(G.edges()))
TestAdjlist
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/torch_entities/networks.py
{ "start": 22493, "end": 27653 }
class ____(nn.Module, Actor): MODEL_EXPORT_VERSION = 3 # Corresponds to ModelApiVersion.MLAgents2_0 def __init__( self, observation_specs: List[ObservationSpec], network_settings: NetworkSettings, action_spec: ActionSpec, conditional_sigma: bool = False, tanh_squash: bool = False, ): super().__init__() self.action_spec = action_spec self.version_number = torch.nn.Parameter( torch.Tensor([self.MODEL_EXPORT_VERSION]), requires_grad=False ) self.is_continuous_int_deprecated = torch.nn.Parameter( torch.Tensor([int(self.action_spec.is_continuous())]), requires_grad=False ) self.continuous_act_size_vector = torch.nn.Parameter( torch.Tensor([int(self.action_spec.continuous_size)]), requires_grad=False ) self.discrete_act_size_vector = torch.nn.Parameter( torch.Tensor([self.action_spec.discrete_branches]), requires_grad=False ) self.act_size_vector_deprecated = torch.nn.Parameter( torch.Tensor( [ self.action_spec.continuous_size + sum(self.action_spec.discrete_branches) ] ), requires_grad=False, ) self.network_body = NetworkBody(observation_specs, network_settings) if network_settings.memory is not None: self.encoding_size = network_settings.memory.memory_size // 2 else: self.encoding_size = network_settings.hidden_units self.memory_size_vector = torch.nn.Parameter( torch.Tensor([int(self.network_body.memory_size)]), requires_grad=False ) self.action_model = ActionModel( self.encoding_size, action_spec, conditional_sigma=conditional_sigma, tanh_squash=tanh_squash, deterministic=network_settings.deterministic, ) @property def memory_size(self) -> int: return self.network_body.memory_size def update_normalization(self, buffer: AgentBuffer) -> None: self.network_body.update_normalization(buffer) def get_action_and_stats( self, inputs: List[torch.Tensor], masks: Optional[torch.Tensor] = None, memories: Optional[torch.Tensor] = None, sequence_length: int = 1, ) -> Tuple[AgentAction, Dict[str, Any], torch.Tensor]: encoding, memories = self.network_body( inputs, memories=memories, sequence_length=sequence_length ) action, log_probs, entropies = self.action_model(encoding, masks) run_out = {} # This is the clipped action which is not saved to the buffer # but is exclusively sent to the environment. run_out["env_action"] = action.to_action_tuple( clip=self.action_model.clip_action ) run_out["log_probs"] = log_probs run_out["entropy"] = entropies return action, run_out, memories def get_stats( self, inputs: List[torch.Tensor], actions: AgentAction, masks: Optional[torch.Tensor] = None, memories: Optional[torch.Tensor] = None, sequence_length: int = 1, ) -> Dict[str, Any]: encoding, actor_mem_outs = self.network_body( inputs, memories=memories, sequence_length=sequence_length ) log_probs, entropies = self.action_model.evaluate(encoding, masks, actions) run_out = {} run_out["log_probs"] = log_probs run_out["entropy"] = entropies return run_out def forward( self, inputs: List[torch.Tensor], masks: Optional[torch.Tensor] = None, memories: Optional[torch.Tensor] = None, ) -> Tuple[Union[int, torch.Tensor], ...]: """ Note: This forward() method is required for exporting to ONNX. Don't modify the inputs and outputs. At this moment, torch.onnx.export() doesn't accept None as tensor to be exported, so the size of return tuple varies with action spec. """ encoding, memories_out = self.network_body( inputs, memories=memories, sequence_length=1 ) ( cont_action_out, disc_action_out, action_out_deprecated, deterministic_cont_action_out, deterministic_disc_action_out, ) = self.action_model.get_action_out(encoding, masks) export_out = [self.version_number, self.memory_size_vector] if self.action_spec.continuous_size > 0: export_out += [ cont_action_out, self.continuous_act_size_vector, deterministic_cont_action_out, ] if self.action_spec.discrete_size > 0: export_out += [ disc_action_out, self.discrete_act_size_vector, deterministic_disc_action_out, ] if self.network_body.memory_size > 0: export_out += [memories_out] return tuple(export_out)
SimpleActor
python
pytorch__pytorch
torch/_inductor/pattern_matcher.py
{ "start": 16341, "end": 16632 }
class ____(PatternExpr): """ Capture an arg which will become an input to the handler. Args are passed in depth first order. """ def _match(self, node: NodeOrConstant, ctx: MatchContext) -> MatchResult: return Match(ctx, self, args=[node]) # matches anything
Arg
python
spyder-ide__spyder
spyder/utils/color_system.py
{ "start": 1620, "end": 1997 }
class ____: """ Group colors for light palette. It does not start with B0 because it doesn't use black. """ B10 = '#FF6700' B20 = '#FFB000' B30 = '#FFE600' B40 = '#7FDD05' B50 = '#00A585' B60 = '#22BCF2' B70 = '#1256CC' B80 = '#803AD0' B90 = '#B568F2' B100 = '#CC2782' B110 = '#FF71BF' B120 = '#7EE8C7'
GroupLight
python
ethereum__web3.py
web3/middleware/formatting.py
{ "start": 2763, "end": 7784 }
class ____(Web3MiddlewareBuilder): request_formatters: Formatters = None result_formatters: Formatters = None error_formatters: Formatters = None sync_formatters_builder: SYNC_FORMATTERS_BUILDER = None async_formatters_builder: ASYNC_FORMATTERS_BUILDER = None @staticmethod @curry def build( w3: Union["Web3", "AsyncWeb3[Any]"], # formatters option: request_formatters: Formatters | None = None, result_formatters: Formatters | None = None, error_formatters: Formatters | None = None, # formatters builder option: sync_formatters_builder: SYNC_FORMATTERS_BUILDER | None = None, async_formatters_builder: ASYNC_FORMATTERS_BUILDER | None = None, ) -> "FormattingMiddlewareBuilder": # if not both sync and async formatters are specified, raise error if ( sync_formatters_builder is None and async_formatters_builder is not None ) or (sync_formatters_builder is not None and async_formatters_builder is None): raise Web3ValueError( "Must specify both sync_formatters_builder and async_formatters_builder" ) if sync_formatters_builder is not None and async_formatters_builder is not None: if ( request_formatters is not None or result_formatters is not None or error_formatters is not None ): raise Web3ValueError( "Cannot specify formatters_builder and formatters at the same time" ) middleware = FormattingMiddlewareBuilder(w3) middleware.request_formatters = request_formatters or {} middleware.result_formatters = result_formatters or {} middleware.error_formatters = error_formatters or {} middleware.sync_formatters_builder = sync_formatters_builder middleware.async_formatters_builder = async_formatters_builder return middleware def request_processor(self, method: "RPCEndpoint", params: Any) -> Any: if self.sync_formatters_builder is not None: formatters = merge( FORMATTER_DEFAULTS, self.sync_formatters_builder(cast("Web3", self._w3), method), ) self.request_formatters = formatters.pop("request_formatters") if method in self.request_formatters: formatter = self.request_formatters[method] params = formatter(params) return method, params def response_processor(self, method: RPCEndpoint, response: "RPCResponse") -> Any: if self.sync_formatters_builder is not None: formatters = merge( FORMATTER_DEFAULTS, self.sync_formatters_builder(cast("Web3", self._w3), method), ) self.result_formatters = formatters["result_formatters"] self.error_formatters = formatters["error_formatters"] return _apply_response_formatters( method, self.result_formatters, self.error_formatters, response, ) # -- async -- # async def async_request_processor(self, method: "RPCEndpoint", params: Any) -> Any: if self.async_formatters_builder is not None: formatters = merge( FORMATTER_DEFAULTS, await self.async_formatters_builder( cast("AsyncWeb3[Any]", self._w3), method ), ) self.request_formatters = formatters.pop("request_formatters") if method in self.request_formatters: formatter = self.request_formatters[method] params = formatter(params) return method, params async def async_response_processor( self, method: RPCEndpoint, response: "RPCResponse" ) -> Any: if self.async_formatters_builder is not None: formatters = merge( FORMATTER_DEFAULTS, await self.async_formatters_builder( cast("AsyncWeb3[Any]", self._w3), method ), ) self.result_formatters = formatters["result_formatters"] self.error_formatters = formatters["error_formatters"] if self._w3.provider.has_persistent_connection: # asynchronous response processing provider = cast("PersistentConnectionProvider", self._w3.provider) provider._request_processor.append_middleware_response_processor( response, _apply_response_formatters( method, self.result_formatters, self.error_formatters, ), ) return response else: return _apply_response_formatters( method, self.result_formatters, self.error_formatters, response, )
FormattingMiddlewareBuilder
python
huggingface__transformers
src/transformers/models/clvp/configuration_clvp.py
{ "start": 15038, "end": 19421 }
class ____(PreTrainedConfig): r""" [`ClvpConfig`] is the configuration class to store the configuration of a [`ClvpModelForConditionalGeneration`]. It is used to instantiate a CLVP model according to the specified arguments, defining the text model, speech model and decoder model configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the CLVP [susnato/clvp_dev](https://huggingface.co/susnato/clvp_dev) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: text_config (`dict`, *optional*): Dictionary of configuration options used to initialize the CLVP text encoder. speech_config (`dict`, *optional*): Dictionary of configuration options used to initialize CLVP speech encoder. decoder_config (`dict`, *optional*): Dictionary of configuration options used to initialize [`ClvpDecoderConfig`]. projection_dim (`int`, *optional*, defaults to 768): Dimensionality of text and speech projection layers. logit_scale_init_value (`float`, *optional*, defaults to 2.6592): The initial value of the *logit_scale* parameter. Default is used as per the original CLVP implementation. initializer_factor (`float`, *optional*, defaults to 1.0): A factor for initializing all weight matrices (should be kept to 1.0, used internally for initialization testing). kwargs (*optional*): Dictionary of keyword arguments. Example: ```python >>> from transformers import ClvpConfig, ClvpModelForConditionalGeneration >>> # Initializing a ClvpConfig with susnato/clvp_dev style configuration >>> configuration = ClvpConfig() >>> # Initializing a ClvpModelForConditionalGeneration (with random weights) from the susnato/clvp_dev style configuration >>> model = ClvpModelForConditionalGeneration(configuration) >>> # Accessing the model configuration >>> configuration = model.config >>> # We can also initialize a CLVPConfig from a CLVPTextConfig, CLVPSpeechConfig and a CLVPAutoRegressiveConfig >>> from transformers import ClvpEncoderConfig, ClvpDecoderConfig >>> # Initializing a CLVP text, CLVP speech and CLVP decoder configuration >>> config_text = ClvpEncoderConfig() >>> config_speech = ClvpEncoderConfig() >>> decoder_config = ClvpDecoderConfig() >>> config = ClvpConfig(config_text, config_speech, decoder_config) ```""" model_type = "clvp" sub_configs = { "text_config": ClvpEncoderConfig, "speech_config": ClvpEncoderConfig, "decoder_config": ClvpDecoderConfig, } def __init__( self, text_config=None, speech_config=None, decoder_config=None, projection_dim=768, logit_scale_init_value=2.6592, initializer_factor=1.0, **kwargs, ): if text_config is None: text_config = ClvpEncoderConfig() logger.info("`text_config` is `None`. initializing the `ClvpEncoderConfig` with default values.") elif isinstance(text_config, dict): text_config = ClvpEncoderConfig(**text_config) if speech_config is None: speech_config = ClvpEncoderConfig() logger.info("`speech_config` is `None`. initializing the `ClvpEncoderConfig` with default values.") elif isinstance(speech_config, dict): speech_config = ClvpEncoderConfig(**speech_config) if decoder_config is None: decoder_config = ClvpDecoderConfig() logger.info("`image_config` is `None`. initializing the `ClvpDecoderConfig` with default values.") elif isinstance(decoder_config, dict): decoder_config = ClvpDecoderConfig(**decoder_config) self.text_config = text_config self.speech_config = speech_config self.decoder_config = decoder_config self.projection_dim = projection_dim self.logit_scale_init_value = logit_scale_init_value self.initializer_factor = initializer_factor super().__init__(**kwargs) __all__ = ["ClvpConfig", "ClvpDecoderConfig", "ClvpEncoderConfig"]
ClvpConfig
python
gevent__gevent
src/gevent/tests/test__threading.py
{ "start": 2434, "end": 2586 }
class ____(TestLockThread): def _spawn(self, func): return gevent.spawn(func) if __name__ == '__main__': greentest.main()
TestLockGreenlet
python
pytorch__pytorch
torch/export/graph_signature.py
{ "start": 3448, "end": 3614 }
class ____: gradients_to_parameters: dict[str, str] gradients_to_user_inputs: dict[str, str] loss_output: str @dataclasses.dataclass
ExportBackwardSignature
python
ray-project__ray
python/ray/util/actor_pool.py
{ "start": 195, "end": 14541 }
class ____: """Utility class to operate on a fixed pool of actors. Arguments: actors: List of Ray actor handles to use in this pool. Examples: .. testcode:: import ray from ray.util.actor_pool import ActorPool @ray.remote class Actor: def double(self, v): return 2 * v a1, a2 = Actor.remote(), Actor.remote() pool = ActorPool([a1, a2]) print(list(pool.map(lambda a, v: a.double.remote(v), [1, 2, 3, 4]))) .. testoutput:: [2, 4, 6, 8] """ def __init__(self, actors: list): from ray._common.usage.usage_lib import record_library_usage record_library_usage("util.ActorPool") # actors to be used self._idle_actors = list(actors) # get actor from future self._future_to_actor = {} # get future from index self._index_to_future = {} # next task to do self._next_task_index = 0 # next task to return self._next_return_index = 0 # next work depending when actors free self._pending_submits = [] def map(self, fn: Callable[["ray.actor.ActorHandle", V], Any], values: List[V]): """Apply the given function in parallel over the actors and values. This returns an ordered iterator that will return results of the map as they finish. Note that you must iterate over the iterator to force the computation to finish. Arguments: fn: Function that takes (actor, value) as argument and returns an ObjectRef computing the result over the value. The actor will be considered busy until the ObjectRef completes. values: List of values that fn(actor, value) should be applied to. Returns: Iterator over results from applying fn to the actors and values. Examples: .. testcode:: import ray from ray.util.actor_pool import ActorPool @ray.remote class Actor: def double(self, v): return 2 * v a1, a2 = Actor.remote(), Actor.remote() pool = ActorPool([a1, a2]) print(list(pool.map(lambda a, v: a.double.remote(v), [1, 2, 3, 4]))) .. testoutput:: [2, 4, 6, 8] """ # Ignore/Cancel all the previous submissions # by calling `has_next` and `gen_next` repeteadly. while self.has_next(): try: self.get_next(timeout=0, ignore_if_timedout=True) except TimeoutError: pass for v in values: self.submit(fn, v) def get_generator(): while self.has_next(): yield self.get_next() return get_generator() def map_unordered( self, fn: Callable[["ray.actor.ActorHandle", V], Any], values: List[V] ): """Similar to map(), but returning an unordered iterator. This returns an unordered iterator that will return results of the map as they finish. This can be more efficient that map() if some results take longer to compute than others. Arguments: fn: Function that takes (actor, value) as argument and returns an ObjectRef computing the result over the value. The actor will be considered busy until the ObjectRef completes. values: List of values that fn(actor, value) should be applied to. Returns: Iterator over results from applying fn to the actors and values. Examples: .. testcode:: import ray from ray.util.actor_pool import ActorPool @ray.remote class Actor: def double(self, v): return 2 * v a1, a2 = Actor.remote(), Actor.remote() pool = ActorPool([a1, a2]) print(list(pool.map_unordered(lambda a, v: a.double.remote(v), [1, 2, 3, 4]))) .. testoutput:: :options: +MOCK [6, 8, 4, 2] """ # Ignore/Cancel all the previous submissions # by calling `has_next` and `gen_next_unordered` repeteadly. while self.has_next(): try: self.get_next_unordered(timeout=0) except TimeoutError: pass for v in values: self.submit(fn, v) def get_generator(): while self.has_next(): yield self.get_next_unordered() return get_generator() def submit(self, fn, value): """Schedule a single task to run in the pool. This has the same argument semantics as map(), but takes on a single value instead of a list of values. The result can be retrieved using get_next() / get_next_unordered(). Arguments: fn: Function that takes (actor, value) as argument and returns an ObjectRef computing the result over the value. The actor will be considered busy until the ObjectRef completes. value: Value to compute a result for. Examples: .. testcode:: import ray from ray.util.actor_pool import ActorPool @ray.remote class Actor: def double(self, v): return 2 * v a1, a2 = Actor.remote(), Actor.remote() pool = ActorPool([a1, a2]) pool.submit(lambda a, v: a.double.remote(v), 1) pool.submit(lambda a, v: a.double.remote(v), 2) print(pool.get_next(), pool.get_next()) .. testoutput:: 2 4 """ if self._idle_actors: actor = self._idle_actors.pop() future = fn(actor, value) future_key = tuple(future) if isinstance(future, list) else future self._future_to_actor[future_key] = (self._next_task_index, actor) self._index_to_future[self._next_task_index] = future self._next_task_index += 1 else: self._pending_submits.append((fn, value)) def has_next(self): """Returns whether there are any pending results to return. Returns: True if there are any pending results not yet returned. Examples: .. testcode:: import ray from ray.util.actor_pool import ActorPool @ray.remote class Actor: def double(self, v): return 2 * v a1, a2 = Actor.remote(), Actor.remote() pool = ActorPool([a1, a2]) pool.submit(lambda a, v: a.double.remote(v), 1) print(pool.has_next()) print(pool.get_next()) print(pool.has_next()) .. testoutput:: True 2 False """ return bool(self._future_to_actor) def get_next(self, timeout=None, ignore_if_timedout=False): """Returns the next pending result in order. This returns the next result produced by submit(), blocking for up to the specified timeout until it is available. Returns: The next result. Raises: TimeoutError: if the timeout is reached. Examples: .. testcode:: import ray from ray.util.actor_pool import ActorPool @ray.remote class Actor: def double(self, v): return 2 * v a1, a2 = Actor.remote(), Actor.remote() pool = ActorPool([a1, a2]) pool.submit(lambda a, v: a.double.remote(v), 1) print(pool.get_next()) .. testoutput:: 2 """ if not self.has_next(): raise StopIteration("No more results to get") if self._next_return_index >= self._next_task_index: raise ValueError( "It is not allowed to call get_next() after get_next_unordered()." ) future = self._index_to_future[self._next_return_index] timeout_msg = "Timed out waiting for result" raise_timeout_after_ignore = False if timeout is not None: res, _ = ray.wait([future], timeout=timeout) if not res: if not ignore_if_timedout: raise TimeoutError(timeout_msg) else: raise_timeout_after_ignore = True del self._index_to_future[self._next_return_index] self._next_return_index += 1 future_key = tuple(future) if isinstance(future, list) else future i, a = self._future_to_actor.pop(future_key) self._return_actor(a) if raise_timeout_after_ignore: raise TimeoutError( timeout_msg + ". The task {} has been ignored.".format(future) ) return ray.get(future) def get_next_unordered(self, timeout=None, ignore_if_timedout=False): """Returns any of the next pending results. This returns some result produced by submit(), blocking for up to the specified timeout until it is available. Unlike get_next(), the results are not always returned in same order as submitted, which can improve performance. Returns: The next result. Raises: TimeoutError: if the timeout is reached. Examples: .. testcode:: import ray from ray.util.actor_pool import ActorPool @ray.remote class Actor: def double(self, v): return 2 * v a1, a2 = Actor.remote(), Actor.remote() pool = ActorPool([a1, a2]) pool.submit(lambda a, v: a.double.remote(v), 1) pool.submit(lambda a, v: a.double.remote(v), 2) print(pool.get_next_unordered()) print(pool.get_next_unordered()) .. testoutput:: :options: +MOCK 4 2 """ if not self.has_next(): raise StopIteration("No more results to get") # TODO(ekl) bulk wait for performance res, _ = ray.wait(list(self._future_to_actor), num_returns=1, timeout=timeout) timeout_msg = "Timed out waiting for result" raise_timeout_after_ignore = False if res: [future] = res else: if not ignore_if_timedout: raise TimeoutError(timeout_msg) else: raise_timeout_after_ignore = True i, a = self._future_to_actor.pop(future) self._return_actor(a) del self._index_to_future[i] self._next_return_index = max(self._next_return_index, i + 1) if raise_timeout_after_ignore: raise TimeoutError( timeout_msg + ". The task {} has been ignored.".format(future) ) return ray.get(future) def _return_actor(self, actor): self._idle_actors.append(actor) if self._pending_submits: self.submit(*self._pending_submits.pop(0)) def has_free(self): """Returns whether there are any idle actors available. Returns: True if there are any idle actors and no pending submits. Examples: .. testcode:: import ray from ray.util.actor_pool import ActorPool @ray.remote class Actor: def double(self, v): return 2 * v a1 = Actor.remote() pool = ActorPool([a1]) pool.submit(lambda a, v: a.double.remote(v), 1) print(pool.has_free()) print(pool.get_next()) print(pool.has_free()) .. testoutput:: False 2 True """ return len(self._idle_actors) > 0 and len(self._pending_submits) == 0 def pop_idle(self): """Removes an idle actor from the pool. Returns: An idle actor if one is available. None if no actor was free to be removed. Examples: .. testcode:: import ray from ray.util.actor_pool import ActorPool @ray.remote class Actor: def double(self, v): return 2 * v a1 = Actor.remote() pool = ActorPool([a1]) pool.submit(lambda a, v: a.double.remote(v), 1) assert pool.pop_idle() is None assert pool.get_next() == 2 assert pool.pop_idle() == a1 """ if self.has_free(): return self._idle_actors.pop() return None def push(self, actor): """Pushes a new actor into the current list of idle actors. Examples: .. testcode:: import ray from ray.util.actor_pool import ActorPool @ray.remote class Actor: def double(self, v): return 2 * v a1, a2 = Actor.remote(), Actor.remote() pool = ActorPool([a1]) pool.push(a2) """ busy_actors = [] if self._future_to_actor.values(): _, busy_actors = zip(*self._future_to_actor.values()) if actor in self._idle_actors or actor in busy_actors: raise ValueError("Actor already belongs to current ActorPool") else: self._return_actor(actor)
ActorPool
python
instagram__MonkeyType
monkeytype/stubs.py
{ "start": 24455, "end": 26251 }
class ____(Stub): def __init__( self, function_stubs: Optional[Iterable[FunctionStub]] = None, class_stubs: Optional[Iterable[ClassStub]] = None, imports_stub: Optional[ImportBlockStub] = None, typed_dict_class_stubs: Optional[Iterable[ClassStub]] = None, ) -> None: self.function_stubs: Dict[str, FunctionStub] = {} if function_stubs is not None: self.function_stubs = {stub.name: stub for stub in function_stubs} self.class_stubs: Dict[str, ClassStub] = {} if class_stubs is not None: self.class_stubs = {stub.name: stub for stub in class_stubs} self.imports_stub = imports_stub if imports_stub else ImportBlockStub() self.typed_dict_class_stubs: List[ClassStub] = [] if typed_dict_class_stubs is not None: self.typed_dict_class_stubs = list(typed_dict_class_stubs) def render(self) -> str: parts = [] if self.imports_stub.imports: parts.append(self.imports_stub.render()) for typed_dict_class_stub in sorted( self.typed_dict_class_stubs, key=lambda s: s.name ): parts.append(typed_dict_class_stub.render()) for func_stub in sorted(self.function_stubs.values(), key=lambda s: s.name): parts.append(func_stub.render()) for class_stub in sorted(self.class_stubs.values(), key=lambda s: s.name): parts.append(class_stub.render()) return "\n\n\n".join(parts) def __repr__(self) -> str: return "ModuleStub(%s, %s, %s, %s)" % ( tuple(self.function_stubs.values()), tuple(self.class_stubs.values()), repr(self.imports_stub), tuple(self.typed_dict_class_stubs), )
ModuleStub
python
getsentry__sentry
src/sentry/sentry_apps/api/serializers/sentry_app_installation.py
{ "start": 793, "end": 1029 }
class ____(TypedDict): app: SentryAppInstallationAppResult organization: SentryAppInstallationOrganizationResult uuid: str status: str code: NotRequired[str] @register(SentryAppInstallation)
SentryAppInstallationResult
python
streamlit__streamlit
lib/tests/streamlit/delta_generator_test.py
{ "start": 28188, "end": 28798 }
class ____(DeltaGeneratorTestCase): def test_ids_are_diff_when_keys_are_diff(self): id1 = compute_and_register_element_id( "text_input", user_key="some_key1", label="Label #1", default="Value #1", key_as_main_identity=False, dg=None, ) id2 = compute_and_register_element_id( "text_input", user_key="some_key2", label="Label #1", default="Value #1", key_as_main_identity=False, dg=None, ) assert id1 != id2
KeyWidgetIdTests
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/sparse_ops/sparse_ops_test.py
{ "start": 13164, "end": 19116 }
class ____(test_util.TensorFlowTestCase): _IND_2_5_6 = np.array( [[0, 0, 0], [0, 1, 0], [0, 1, 3], [1, 1, 4], [1, 3, 2], [1, 3, 3]], dtype=np.int64) _VAL_2_5_6 = np.array([0, 10, 13, 14, 32, 33], dtype=np.int32) _SHP_2_5_6 = np.array([2, 5, 6], dtype=np.int64) def _SparseTensor_2x5x6(self): return sparse_tensor.SparseTensor( constant_op.constant(self._IND_2_5_6, dtypes.int64), constant_op.constant(self._VAL_2_5_6, dtypes.int32), constant_op.constant(self._SHP_2_5_6, dtypes.int64)) def _SparseTensor_2x5x6_Empty(self): return sparse_tensor.SparseTensor( constant_op.constant( np.empty(shape=[0, 3], dtype=np.int64), dtypes.int64), constant_op.constant(np.empty(shape=[0], dtype=np.int32), dtypes.int32), constant_op.constant(self._SHP_2_5_6, dtypes.int64)) def _SparseTensorValue_2x5x6(self): return sparse_tensor.SparseTensorValue(self._IND_2_5_6, self._VAL_2_5_6, self._SHP_2_5_6) def testStaticShapeInfoPreservedWhenNewShapeIsProvidedAndStatic(self): sp_input = self._SparseTensor_2x5x6() new_shape = np.array([3, 6, 7], dtype=np.int64) sp_output = sparse_ops.sparse_reset_shape(sp_input, new_shape) self.assertAllEqual([3, 6, 7], sp_output.get_shape()) def testBasic(self): with test_util.force_cpu(): sp_input = self._SparseTensor_2x5x6() new_shape = np.array([3, 6, 7], dtype=np.int64) sp_output = sparse_ops.sparse_reset_shape(sp_input, new_shape) output = self.evaluate(sp_output) self.assertAllEqual(output.indices, [[0, 0, 0], [0, 1, 0], [0, 1, 3], [1, 1, 4], [1, 3, 2], [1, 3, 3]]) self.assertAllEqual(output.values, [0, 10, 13, 14, 32, 33]) self.assertAllEqual(output.dense_shape, [3, 6, 7]) def testInputUnavailableInGraphConstructionOk(self): with test_util.force_cpu(): sp_input = self._SparseTensorValue_2x5x6() new_shape = np.array([3, 6, 7], dtype=np.int64) sp_output = sparse_ops.sparse_reset_shape(sp_input, new_shape) output = self.evaluate(sp_output) self.assertAllEqual(output.indices, [[0, 0, 0], [0, 1, 0], [0, 1, 3], [1, 1, 4], [1, 3, 2], [1, 3, 3]]) self.assertAllEqual(output.values, [0, 10, 13, 14, 32, 33]) self.assertAllEqual(output.dense_shape, [3, 6, 7]) @test_util.run_deprecated_v1 def testFeedInputUnavailableInGraphConstructionOk(self): with self.session(use_gpu=False) as sess: sp_input = array_ops.sparse_placeholder(dtype=dtypes.int32) new_shape = np.array([3, 6, 7], dtype=np.int64) sp_output = sparse_ops.sparse_reset_shape(sp_input, new_shape) output = sess.run(sp_output, feed_dict={sp_input: self._SparseTensorValue_2x5x6()}) self.assertAllEqual(output.indices, [[0, 0, 0], [0, 1, 0], [0, 1, 3], [1, 1, 4], [1, 3, 2], [1, 3, 3]]) self.assertAllEqual(output.values, [0, 10, 13, 14, 32, 33]) self.assertAllEqual(output.dense_shape, [3, 6, 7]) def testTightBoundingBox(self): with test_util.force_cpu(): sp_input = self._SparseTensor_2x5x6() sp_output = sparse_ops.sparse_reset_shape(sp_input) output = self.evaluate(sp_output) self.assertAllEqual(output.indices, [[0, 0, 0], [0, 1, 0], [0, 1, 3], [1, 1, 4], [1, 3, 2], [1, 3, 3]]) self.assertAllEqual(output.values, [0, 10, 13, 14, 32, 33]) self.assertAllEqual(output.dense_shape, [2, 4, 5]) def testTightBoundingBoxEmpty(self): with test_util.force_cpu(): sp_input = self._SparseTensor_2x5x6_Empty() sp_output = sparse_ops.sparse_reset_shape(sp_input) output = self.evaluate(sp_output) self.assertAllEqual(output.indices.shape, [0, 3]) self.assertAllEqual(output.values.shape, [0]) self.assertAllEqual(output.dense_shape, [0, 0, 0]) def testInvalidRank(self): with test_util.force_cpu(): sp_input = self._SparseTensor_2x5x6() new_shape = np.array([3, 7], dtype=np.int64) with self.assertRaises(ValueError): sparse_ops.sparse_reset_shape(sp_input, new_shape) @test_util.run_deprecated_v1 def testInvalidRankNewShapeUnavailableInGraphConstruction(self): with self.session(use_gpu=False) as sess: new_shape = array_ops.placeholder(dtype=dtypes.int64) sp_input = self._SparseTensor_2x5x6() out = sparse_ops.sparse_reset_shape(sp_input, new_shape) with self.assertRaisesOpError("x == y did not hold element-wise"): sess.run(out, feed_dict={new_shape: np.array([3, 7], dtype=np.int64)}) def testInvalidDimensionSizeStatic(self): sp_input = self._SparseTensor_2x5x6() new_shape = np.array([3, 7, 5], dtype=np.int64) with self.assertRaisesRegex(ValueError, "should have dimension sizes"): sparse_ops.sparse_reset_shape(sp_input, new_shape) @test_util.run_deprecated_v1 def testInvalidDimensionSizeDynamic(self): with self.session(use_gpu=False) as sess: sp_input = self._SparseTensor_2x5x6() new_shape = array_ops.placeholder(dtype=dtypes.int32) out = sparse_ops.sparse_reset_shape(sp_input, new_shape) with self.assertRaisesOpError("x <= y did not hold element-wise"): sess.run(out, feed_dict={new_shape: [3, 7, 5]}) @test_util.run_deprecated_v1 def testInvalidDimensionSizeInputUnavailableInGraphConstruction(self): sp_input = array_ops.sparse_placeholder(dtype=dtypes.int32) with self.session(use_gpu=False) as sess: new_shape = np.array([3, 7, 5], dtype=np.int64) out = sparse_ops.sparse_reset_shape(sp_input, new_shape) with self.assertRaisesOpError("x <= y did not hold element-wise"): sess.run(out, feed_dict={sp_input: self._SparseTensorValue_2x5x6()})
SparseResetShapeTest
python
doocs__leetcode
solution/1300-1399/1346.Check If N and Its Double Exist/Solution.py
{ "start": 0, "end": 237 }
class ____: def checkIfExist(self, arr: List[int]) -> bool: s = set() for x in arr: if x * 2 in s or (x % 2 == 0 and x // 2 in s): return True s.add(x) return False
Solution
python
django__django
tests/file_storage/tests.py
{ "start": 23501, "end": 23910 }
class ____(FileSystemStorage): def get_available_name(self, name, max_length=None): """ Append numbers to duplicate files rather than underscores, like Trac. """ basename, *ext = os.path.splitext(name) number = 2 while self.exists(name): name = "".join([basename, ".", str(number)] + ext) number += 1 return name
CustomStorage
python
encode__django-rest-framework
tests/test_relations.py
{ "start": 1033, "end": 3388 }
class ____(APISimpleTestCase): def setUp(self): self.queryset = MockQueryset([ MockObject(pk=i, name=str(i)) for i in range(0, 1100) ]) self.monkeypatch = MonkeyPatch() def test_no_settings(self): # The default is 1,000, so sans settings it should be 1,000 plus one. for many in (False, True): field = serializers.PrimaryKeyRelatedField(queryset=self.queryset, many=many) options = list(field.iter_options()) assert len(options) == 1001 assert options[-1].display_text == "More than 1000 items..." def test_settings_cutoff(self): self.monkeypatch.setattr(relations, "api_settings", MockApiSettings(2, "Cut Off")) for many in (False, True): field = serializers.PrimaryKeyRelatedField(queryset=self.queryset, many=many) options = list(field.iter_options()) assert len(options) == 3 # 2 real items plus the 'Cut Off' item. assert options[-1].display_text == "Cut Off" def test_settings_cutoff_none(self): # Setting it to None should mean no limit; the default limit is 1,000. self.monkeypatch.setattr(relations, "api_settings", MockApiSettings(None, "Cut Off")) for many in (False, True): field = serializers.PrimaryKeyRelatedField(queryset=self.queryset, many=many) options = list(field.iter_options()) assert len(options) == 1100 def test_settings_kwargs_cutoff(self): # The explicit argument should override the settings. self.monkeypatch.setattr(relations, "api_settings", MockApiSettings(2, "Cut Off")) for many in (False, True): field = serializers.PrimaryKeyRelatedField(queryset=self.queryset, many=many, html_cutoff=100) options = list(field.iter_options()) assert len(options) == 101 assert options[-1].display_text == "Cut Off"
TestRelatedFieldHTMLCutoff
python
geekcomputers__Python
Colors/print_colors.py
{ "start": 13, "end": 400 }
class ____: CYAN = "\033[36m" GREEN = "\033[32m" YELLOW = "\033[33m" BLUE = "\033[34m" RED = "\033[31m" ENDC = "\033[0m" def printc(color, message): print(color + message + colors.ENDC) printc(colors.CYAN, sys.argv[1]) printc(colors.GREEN, sys.argv[1]) printc(colors.YELLOW, sys.argv[1]) printc(colors.BLUE, sys.argv[1]) printc(colors.RED, sys.argv[1])
colors
python
pypa__pipenv
pipenv/vendor/plette/models/base.py
{ "start": 50, "end": 1450 }
class ____: def __init__(self, data): self.validate(data) self._data = data def __repr__(self): return "{0}({1!r})".format(type(self).__name__, self._data) def __eq__(self, other): if not isinstance(other, type(self)): raise TypeError( "cannot compare {0!r} with {1!r}".format( type(self).__name__, type(other).__name__ ) ) return self._data == other._data def __getitem__(self, key): return self._data[key] def __setitem__(self, key, value): self._data[key] = value def __delitem__(self, key): del self._data[key] def get(self, key, default=None): try: return self[key] except KeyError: return default @classmethod def validate(cls, data): for k, v in cls.__SCHEMA__.items(): if k not in data: raise DataValidationError(f"Missing required field: {k}") if not isinstance(data[k], v): raise DataValidationError(f"Invalid type for field {k}: {type(data[k])}") if hasattr(cls, "__OPTIONAL__"): for k, v in cls.__OPTIONAL__.items(): if k in data and not isinstance(data[k], v): raise DataValidationError(f"Invalid type for field {k}: {type(data[k])}")
DataModel
python
gevent__gevent
src/gevent/_tracer.py
{ "start": 575, "end": 4426 }
class ____(object): def __init__(self): # A counter, incremented by the greenlet trace function # we install on every greenlet switch. This is reset when the # periodic monitoring thread runs. self.greenlet_switch_counter = 0 # The greenlet last switched to. self.active_greenlet = None # The trace function that was previously installed, # if any. # NOTE: Calling a class instance is cheaper than # calling a bound method (at least when compiled with cython) # even when it redirects to another function. prev_trace = settrace(self) self.previous_trace_function = prev_trace self._killed = False def kill(self): # Must be called in the monitored thread. if not self._killed: self._killed = True settrace(self.previous_trace_function) self.previous_trace_function = None def _trace(self, event, args): # This function runs in the thread we are monitoring. self.greenlet_switch_counter += 1 if event in ('switch', 'throw'): # args is (origin, target). This is the only defined # case self.active_greenlet = args[1] else: self.active_greenlet = None if self.previous_trace_function is not None: self.previous_trace_function(event, args) def __call__(self, event, args): return self._trace(event, args) def did_block_hub(self, hub): # Check to see if we have blocked since the last call to this # method. Returns a true value if we blocked (not in the hub), # a false value if everything is fine. # This may be called in the same thread being traced or a # different thread; if a different thread, there is a race # condition with this being incremented in the thread we're # monitoring, but probably not often enough to lead to # annoying false positives. active_greenlet = self.active_greenlet did_switch = self.greenlet_switch_counter != 0 self.greenlet_switch_counter = 0 if did_switch or active_greenlet is None or active_greenlet is hub: # Either we switched, or nothing is running (we got a # trace event we don't know about or were requested to # ignore), or we spent the whole time in the hub, blocked # for IO. Nothing to report. return False return True, active_greenlet def ignore_current_greenlet_blocking(self): # Don't pay attention to the current greenlet. self.active_greenlet = None def monitor_current_greenlet_blocking(self): self.active_greenlet = getcurrent() def did_block_hub_report(self, hub, active_greenlet, format_kwargs): # XXX: On Python 2 with greenlet 1.0a1, '%s' formatting a greenlet # results in a unicode object. This is a bug in greenlet, I think. # https://github.com/python-greenlet/greenlet/issues/218 report = ['=' * 80, '\n%s : Greenlet %s appears to be blocked' % (gmctime(), str(active_greenlet))] report.append(" Reported by %s" % (self,)) try: frame = sys._current_frames()[hub.thread_ident] except KeyError: # The thread holding the hub has died. Perhaps we shouldn't # even report this? stack = ["Unknown: No thread found for hub %r\n" % (hub,)] else: stack = traceback.format_stack(frame) report.append('Blocked Stack (for thread id %s):' % (hex(hub.thread_ident),)) report.append(''.join(stack)) report.append("Info:") report.extend(format_run_info(**format_kwargs)) return report
GreenletTracer
python
anthropics__anthropic-sdk-python
src/anthropic/pagination.py
{ "start": 2997, "end": 3720 }
class ____(BaseAsyncPage[_T], BasePage[_T], Generic[_T]): data: List[_T] has_more: Optional[bool] = None next_page: Optional[str] = None @override def _get_page_items(self) -> List[_T]: data = self.data if not data: return [] return data @override def has_next_page(self) -> bool: has_more = self.has_more if has_more is not None and has_more is False: return False return super().has_next_page() @override def next_page_info(self) -> Optional[PageInfo]: next_page = self.next_page if not next_page: return None return PageInfo(params={"page_token": next_page})
AsyncTokenPage
python
streamlit__streamlit
lib/tests/streamlit/elements/iframe_test.py
{ "start": 2748, "end": 6897 }
class ____(DeltaGeneratorTestCase): """Test the streamlit.components.v1.iframe and html functions.""" def test_iframe_no_width_uses_stretch_width_config(self): """Test that components.iframe without width uses 'stretch' in width_config.""" st.components.v1.iframe("https://example.com") element = self.get_delta_from_queue().new_element assert ( element.width_config.WhichOneof("width_spec") == WidthConfigFields.USE_STRETCH.value ) assert element.width_config.use_stretch is True assert element.height_config.pixel_height == 150 assert element.iframe.src == "https://example.com" def test_iframe_with_width_uses_pixel_width_config(self): """Test that components.iframe with width uses pixel value in width_config.""" st.components.v1.iframe("https://example.com", width=300, height=200) element = self.get_delta_from_queue().new_element assert ( element.width_config.WhichOneof("width_spec") == WidthConfigFields.PIXEL_WIDTH.value ) assert element.width_config.pixel_width == 300 assert element.height_config.pixel_height == 200 assert element.iframe.src == "https://example.com" def test_iframe_with_width_no_height_uses_default_height(self): """Test that components.iframe with width but no height uses default height.""" st.components.v1.iframe("https://example.com", width=300) element = self.get_delta_from_queue().new_element assert ( element.width_config.WhichOneof("width_spec") == WidthConfigFields.PIXEL_WIDTH.value ) assert element.width_config.pixel_width == 300 assert element.height_config.pixel_height == 150 assert element.iframe.src == "https://example.com" def test_html_no_width_uses_stretch_width_config(self): """Test that components.html without width uses 'stretch' in width_config.""" st.components.v1.html("<h1>Test</h1>") element = self.get_delta_from_queue().new_element assert ( element.width_config.WhichOneof("width_spec") == WidthConfigFields.USE_STRETCH.value ) assert element.width_config.use_stretch is True assert element.height_config.pixel_height == 150 assert element.iframe.srcdoc == "<h1>Test</h1>" def test_html_with_width_uses_pixel_width_config(self): """Test that components.html with width uses pixel value in width_config.""" st.components.v1.html("<h1>Test</h1>", width=400, height=300) element = self.get_delta_from_queue().new_element assert ( element.width_config.WhichOneof("width_spec") == WidthConfigFields.PIXEL_WIDTH.value ) assert element.width_config.pixel_width == 400 assert element.height_config.pixel_height == 300 assert element.iframe.srcdoc == "<h1>Test</h1>" def test_iframe_with_zero_width_and_height(self): """Test that components.iframe accepts both width=0 and height=0.""" st.components.v1.iframe("https://example.com", width=0, height=0) element = self.get_delta_from_queue().new_element assert ( element.width_config.WhichOneof("width_spec") == WidthConfigFields.PIXEL_WIDTH.value ) assert element.width_config.pixel_width == 0 assert element.height_config.pixel_height == 0 assert element.iframe.src == "https://example.com" def test_html_with_zero_width_and_height(self): """Test that components.html accepts both width=0 and height=0.""" st.components.v1.html("<h1>Test</h1>", width=0, height=0) element = self.get_delta_from_queue().new_element assert ( element.width_config.WhichOneof("width_spec") == WidthConfigFields.PIXEL_WIDTH.value ) assert element.width_config.pixel_width == 0 assert element.height_config.pixel_height == 0 assert element.iframe.srcdoc == "<h1>Test</h1>"
IFrameComponentTest
python
doocs__leetcode
solution/0200-0299/0209.Minimum Size Subarray Sum/Solution2.py
{ "start": 0, "end": 340 }
class ____: def minSubArrayLen(self, target: int, nums: List[int]) -> int: l = s = 0 ans = inf for r, x in enumerate(nums): s += x while s >= target: ans = min(ans, r - l + 1) s -= nums[l] l += 1 return 0 if ans == inf else ans
Solution
python
astropy__astropy
astropy/modeling/projections.py
{ "start": 37827, "end": 38244 }
class ____(Projection): r"""Base class for quad cube projections. Quadrilateralized spherical cube (quad-cube) projections belong to the class of polyhedral projections in which the sphere is projected onto the surface of an enclosing polyhedron. The six faces of the quad-cube projections are numbered and laid out as:: 0 4 3 2 1 4 3 2 5 """
QuadCube
python
automl__auto-sklearn
test/test_evaluation/test_test_evaluator.py
{ "start": 2703, "end": 2978 }
class ____: def __init__(self): self.info = {"task": MULTICLASS_CLASSIFICATION, "is_sparse": False} self.feat_type = { 0: "numerical", 1: "Numerical", 2: "numerical", 3: "numerical", }
DummyDatamanager
python
huggingface__transformers
examples/modular-transformers/modeling_super.py
{ "start": 1258, "end": 1981 }
class ____(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ SuperRMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype) def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
SuperRMSNorm
python
HypothesisWorks__hypothesis
hypothesis-python/src/hypothesis/internal/conjecture/shrinking/collection.py
{ "start": 649, "end": 3237 }
class ____(Shrinker): def setup( self, *, ElementShrinker, min_size, to_order=identity, from_order=identity ): self.ElementShrinker = ElementShrinker self.to_order = to_order self.from_order = from_order self.min_size = min_size def make_immutable(self, value): return tuple(value) def short_circuit(self): zero = self.from_order(0) return self.consider([zero] * self.min_size) def left_is_better(self, left, right): if len(left) < len(right): return True # examine elements one by one from the left until an element differs. for v1, v2 in zip(left, right, strict=False): if self.to_order(v1) == self.to_order(v2): continue return self.to_order(v1) < self.to_order(v2) # equal length and all values were equal by our ordering, so must be equal # by our ordering. assert list(map(self.to_order, left)) == list(map(self.to_order, right)) return False def run_step(self): # try all-zero first; we already considered all-zero-and-smallest in # short_circuit. zero = self.from_order(0) self.consider([zero] * len(self.current)) # try deleting each element in turn, starting from the back # TODO_BETTER_SHRINK: adaptively delete here by deleting larger chunks at once # if early deletes succeed. use find_integer. turns O(n) into O(log(n)) for i in reversed(range(len(self.current))): self.consider(self.current[:i] + self.current[i + 1 :]) # then try reordering Ordering.shrink(self.current, self.consider, key=self.to_order) # then try minimizing all duplicated elements together simultaneously. This # helps in cases like https://github.com/HypothesisWorks/hypothesis/issues/4286 duplicated = {val for val, count in Counter(self.current).items() if count > 1} for val in duplicated: self.ElementShrinker.shrink( self.to_order(val), lambda v: self.consider( tuple(self.from_order(v) if x == val else x for x in self.current) ), ) # then try minimizing each element in turn for i, val in enumerate(self.current): self.ElementShrinker.shrink( self.to_order(val), lambda v: self.consider( self.current[:i] + (self.from_order(v),) + self.current[i + 1 :] ), )
Collection
python
huggingface__transformers
src/transformers/models/grounding_dino/modeling_grounding_dino.py
{ "start": 61294, "end": 66393 }
class ____(nn.Module): def __init__(self, config: GroundingDinoConfig): super().__init__() self.embed_dim = config.d_model # self-attention self.self_attn = GroundingDinoMultiheadAttention(config, num_attention_heads=config.decoder_attention_heads) self.dropout = config.dropout self.activation_fn = ACT2FN[config.activation_function] self.activation_dropout = config.activation_dropout self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim, config.layer_norm_eps) # cross-attention text self.encoder_attn_text = GroundingDinoMultiheadAttention( config, num_attention_heads=config.decoder_attention_heads ) self.encoder_attn_text_layer_norm = nn.LayerNorm(self.embed_dim, config.layer_norm_eps) # cross-attention self.encoder_attn = GroundingDinoMultiscaleDeformableAttention( config, num_heads=config.decoder_attention_heads, n_points=config.decoder_n_points, ) self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim, config.layer_norm_eps) # feedforward neural networks self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim) self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim) self.final_layer_norm = nn.LayerNorm(self.embed_dim, config.layer_norm_eps) def with_pos_embed(self, tensor: torch.Tensor, position_embeddings: Optional[Tensor]): return tensor if position_embeddings is None else tensor + position_embeddings def forward( self, hidden_states: torch.Tensor, position_embeddings: Optional[torch.Tensor] = None, reference_points=None, spatial_shapes=None, spatial_shapes_list=None, level_start_index=None, vision_encoder_hidden_states: Optional[torch.Tensor] = None, vision_encoder_attention_mask: Optional[torch.Tensor] = None, text_encoder_hidden_states: Optional[torch.Tensor] = None, text_encoder_attention_mask: Optional[torch.Tensor] = None, self_attn_mask: Optional[torch.Tensor] = None, output_attentions: Optional[bool] = False, ): residual = hidden_states # Self Attention queries = keys = self.with_pos_embed(hidden_states, position_embeddings) hidden_states, self_attn_weights = self.self_attn( queries=queries, keys=keys, values=hidden_states, attention_mask=self_attn_mask, output_attentions=True, ) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.self_attn_layer_norm(hidden_states) second_residual = hidden_states # Cross-Attention Text queries = self.with_pos_embed(hidden_states, position_embeddings) hidden_states, text_cross_attn_weights = self.encoder_attn_text( queries=queries, keys=text_encoder_hidden_states, values=text_encoder_hidden_states, attention_mask=text_encoder_attention_mask, output_attentions=True, ) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = second_residual + hidden_states hidden_states = self.encoder_attn_text_layer_norm(hidden_states) third_residual = hidden_states # Cross-Attention cross_attn_weights = None hidden_states, cross_attn_weights = self.encoder_attn( hidden_states=hidden_states, attention_mask=vision_encoder_attention_mask, encoder_hidden_states=vision_encoder_hidden_states, encoder_attention_mask=vision_encoder_attention_mask, position_embeddings=position_embeddings, reference_points=reference_points, spatial_shapes=spatial_shapes, spatial_shapes_list=spatial_shapes_list, level_start_index=level_start_index, output_attentions=output_attentions, ) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = third_residual + hidden_states hidden_states = self.encoder_attn_layer_norm(hidden_states) # Fully Connected residual = hidden_states hidden_states = self.activation_fn(self.fc1(hidden_states)) hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training) hidden_states = self.fc2(hidden_states) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states hidden_states = self.final_layer_norm(hidden_states) outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights, text_cross_attn_weights, cross_attn_weights) return outputs
GroundingDinoDecoderLayer
python
getsentry__sentry
src/sentry/integrations/pagerduty/integration.py
{ "start": 9280, "end": 10155 }
class ____: def get_app_url(self, account_name: str | None = None) -> str: if not account_name: account_name = "app" app_id = options.get("pagerduty.app-id") setup_url = absolute_uri("/extensions/pagerduty/setup/") return f"https://{account_name}.pagerduty.com/install/integration?app_id={app_id}&redirect_url={setup_url}&version=2" def dispatch(self, request: HttpRequest, pipeline: IntegrationPipeline) -> HttpResponseBase: with record_event(OnCallInteractionType.INSTALLATION_REDIRECT).capture(): if "config" in request.GET: pipeline.bind_state("config", request.GET["config"]) return pipeline.next_step() account_name = request.GET.get("account", None) return HttpResponseRedirect(self.get_app_url(account_name))
PagerDutyInstallationRedirect
python
coleifer__peewee
tests/results.py
{ "start": 5607, "end": 5677 }
class ____(TestModel): key = TextField() ts = DateTimeField()
Reg
python
spyder-ide__spyder
spyder/api/utils.py
{ "start": 2453, "end": 4043 }
class ____(BaseABCMeta): """ Metaclass to mark abstract classes. Adds support for abstract attributes. If a class has abstract attributes and is instantiated, a NotImplementedError is raised. Usage ----- .. code-block:: python class MyABC(metaclass=ABCMeta): @abstract_attribute def my_abstract_attribute(self): pass class MyClassOK(MyABC): def __init__(self): self.my_abstract_attribute = 1 class MyClassNotOK(MyABC): pass Raises ------ NotImplementedError When it's not possible to instantiate an abstract class with abstract attributes. """ def __call__(cls, *args, **kwargs): # Collect all abstract-attribute names from the entire MRO abstract_attr_names = set() for base in cls.__mro__: for name, value in base.__dict__.items(): if getattr(value, '__is_abstract_attribute__', False): abstract_attr_names.add(name) for name, value in cls.__dict__.items(): if not getattr(value, '__is_abstract_attribute__', False): abstract_attr_names.discard(name) if abstract_attr_names: raise NotImplementedError( "Can't instantiate abstract class " "{} with abstract attributes: {}".format( cls.__name__, ", ".join(abstract_attr_names) ) ) return super().__call__(*args, **kwargs)
ABCMeta
python
sympy__sympy
sympy/core/mul.py
{ "start": 809, "end": 2345 }
class ____: is_Order = False is_Mul = False is_Number = False is_Poly = False is_commutative = False def _mulsort(args): # in-place sorting of args args.sort(key=_args_sortkey) def _unevaluated_Mul(*args): """Return a well-formed unevaluated Mul: Numbers are collected and put in slot 0, any arguments that are Muls will be flattened, and args are sorted. Use this when args have changed but you still want to return an unevaluated Mul. Examples ======== >>> from sympy.core.mul import _unevaluated_Mul as uMul >>> from sympy import S, sqrt, Mul >>> from sympy.abc import x >>> a = uMul(*[S(3.0), x, S(2)]) >>> a.args[0] 6.00000000000000 >>> a.args[1] x Two unevaluated Muls with the same arguments will always compare as equal during testing: >>> m = uMul(sqrt(2), sqrt(3)) >>> m == uMul(sqrt(3), sqrt(2)) True >>> u = Mul(sqrt(3), sqrt(2), evaluate=False) >>> m == uMul(u) True >>> m == Mul(*m.args) False """ cargs = [] ncargs = [] args = list(args) co = S.One for a in args: if a.is_Mul: a_c, a_nc = a.args_cnc() args.extend(a_c) # grow args ncargs.extend(a_nc) elif a.is_Number: co *= a elif a.is_commutative: cargs.append(a) else: ncargs.append(a) _mulsort(cargs) if co is not S.One: cargs.insert(0, co) return Mul._from_args(cargs+ncargs)
NC_Marker
python
astropy__astropy
astropy/modeling/projections.py
{ "start": 9012, "end": 10202 }
class ____(Sky2PixProjection, Zenithal): r""" Zenithal perspective projection - sky to pixel. Corresponds to the ``AZP`` projection in FITS WCS. .. math:: x &= R \sin \phi \\ y &= -R \sec \gamma \cos \theta where: .. math:: R = \frac{180^{\circ}}{\pi} \frac{(\mu + 1) \cos \theta} {(\mu + \sin \theta) + \cos \theta \cos \phi \tan \gamma} Parameters ---------- mu : float Distance from point of projection to center of sphere in spherical radii, μ. Default is 0. gamma : float Look angle γ in degrees. Default is 0°. """ mu = _ParameterDS( default=0.0, description="Distance from point of projection to center of sphere" ) gamma = _ParameterDS( default=0.0, getter=_to_orig_unit, setter=_to_radian, description="Look angle γ in degrees (Default=0°)", ) def _mu_validator(self, value): if np.any(np.equal(value, -1.0)): raise InputParameterError( "Zenithal perspective projection is not defined for mu = -1" ) mu._validator = _mu_validator
Sky2Pix_ZenithalPerspective
python
getsentry__sentry
tests/sentry/notifications/api/endpoints/test_user_notification_details.py
{ "start": 286, "end": 1259 }
class ____(UserNotificationDetailsTestBase): def test_lookup_self(self) -> None: self.get_success_response("me") def test_lookup_other_user(self) -> None: user_b = self.create_user(email="b@example.com") self.get_error_response(user_b.id, status_code=403) def test_superuser(self) -> None: superuser = self.create_user(email="b@example.com", is_superuser=True) self.login_as(user=superuser, superuser=True) self.get_success_response(self.user.id) def test_returns_correct_defaults(self) -> None: """ In this test we add existing per-project and per-organization Notification settings in order to test that defaults are correct. """ response = self.get_success_response("me") assert response.data.get("personalActivityNotifications") is False assert response.data.get("selfAssignOnResolve") is False @control_silo_test
UserNotificationDetailsGetTest
python
joke2k__faker
faker/providers/job/az_AZ/__init__.py
{ "start": 42, "end": 2489 }
class ____(BaseProvider): jobs = [ "Aktyor", "Akustik Mühəndisi", "Allerqoloq", "Analitik", "Androloq", "Antropoloq", "Aqronom", "Aqronom-Torpaqşünas", "Arxeoloq", "Arxivçi", "Astrofizik", "Astronom", "Aviatexnik", "Bakterioloq", "Bankir", "Barmen", "Biokimyaçı", "Bioloq", "Biomühəndis", "Blogger", "Botanik", "Cihazqayırma və idarəetmə mühəndisi", "Coğrafiyaçı", "Cərrah", "DJ", "Dalğıc", "Daşçı", "Dekan", "Dermatoloq", "Diler", "Diplomat", "Diplomatik işçi", "Dirijyor", "Dispetçer", "Dizayner", "Dizayner-konstruktor", "Dülgər", "Elektrikçi", "Enerji Mühəndisi", "Genetik", "Geoloq", "Ginekoloq", "Gitarist", "Gəmi kapitanı", "Hematoloq", "Hepatoloq", "Hidrolik Mühəndis", "Hidroloq", "Hüquqşünas", "Hərbi Hakim", "Hərbi Məsləhətçi", "Hərbi Polis", "Hərbi Prokuror", "Hərbi müstəntiq", "Hərbi tərcüməçi", "Hərbi vəkil", "Hərbçi", "Jurnalist", "Kardioloq", "Kimya mühəndisi", "Kitabxanaçı", "Kolleksiyaçı", "Makler", "Memar", "Mexanik", "Mexanika Mühəndisi", "Mühasib", "Mühəndis", "Mühəndis-Fizik", "Mühəndis-laboratoriya köməkçisi", "Müstəntiq", "Mədənçi", "Paraşütçü", "Partlayıcı Mühəndis", "Pilot", "Qastroenteroloq", "Qulluqçu", "Qumbara Atıcı", "Reklam dizayneri", "Sistem Mühəndisi", "Stüardessa", "Sürücü", "Səs mühəndisi", "Tarixçi", "Torpaqçı", "Təcili yardım həkimi", "Təhlükəsizlik Mühəndisi", "Təmizlikçi", "Təxribatçı", "Uçuş mühəndisi", "Veb Proqramçı", "Verilənlər bazası administratoru", "Viroloq", "Vizajist", "Vokalçı", "Webmaster", "Xoreoqraf", "Zooloq", "Zootexnik", "Zərgər", "Çörəkçi", "İmmunoloq", "İnfeksionist", "İnşaat mühəndisi", "İşsiz", "Şərqşünas", ]
Provider
python
readthedocs__readthedocs.org
readthedocs/rtd_tests/tests/test_automation_rules.py
{ "start": 11328, "end": 13303 }
class ____: @pytest.fixture(autouse=True) def setup_method(self): self.project = get(Project) def test_add_rule_regex(self): assert not self.project.automation_rules.all() rule = RegexAutomationRule.objects.create( project=self.project, description="First rule", match_arg=".*", version_type=TAG, action=VersionAutomationRule.ACTIVATE_VERSION_ACTION, ) # First rule gets added with priority 0 assert self.project.automation_rules.count() == 1 assert rule.priority == 0 # Adding a second rule rule = RegexAutomationRule.objects.create( project=self.project, description="Second rule", match_arg=".*", version_type=BRANCH, action=VersionAutomationRule.ACTIVATE_VERSION_ACTION, ) assert self.project.automation_rules.count() == 2 assert rule.priority == 0 # Adding a rule with a not secuencial priority rule = get( RegexAutomationRule, description="Third rule", project=self.project, priority=9, match_arg=".*", version_type=TAG, action=VersionAutomationRule.ACTIVATE_VERSION_ACTION, ) assert self.project.automation_rules.count() == 3 assert rule.priority == 2 # Adding a new rule rule = RegexAutomationRule.objects.create( project=self.project, description="Fourth rule", match_arg=".*", version_type=BRANCH, action=VersionAutomationRule.ACTIVATE_VERSION_ACTION, ) assert self.project.automation_rules.count() == 4 assert rule.priority == 0 assert list( self.project.automation_rules.all().values_list("priority", flat=True) ) == [0, 1, 2, 3] @pytest.mark.django_db
TestAutomationRuleManager
python
google__pytype
pytype/tools/config.py
{ "start": 1774, "end": 2366 }
class ____(ConfigSection): """A section of an INI config file.""" def __init__(self, parser, section): self._parser = parser self._section = section @classmethod def create_from_file(cls, filepath, section): parser = configparser.ConfigParser() try: parser.read(filepath) except configparser.MissingSectionHeaderError: # We've read an improperly formatted config file. return None if parser.has_section(section): return cls(parser, section) return None def items(self): return self._parser.items(self._section)
IniConfigSection
python
streamlit__streamlit
lib/tests/streamlit/elements/lib/column_config_utils_test.py
{ "start": 1566, "end": 3150 }
class ____: def __str__(self): return "TestObject" def _get_arrow_schema_field(column: pd.Series) -> pa.Field | None: """Get the Arrow schema field for a pandas Series.""" try: arrow_schema = pa.Table.from_pandas(column.to_frame()).schema return arrow_schema.field(0) except (pa.ArrowTypeError, pa.ArrowInvalid, pa.ArrowNotImplementedError): return None SHARED_DATA_KIND_TEST_CASES = [ (pd.Series(["a", "b", "c"], dtype=pd.StringDtype()), ColumnDataKind.STRING), # We need to use Int64 here, otherwise it gets converted to float if a None is added: (pd.Series([1, 2, -3], dtype="Int64"), ColumnDataKind.INTEGER), (pd.Series([1.1, 2.2, -3.3]), ColumnDataKind.FLOAT), (pd.Series([1, 2.2, 3]), ColumnDataKind.FLOAT), # mixed-integer-float ( pd.Series([pd.Timestamp("2000-01-01"), pd.Timestamp("2000-01-02")]), ColumnDataKind.DATETIME, ), ( pd.Series([datetime.datetime(2000, 1, 1), datetime.datetime(2000, 1, 2)]), ColumnDataKind.DATETIME, ), ( pd.Series( [ pd.Timestamp("2000-01-01", tz="US/Central"), pd.Timestamp("2000-01-02", tz="US/Central"), ] ), ColumnDataKind.DATETIME, ), (pd.Series([True, False]), ColumnDataKind.BOOLEAN), ( pd.Series([pd.Timedelta("1 day"), pd.Timedelta("2 days")]), ColumnDataKind.TIMEDELTA, ), ( pd.Series([np.timedelta64(1, "D"), np.timedelta64(2, "D")]), ColumnDataKind.TIMEDELTA, ), ]
TestObject
python
pytorch__pytorch
torch/_dynamo/variables/base.py
{ "start": 8832, "end": 27381 }
class ____(metaclass=VariableTrackerMeta): """ Base class for tracked locals and stack values VariableTracker instances are immutable and should be copied in order to change them. Prefer the factory function VariableTracker.build() over VariableTracker.__init__(). """ # fields to leave unmodified in apply() _nonvar_fields = { "value", "guards", "source", "mutation_type", "parents_tracker", "user_code_variable_name", } def clone(self, **kwargs: Any) -> "VariableTracker": """Shallow copy with some (optional) changes""" args = dict(self.__dict__) args.update(kwargs) return self.__class__(**args) @classmethod def visit( cls, fn: Callable[["VariableTracker"], None], value: Any, cache: Optional[dict[int, Any]] = None, ) -> None: """ Walk value and call fn on all the VariableTracker instances """ if cache is None: cache = {} idx = id(value) if idx in cache: return # save `value` to keep it alive and ensure id() isn't reused cache[idx] = value if isinstance(value, VariableTracker): value = value.unwrap() fn(value) value = value.unwrap() # calling fn() might have realized it nonvars = value._nonvar_fields for key, subvalue in value.__dict__.items(): if key not in nonvars: cls.visit(fn, subvalue, cache) elif istype(value, (list, tuple)): for subvalue in value: cls.visit(fn, subvalue, cache) elif istype(value, (dict, collections.OrderedDict)): for subvalue in value.values(): cls.visit(fn, subvalue, cache) def __repr__(self) -> str: return f"{self.__class__.__name__}()" def debug_repr(self) -> str: # Intended to be overridden to provide more info try: return repr(self.as_python_constant()) except NotImplementedError: return repr(self) def python_type(self) -> type: """ Abstract method to be implemented by subclasses of VariableTracker. This method should return the type represented by the instance of the subclass. The purpose is to provide a standardized way to retrieve the Python type information of the variable being tracked. Returns: type: The Python type (such as int, str, list, etc.) of the variable tracked by the subclass. If the type cannot be determined or is not relevant, leaving it undefined or invoking super() is always sound. Note: This is an abstract method and may be overridden in subclasses. Example: class SetVariable(VariableTracker): def python_type(self): return set Raises: NotImplementedError: If the method is not implemented in a subclass. """ try: return type(self.as_python_constant()) except NotImplementedError: raise NotImplementedError(f"{self} has no type") from None def python_type_name(self) -> str: try: return self.python_type().__name__ except NotImplementedError: return "<unknown type>" def as_python_constant(self) -> Any: """For constants""" raise AsPythonConstantNotImplementedError(self) def guard_as_python_constant(self) -> Any: """Similar to as_python_constant(), but add ID_MATCH guards to try to force things to become constants""" try: return self.as_python_constant() except NotImplementedError: unimplemented( gb_type="Not a Python constant", context=f"guard_as_python_constant {self}", explanation=f"Failed to convert {self} into a Python constant.", hints=[], ) def is_python_constant(self) -> bool: try: self.as_python_constant() return True except NotImplementedError: return False def make_guard(self, fn: Callable[..., Any]) -> Guard: if self.source: return self.source.make_guard(fn) raise NotImplementedError # TODO[@lucaskabela] - change this type to `InstructionTranslatorBase` # and cascade that (large blast radius) def const_getattr(self, tx: "InstructionTranslator", name: str) -> Any: """getattr(self, name) returning a python constant""" raise NotImplementedError def var_getattr(self, tx: "InstructionTranslator", name: str) -> "VariableTracker": """getattr(self, name) returning a new variable""" value = self.const_getattr(tx, name) if not variables.ConstantVariable.is_literal(value): raise NotImplementedError source = self.source and AttrSource(self.source, name) if source and not isinstance(self, variables.ConstantVariable): # The second condition is to avoid guards on const getattr objects # like __code__.co_argcount install_guard(source.make_guard(GuardBuilder.CONSTANT_MATCH)) return variables.ConstantVariable.create(value, source=source) def is_proxy(self) -> bool: try: self.as_proxy() return True except NotImplementedError: return False def as_proxy(self) -> Any: raise NotImplementedError(str(self)) def maybe_fx_node(self) -> Optional[Node]: try: proxy = self.as_proxy() import torch.fx if isinstance(proxy, torch.fx.Proxy): return proxy.node return None except NotImplementedError: return None def reconstruct(self, codegen: "PyCodegen") -> None: raise NotImplementedError def unpack_var_sequence(self, tx: Any) -> list["VariableTracker"]: raise NotImplementedError def force_unpack_var_sequence(self, tx: Any) -> list["VariableTracker"]: # like unpack_var_sequence, but should only be used when it is # safe to eagerly (vs. lazily) unpack this variable. # e.g. map(f, x) is normally evaluated lazily but sometimes # we want to force eager unpacking, e.g. when converting to a list. # NOTE: this method is allowed to mutate the VariableTracker, so # it should only be called once. return self.unpack_var_sequence(tx) def has_unpack_var_sequence(self, tx: Any) -> bool: try: self.unpack_var_sequence(tx) return True except NotImplementedError: return False # NB: don't call force_unpack_var_sequence, especially if it mutates! def has_force_unpack_var_sequence(self, tx: Any) -> bool: return self.has_unpack_var_sequence(tx) # Forces unpacking the var sequence while also applying a function to each element. # Only use when it is safe to eagerly unpack this variable (like force_unpack_var_sequence). # INVARIANT: variable must satisfy has_force_unpack_var_sequence() == True! def force_apply_to_var_sequence( self, tx: Any, fn: Callable[["VariableTracker"], Any] ) -> None: assert self.has_force_unpack_var_sequence(tx) for v in self.unpack_var_sequence(tx): fn(v) def call_obj_hasattr(self, tx: Any, name: str) -> "ConstantVariable": unimplemented( gb_type="Unsupported hasattr call", context=f"call_obj_hasattr {self} {name}", explanation=f"Dynamo does not know how to trace the function `{self.debug_repr()}`", hints=[ f"Avoid calling `hasattr({self.__class__.__name__}, {name})` in your code.", *graph_break_hints.SUPPORTABLE, ], ) def call_function( self, tx: Any, args: Sequence["VariableTracker"], kwargs: dict[str, "VariableTracker"], ) -> "VariableTracker": unimplemented( gb_type="Unsupported function call", context=f"call_function {self} {args} {kwargs}", explanation=f"Dynamo does not know how to trace the function `{self.debug_repr()}`", hints=[ f"Avoid calling `{self.debug_repr()}` in your code.", "Please report an issue to PyTorch.", ], ) def call_method( self, tx: Any, name: str, args: list["VariableTracker"], kwargs: dict[str, "VariableTracker"], ) -> "VariableTracker": if name == "__len__" and self.has_unpack_var_sequence(tx): assert not (args or kwargs) return variables.ConstantVariable.create(len(self.unpack_var_sequence(tx))) elif ( name == "__getattr__" and len(args) == 1 and args[0].is_python_constant() and not kwargs ): return self.var_getattr(tx, args[0].as_python_constant()) elif name in cmp_name_to_op_mapping and len(args) == 1 and not kwargs: other = args[0] if not isinstance(self, type(other)) and not ( isinstance(self, variables.GetAttrVariable) or isinstance(other, variables.GetAttrVariable) ): # NB: GetAttrVariable is a special case because sometimes an # object can map to GetAttrVariable but other time as # SkipFunctionVariable if it is an input to the compiled # function, e.g. tensor.data_ptr return variables.ConstantVariable.create(NotImplemented) # NB : Checking for mutation is necessary because we compare # constant values if ( not self.is_python_constant() or not other.is_python_constant() or tx.output.side_effects.has_pending_mutation(self) or tx.output.side_effects.has_pending_mutation(other) ): unimplemented( gb_type="Builtin `operator.*` comparison with constant `self` failed", context=f"call_method {self} {name} {args} {kwargs}", explanation=f"Failed to compare {self} with {other}, " + f"because {other} is not a Python constant or its mutation check fails.", hints=[], ) try: return variables.ConstantVariable.create( cmp_name_to_op_mapping[name]( self.as_python_constant(), other.as_python_constant() ) ) except Exception as e: raise_observed_exception( type(e), tx, args=[list(map(variables.ConstantVariable.create, e.args))], ) hints = [ f"Avoid calling `{self.python_type_name()}.{name}` in your code.", "Please report an issue to PyTorch.", ] # additional hint for method calls on improperly constructed iterators if isinstance(self, variables.UserDefinedObjectVariable) and name in ( "__iter__", "__next__", ): if isinstance(self.value, (KeysView, ItemsView, ValuesView)): hints.append( "Consider moving the creation of dict view object (e.g. `dict.keys()`, `dict.items()`,) " "to the compiled region, instead of passing it as an input to the compiled region." ) hints.append( "Dynamo does not fully support tracing builtin iterators (e.g. `map`, `zip`, `enumerate`) " "passed in from uncompiled to compiled regions (e.g. `torch.compile(fn)(enumerate(...))`). " "This can happen unintentionally if a previous graph break happens with a builtin iterator " "in the local scope." ) hints.append( "List/dict comprehensions in Python <= 3.11 result in implicit function calls, which Dynamo " "cannot trace as a top level frame. Possible workarounds are (1) use a loop instead of a comprehension, " "(2) fix any graph breaks in the function above the comprehension, (3) wrap the comprehension in a " "function, or (4) use Python 3.12+." ) unimplemented( gb_type="Unsupported method call", context=f"call_method {self} {name} {args} {kwargs}", explanation=f"Dynamo does not know how to trace method `{name}` of class `{self.python_type_name()}`", hints=hints, ) def call_tree_map( self, tx: Any, tree_map_fn: "UserFunctionVariable", map_fn: "VariableTracker", rest: Sequence["VariableTracker"], tree_map_kwargs: dict[str, "VariableTracker"], ) -> "VariableTracker": """Performance optimization to implement optree.tree_map faster than tracing it""" is_leaf_var = tree_map_kwargs.get("is_leaf") if is_leaf_var is not None and not ( is_leaf_var.is_python_constant() and is_leaf_var.as_python_constant() is None ): pred_result = is_leaf_var.call_function(tx, [self], {}) try: leaf_decision = pred_result.as_python_constant() except NotImplementedError: return self._tree_map_fallback( tx, tree_map_fn, map_fn, rest, tree_map_kwargs, ) if leaf_decision: return map_fn.call_function(tx, [self, *rest], {}) return self.call_tree_map_branch( tx, tree_map_fn, map_fn, rest, tree_map_kwargs, ) def call_tree_map_branch( self, tx: Any, tree_map_fn: "UserFunctionVariable", map_fn: "VariableTracker", rest: Sequence["VariableTracker"], tree_map_kwargs: dict[str, "VariableTracker"], ) -> "VariableTracker": """Emulate optree.tree_map without is_leaf/none_is_leaf checks (handled above)""" return self._tree_map_fallback( tx, tree_map_fn, map_fn, rest, tree_map_kwargs, ) def _tree_map_fallback( self, tx: Any, tree_map_fn: "UserFunctionVariable", map_fn: "VariableTracker", rest: Sequence["VariableTracker"], tree_map_kwargs: dict[str, "VariableTracker"], ) -> "VariableTracker": tree_map_fn_copy = tree_map_fn.clone() tree_map_fn_copy._maybe_call_tree_map_fastpath = lambda *args, **kwargs: None # type: ignore[missing-attribute] log.debug( "tree_map fastpath fallback triggered for %s (rest=%s, kwargs=%s)", self, rest, tree_map_kwargs, ) return tree_map_fn_copy.call_function( tx, [map_fn, self, *rest], tree_map_kwargs, ) def set_name_hint(self, name: str) -> None: pass def realize(self) -> "VariableTracker": """Used by LazyVariableTracker to build the real VariableTracker""" return self def unwrap(self) -> "VariableTracker": """Used by LazyVariableTracker to return the real VariableTracker if it already exists""" return self def is_realized(self) -> bool: """Used by LazyVariableTracker to indicate an unrealized node""" return True def next_variable(self, tx: Any) -> "VariableTracker": unimplemented( gb_type="Unsupported next() call", context=f"next({self})", explanation=f"Dynamo does not know how to trace calling `next()` on variable `{self}`.", hints=[*graph_break_hints.USER_ERROR], ) def is_strict_mode(self, tx: Any) -> bool: return bool(tx.strict_checks_fn and tx.strict_checks_fn(self)) def is_mutable(self) -> bool: """Whether Dynamo allows mutation on this variable.""" return not self.is_immutable() def is_immutable(self) -> bool: """Whether Dynamo bans mutation on this variable.""" return self.mutation_type is None @staticmethod def build( tx: Any, value: Any, source: Optional[Source] = None, ) -> Any: """Create a new VariableTracker from a value and optional Source""" if source is None: return builder.SourcelessBuilder.create(tx, value) else: return variables.LazyVariableTracker.create(value, source) def __init__( self, *, source: Optional[Source] = None, mutation_type: Optional[MutationType] = None, ) -> None: super().__init__() self.source = source self.mutation_type = mutation_type # NOTE sometimes mutation_type is set afterwards for implementation # convenience, we don't validate those cases at the moment. if mutation_type is not None: if isinstance(mutation_type, (ValueMutationNew, AttributeMutationNew)): # If this fails, it's either # 1. one mistakenly passed in a source # 2. `mutation_type` is incorrect assert source is None else: assert isinstance( mutation_type, (ValueMutationExisting, AttributeMutationExisting) ) # If this fails, it's either # 1. one forgot to pass in a source # 2. `mutation_type` is incorrect assert source is not None def raise_type_error_exc(tx: Any, msg_str: str) -> NoReturn: msg = variables.ConstantVariable.create(msg_str) raise_observed_exception(TypeError, tx, args=[msg]) def typestr(*objs: object) -> str: if len(objs) == 1: (obj,) = objs if isinstance(obj, VariableTracker): return str(obj) else: return type(obj).__name__ else: return " ".join(map(typestr, objs)) from . import builder
VariableTracker
python
ray-project__ray
python/ray/util/iter.py
{ "start": 26472, "end": 42040 }
class ____(Generic[T]): """An iterator over a single shard of data. It implements similar transformations as ParallelIterator[T], but the transforms will be applied locally and not remotely in parallel. This class is **serializable** and can be passed to other remote tasks and actors. However, it should be read from at most one process at a time.""" # If a function passed to LocalIterator.for_each() has this method, # we will call it at the beginning of each data fetch call. This can be # used to measure the underlying wait latency for measurement purposes. ON_FETCH_START_HOOK_NAME = "_on_fetch_start" thread_local = threading.local() def __init__( self, base_iterator: Callable[[], Iterable[T]], shared_metrics: SharedMetrics, local_transforms: List[Callable[[Iterable], Any]] = None, timeout: int = None, name=None, ): """Create a local iterator (this is an internal function). Args: base_iterator: A function that produces the base iterator. This is a function so that we can ensure LocalIterator is serializable. shared_metrics: Existing metrics context or a new context. Should be the same for each chained iterator. local_transforms: A list of transformation functions to be applied on top of the base iterator. When iteration begins, we create the base iterator and apply these functions. This lazy creation ensures LocalIterator is serializable until you start iterating over it. timeout: Optional timeout in seconds for this iterator, after which _NextValueNotReady will be returned. This avoids blocking. name: Optional name for this iterator. """ assert isinstance(shared_metrics, SharedMetrics) self.base_iterator = base_iterator self.built_iterator = None self.local_transforms = local_transforms or [] self.shared_metrics = shared_metrics self.timeout = timeout self.name = name or "unknown" @staticmethod def get_metrics() -> MetricsContext: """Return the current metrics context. This can only be called within an iterator function.""" if ( not hasattr(LocalIterator.thread_local, "metrics") or LocalIterator.thread_local.metrics is None ): raise ValueError("Cannot access context outside an iterator.") return LocalIterator.thread_local.metrics def _build_once(self): if self.built_iterator is None: it = iter(self.base_iterator(self.timeout)) for fn in self.local_transforms: it = fn(it) self.built_iterator = it @contextmanager def _metrics_context(self): self.thread_local.metrics = self.shared_metrics.get() yield def __iter__(self): self._build_once() return self.built_iterator def __next__(self): self._build_once() return next(self.built_iterator) def __str__(self): return repr(self) def __repr__(self): return f"LocalIterator[{self.name}]" def transform(self, fn: Callable[[Iterable[T]], Iterable[U]]) -> "LocalIterator[U]": # TODO(ekl) can we automatically handle NextValueNotReady here? def apply_transform(it): for item in fn(it): yield item return LocalIterator( self.base_iterator, self.shared_metrics, self.local_transforms + [apply_transform], name=self.name + ".transform()", ) def for_each( self, fn: Callable[[T], U], max_concurrency=1, resources=None ) -> "LocalIterator[U]": if max_concurrency == 1: def apply_foreach(it): for item in it: if isinstance(item, _NextValueNotReady): yield item else: # Keep retrying the function until it returns a valid # value. This allows for non-blocking functions. while True: with self._metrics_context(): result = fn(item) yield result if not isinstance(result, _NextValueNotReady): break else: if resources is None: resources = {} def apply_foreach(it): cur = [] remote = ray.remote(fn).options(**resources) remote_fn = remote.remote for item in it: if isinstance(item, _NextValueNotReady): yield item else: if max_concurrency and len(cur) >= max_concurrency: finished, cur = ray.wait(cur) yield from ray.get(finished) cur.append(remote_fn(item)) while cur: finished, cur = ray.wait(cur) yield from ray.get(finished) if hasattr(fn, LocalIterator.ON_FETCH_START_HOOK_NAME): unwrapped = apply_foreach def add_wait_hooks(it): it = unwrapped(it) new_item = True while True: # Avoids calling on_fetch_start repeatedly if we are # yielding _NextValueNotReady. if new_item: with self._metrics_context(): fn._on_fetch_start() new_item = False item = next(it) if not isinstance(item, _NextValueNotReady): new_item = True yield item apply_foreach = add_wait_hooks return LocalIterator( self.base_iterator, self.shared_metrics, self.local_transforms + [apply_foreach], name=self.name + ".for_each()", ) def filter(self, fn: Callable[[T], bool]) -> "LocalIterator[T]": def apply_filter(it): for item in it: with self._metrics_context(): if isinstance(item, _NextValueNotReady) or fn(item): yield item return LocalIterator( self.base_iterator, self.shared_metrics, self.local_transforms + [apply_filter], name=self.name + ".filter()", ) def batch(self, n: int) -> "LocalIterator[List[T]]": def apply_batch(it): batch = [] for item in it: if isinstance(item, _NextValueNotReady): yield item else: batch.append(item) if len(batch) >= n: yield batch batch = [] if batch: yield batch return LocalIterator( self.base_iterator, self.shared_metrics, self.local_transforms + [apply_batch], name=self.name + f".batch({n})", ) def flatten(self) -> "LocalIterator[T[0]]": def apply_flatten(it): for item in it: if isinstance(item, _NextValueNotReady): yield item else: for subitem in item: yield subitem return LocalIterator( self.base_iterator, self.shared_metrics, self.local_transforms + [apply_flatten], name=self.name + ".flatten()", ) def shuffle(self, shuffle_buffer_size: int, seed: int = None) -> "LocalIterator[T]": """Shuffle items of this iterator Args: shuffle_buffer_size: The algorithm fills a buffer with shuffle_buffer_size elements and randomly samples elements from this buffer, replacing the selected elements with new elements. For perfect shuffling, this argument should be greater than or equal to the largest iterator size. seed: Seed to use for randomness. Default value is None. Returns: A new LocalIterator with shuffling applied """ shuffle_random = random.Random(seed) def apply_shuffle(it): buffer = [] for item in it: if isinstance(item, _NextValueNotReady): yield item else: buffer.append(item) if len(buffer) >= shuffle_buffer_size: yield buffer.pop(shuffle_random.randint(0, len(buffer) - 1)) while len(buffer) > 0: yield buffer.pop(shuffle_random.randint(0, len(buffer) - 1)) return LocalIterator( self.base_iterator, self.shared_metrics, self.local_transforms + [apply_shuffle], name=self.name + ".shuffle(shuffle_buffer_size={}, seed={})".format( shuffle_buffer_size, str(seed) if seed is not None else "None" ), ) def combine(self, fn: Callable[[T], List[U]]) -> "LocalIterator[U]": it = self.for_each(fn).flatten() it.name = self.name + ".combine()" return it def zip_with_source_actor(self): def zip_with_source(item): metrics = LocalIterator.get_metrics() if metrics.current_actor is None: raise ValueError("Could not identify source actor of item") return metrics.current_actor, item it = self.for_each(zip_with_source) it.name = self.name + ".zip_with_source_actor()" return it def take(self, n: int) -> List[T]: """Return up to the first n items from this iterator.""" out = [] for item in self: out.append(item) if len(out) >= n: break return out def show(self, n: int = 20): """Print up to the first n items from this iterator.""" i = 0 for item in self: print(item) i += 1 if i >= n: break def duplicate(self, n) -> List["LocalIterator[T]"]: """Copy this iterator `n` times, duplicating the data. The child iterators will be prioritized by how much of the parent stream they have consumed. That is, we will not allow children to fall behind, since that can cause infinite memory buildup in this operator. Returns: List[LocalIterator[T]]: child iterators that each have a copy of the data of this iterator. """ if n < 2: raise ValueError("Number of copies must be >= 2") queues = [] for _ in range(n): queues.append(collections.deque()) def fill_next(timeout): self.timeout = timeout item = next(self) for q in queues: q.append(item) def make_next(i): def gen(timeout): while True: my_len = len(queues[i]) max_len = max(len(q) for q in queues) # Yield to let other iterators that have fallen behind # process more items. if my_len < max_len: yield _NextValueNotReady() else: if len(queues[i]) == 0: try: fill_next(timeout) except StopIteration: return yield queues[i].popleft() return gen iterators = [] for i in range(n): iterators.append( LocalIterator( make_next(i), self.shared_metrics, [], name=self.name + f".duplicate[{i}]", ) ) return iterators def union( self, *others: "LocalIterator[T]", deterministic: bool = False, round_robin_weights: List[float] = None, ) -> "LocalIterator[T]": """Return an iterator that is the union of this and the others. Args: deterministic: If deterministic=True, we alternate between reading from one iterator and the others. Otherwise we return items from iterators as they become ready. round_robin_weights: List of weights to use for round robin mode. For example, [2, 1] will cause the iterator to pull twice as many items from the first iterator as the second. [2, 1, "*"] will cause as many items to be pulled as possible from the third iterator without blocking. This overrides the deterministic flag. """ for it in others: if not isinstance(it, LocalIterator): raise ValueError(f"other must be of type LocalIterator, got {type(it)}") active = [] parent_iters = [self] + list(others) shared_metrics = SharedMetrics(parents=[p.shared_metrics for p in parent_iters]) timeout = None if deterministic else 0 if round_robin_weights: if len(round_robin_weights) != len(parent_iters): raise ValueError( "Length of round robin weights must equal number of " "iterators total." ) timeouts = [0 if w == "*" else None for w in round_robin_weights] else: timeouts = [timeout] * len(parent_iters) round_robin_weights = [1] * len(parent_iters) for i, it in enumerate(parent_iters): active.append( LocalIterator( it.base_iterator, shared_metrics, it.local_transforms, timeout=timeouts[i], ) ) active = list(zip(round_robin_weights, active)) def build_union(timeout=None): while True: for weight, it in list(active): if weight == "*": max_pull = 100 # TOOD(ekl) how to best bound this? else: max_pull = _randomized_int_cast(weight) try: for _ in range(max_pull): item = next(it) if isinstance(item, _NextValueNotReady): if timeout is not None: yield item break else: yield item except StopIteration: active.remove((weight, it)) if not active: break return LocalIterator( build_union, shared_metrics, [], name=f"LocalUnion[{self}, {', '.join(map(str, others))}]", ) @Deprecated
LocalIterator
python
huggingface__transformers
tests/repo_utils/test_check_copies.py
{ "start": 8009, "end": 17551 }
class ____(unittest.TestCase): def test_find_code_in_transformers(self): with tempfile.TemporaryDirectory() as tmp_folder: create_tmp_repo(tmp_folder) with patch_transformer_repo_path(tmp_folder): code = find_code_in_transformers("models.bert.modeling_bert.BertAttention") reference_code = ( "class BertAttention(nn.Module):\n def __init__(self, config):\n super().__init__()\n" ) self.assertEqual(code, reference_code) def test_is_copy_consistent(self): path_to_check = ["src", "transformers", "models", "bertcopy", "modeling_bertcopy.py"] with tempfile.TemporaryDirectory() as tmp_folder: # Base check create_tmp_repo(tmp_folder) with patch_transformer_repo_path(tmp_folder): file_to_check = os.path.join(tmp_folder, *path_to_check) diffs = is_copy_consistent(file_to_check) self.assertEqual(diffs, []) # Base check with an inconsistency create_tmp_repo(tmp_folder) with patch_transformer_repo_path(tmp_folder): file_to_check = os.path.join(tmp_folder, *path_to_check) replace_in_file(file_to_check, "self.bertcopy(x)", "self.bert(x)") diffs = is_copy_consistent(file_to_check) self.assertEqual(diffs, [["models.bert.modeling_bert.BertModel", 22]]) _ = is_copy_consistent(file_to_check, overwrite=True) with open(file_to_check, encoding="utf-8") as f: self.assertEqual(f.read(), MOCK_BERT_COPY_CODE) def test_is_copy_consistent_with_ignored_match(self): path_to_check = ["src", "transformers", "models", "dummy_roberta_match", "modeling_dummy_roberta_match.py"] with tempfile.TemporaryDirectory() as tmp_folder: # Base check create_tmp_repo(tmp_folder) with patch_transformer_repo_path(tmp_folder): file_to_check = os.path.join(tmp_folder, *path_to_check) diffs = is_copy_consistent(file_to_check) self.assertEqual(diffs, []) def test_is_copy_consistent_with_ignored_no_match(self): path_to_check = [ "src", "transformers", "models", "dummy_roberta_no_match", "modeling_dummy_roberta_no_match.py", ] with tempfile.TemporaryDirectory() as tmp_folder: # Base check with an inconsistency create_tmp_repo(tmp_folder) with patch_transformer_repo_path(tmp_folder): file_to_check = os.path.join(tmp_folder, *path_to_check) diffs = is_copy_consistent(file_to_check) # line 6: `attr_2 = 3` in `MOCK_DUMMY_ROBERTA_CODE_NO_MATCH`. # (which has a leading `\n`.) self.assertEqual( diffs, [["models.dummy_bert_no_match.modeling_dummy_bert_no_match.BertDummyModel", 6]] ) _ = is_copy_consistent(file_to_check, overwrite=True) with open(file_to_check, encoding="utf-8") as f: self.assertEqual(f.read(), EXPECTED_REPLACED_CODE) def test_convert_to_localized_md(self): localized_readme = check_copies.LOCALIZED_READMES["README_zh-hans.md"] md_list = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the" " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for" " Self-supervised Learning of Language Representations](https://huggingface.co/papers/1909.11942), by Zhenzhong" " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1." " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace)," " released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and" " lighter](https://huggingface.co/papers/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same" " method has been applied to compress GPT2 into" " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into" " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation)," " Multilingual BERT into" " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German" " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**" " (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders" " as discriminators rather than generators](https://huggingface.co/papers/2003.10555) by Kevin Clark, Minh-Thang" " Luong, Quoc V. Le, Christopher D. Manning." ) localized_md_list = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" " Language Representations](https://huggingface.co/papers/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" ) converted_md_list_sample = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" " Language Representations](https://huggingface.co/papers/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1." " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文" " [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and" " lighter](https://huggingface.co/papers/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same" " method has been applied to compress GPT2 into" " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into" " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation)," " Multilingual BERT into" " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German" " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自" " Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather" " than generators](https://huggingface.co/papers/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le," " Christopher D. Manning 发布。\n" ) num_models_equal, converted_md_list = convert_to_localized_md( md_list, localized_md_list, localized_readme["format_model_list"] ) self.assertFalse(num_models_equal) self.assertEqual(converted_md_list, converted_md_list_sample) num_models_equal, converted_md_list = convert_to_localized_md( md_list, converted_md_list, localized_readme["format_model_list"] ) # Check whether the number of models is equal to README.md after conversion. self.assertTrue(num_models_equal) link_changed_md_list = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the" " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for" " Self-supervised Learning of Language Representations](https://huggingface.co/papers/1909.11942), by Zhenzhong" " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut." ) link_unchanged_md_list = ( "1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and" " the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" " Language Representations](https://huggingface.co/papers/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" ) converted_md_list_sample = ( "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" " Language Representations](https://huggingface.co/papers/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" ) num_models_equal, converted_md_list = convert_to_localized_md( link_changed_md_list, link_unchanged_md_list, localized_readme["format_model_list"] ) # Check if the model link is synchronized. self.assertEqual(converted_md_list, converted_md_list_sample)
CopyCheckTester
python
scrapy__scrapy
tests/test_webclient.py
{ "start": 6519, "end": 6747 }
class ____(resource.Resource): def render(self, request): request.setResponseCode(401) if request.args.get(b"showlength"): request.setHeader(b"content-length", b"0") return b""
ErrorResource
python
doocs__leetcode
solution/3300-3399/3326.Minimum Division Operations to Make Array Non Decreasing/Solution.py
{ "start": 178, "end": 503 }
class ____: def minOperations(self, nums: List[int]) -> int: ans = 0 for i in range(len(nums) - 2, -1, -1): if nums[i] > nums[i + 1]: nums[i] = lpf[nums[i]] if nums[i] > nums[i + 1]: return -1 ans += 1 return ans
Solution
python
pytorch__pytorch
torch/_inductor/pattern_matcher.py
{ "start": 5306, "end": 12656 }
class ____: """ Represents a successfully matched pattern. The `Match` object is returned to represent a successfully matched pattern. Included in the Match are the pattern that was matched, the graph nodes matched, and any args that were used during the matching. The args and kwargs are specific to the type of pattern that was matched and provide hints about what was matched. """ pattern: PatternExpr args: list[Any] kwargs: dict[str, Any] nodes: list[torch.fx.Node] targets: dict[_TargetExpr, torch.fx.node.Target] ctx: MatchContext replacement_graph: Optional[torch.fx.GraphModule] def __init__( self, ctx: MatchContext, pattern: PatternExpr, args: Optional[Sequence[Any]] = None, kwargs: Optional[dict[str, Any]] = None, ) -> None: super().__init__() self.pattern = pattern # The input nodes that must be passed in to the result self.args = list(args or []) self.kwargs = kwargs or {} # The nodes matched in this expression self.nodes = [] # Mapping CallFunction to the node.target self.targets = {} self.ctx = ctx self.replacement_graph = None @property def graph(self) -> torch.fx.Graph: return self.ctx.graph def extend(self, other: Match) -> None: if self.kwargs: for key in OrderedSet(self.kwargs.keys()) & OrderedSet(other.kwargs.keys()): if self.kwargs[key] != other.kwargs[key]: raise FailedMatch("kwarg mismatch: {}", key) self.args.extend(other.args) self.nodes.extend(other.nodes) self.kwargs.update(other.kwargs) self.targets.update(other.targets) def bundle(self) -> Match: # Wrap args in an extra list self.args = [tuple(self.args)] if self.args else [] return self def __repr__(self) -> str: return f"Match(..., {self.args}, {self.kwargs})" def erase_nodes(self) -> None: graph = self.graph for n in reversed(self.nodes): if not n._erased and not n.users: graph.erase_node(n) def output_nodes(self) -> list[Optional[torch.fx.Node]]: return [ (self.ctx.pattern_to_node[p] if p is not None else None) for p in self.ctx.outputs ] def output_node(self) -> torch.fx.Node: return next(p for p in self.output_nodes() if p) def replace_with_graph( self, replacement_graph: torch.fx.Graph, args: Sequence[Any] ) -> None: ReplacementPatternEntry.replace_with_graph( self, self.ctx.graph, replacement_graph, args ) def replace_by_example( self, replacement_fn: ReplaceFn, args: Sequence[Any], trace_fn: Optional[TraceFn] = None, run_functional_passes: bool = True, ) -> None: """Replace with a graph generated by tracing the replacement_fn. Args: run_functional_passes (bool). If we should run passes that assume functional IR (like DCE, remove_noop_ops), on the replacement graph. """ from torch._inductor.virtualized import NullHandler, V context = ( V.fake_mode if (not isinstance(V.fake_mode, NullHandler) or (V.fake_mode is None)) else contextlib.nullcontext() ) def should_propagate_eager_input_vals(nodes: list[torch.fx.Node]) -> bool: if len(nodes) != 1: return False node = nodes[0] if "eager_input_vals" not in node.meta: return False return node.target in OrderedSet( [ torch.ops.higher_order.triton_kernel_wrapper_functional, torch.ops.higher_order.auto_functionalized, torch.ops.higher_order.auto_functionalized_v2, ] ) # pyrefly: ignore [bad-context-manager] with context: if trace_fn is None: trace_fn = functools.partial( fwd_only, run_functional_passes=run_functional_passes ) if should_propagate_eager_input_vals(self.nodes): # Our strategy is: # 1) trace out the graph with eager_input_vals (which have accurate eager-mode metadata) # 2) trace out the graph with vals (which have the accurate Inductor metadata) # 3) Propagate the eager_input_vals from the first graph to the second. # 4) Use the second graph as the replacement graph. # Construct a map of node -> FakeTensor val in eager_input_vals node_to_val = {} fake_args, fake_kwargs = self.nodes[0].meta["eager_input_vals"] fake_kwargs = {**fake_kwargs} match_args, match_kwargs = tuple(self.args), self.kwargs def record(node: torch.fx.Node, val: Any) -> None: if isinstance(node, torch.fx.Node): node_to_val[node] = val torch.utils._pytree.tree_map( record, (match_args, match_kwargs), (fake_args, fake_kwargs) ) # map args to their FakeTensor val in eager_input_vals example_vals = torch.fx.map_arg(args, lambda arg: node_to_val[arg]) # first graph graph_with_eager_vals = trace_fn(replacement_fn, example_vals) # second graph example_vals = torch.fx.map_arg(args, lambda arg: arg.meta["val"]) replacement = trace_fn(graph_with_eager_vals, example_vals) # propagate metadata from first graph to second # NB: This assertion might not be true in general, but it is true for # the two use cases we have # (triton_kernel_wrapper_functional, auto_functionalized) assert len(graph_with_eager_vals.graph.nodes) == len( replacement.graph.nodes ) for old_node, new_node in zip( graph_with_eager_vals.graph.nodes, replacement.graph.nodes ): if "eager_input_vals" in old_node.meta: new_node.meta["eager_input_vals"] = old_node.meta[ "eager_input_vals" ] else: example_vals = torch.fx.map_arg( args, lambda arg: arg.meta["val"] if "val" in arg.meta else arg.meta["example_value"], ) replacement = trace_fn(replacement_fn, example_vals) if len(self.nodes) == 1: for n in replacement.graph.nodes: _transfer_meta( new_meta=n.meta, old_node=self.nodes[0], pass_name="replace_by_example", ) ReplacementPatternEntry.replace_with_graph( self, self.ctx.graph, replacement, args, )
Match
python
tensorflow__tensorflow
tensorflow/python/keras/optimizer_v2/learning_rate_schedule.py
{ "start": 20242, "end": 23794 }
class ____(LearningRateSchedule): """A LearningRateSchedule that uses a cosine decay schedule. See [Loshchilov & Hutter, ICLR2016](https://arxiv.org/abs/1608.03983), SGDR: Stochastic Gradient Descent with Warm Restarts. When training a model, it is often useful to lower the learning rate as the training progresses. This schedule applies a cosine decay function to an optimizer step, given a provided initial learning rate. It requires a `step` value to compute the decayed learning rate. You can just pass a TensorFlow variable that you increment at each training step. The schedule a 1-arg callable that produces a decayed learning rate when passed the current optimizer step. This can be useful for changing the learning rate value across different invocations of optimizer functions. It is computed as: ```python def decayed_learning_rate(step): step = min(step, decay_steps) cosine_decay = 0.5 * (1 + cos(pi * step / decay_steps)) decayed = (1 - alpha) * cosine_decay + alpha return initial_learning_rate * decayed ``` Example usage: ```python decay_steps = 1000 lr_decayed_fn = tf.keras.optimizers.schedules.CosineDecay( initial_learning_rate, decay_steps) ``` You can pass this schedule directly into a `tf.keras.optimizers.Optimizer` as the learning rate. The learning rate schedule is also serializable and deserializable using `tf.keras.optimizers.schedules.serialize` and `tf.keras.optimizers.schedules.deserialize`. Returns: A 1-arg callable learning rate schedule that takes the current optimizer step and outputs the decayed learning rate, a scalar `Tensor` of the same type as `initial_learning_rate`. """ def __init__( self, initial_learning_rate, decay_steps, alpha=0.0, name=None): """Applies cosine decay to the learning rate. Args: initial_learning_rate: A scalar `float32` or `float64` Tensor or a Python number. The initial learning rate. decay_steps: A scalar `int32` or `int64` `Tensor` or a Python number. Number of steps to decay over. alpha: A scalar `float32` or `float64` Tensor or a Python number. Minimum learning rate value as a fraction of initial_learning_rate. name: String. Optional name of the operation. Defaults to 'CosineDecay'. """ super(CosineDecay, self).__init__() self.initial_learning_rate = initial_learning_rate self.decay_steps = decay_steps self.alpha = alpha self.name = name def __call__(self, step): with ops.name_scope_v2(self.name or "CosineDecay"): initial_learning_rate = ( tensor_conversion.convert_to_tensor_v2_with_dispatch( self.initial_learning_rate, name="initial_learning_rate" ) ) dtype = initial_learning_rate.dtype decay_steps = math_ops.cast(self.decay_steps, dtype) global_step_recomp = math_ops.cast(step, dtype) global_step_recomp = math_ops.minimum(global_step_recomp, decay_steps) completed_fraction = global_step_recomp / decay_steps cosine_decayed = 0.5 * (1.0 + math_ops.cos( constant_op.constant(math.pi) * completed_fraction)) decayed = (1 - self.alpha) * cosine_decayed + self.alpha return math_ops.multiply(initial_learning_rate, decayed) def get_config(self): return { "initial_learning_rate": self.initial_learning_rate, "decay_steps": self.decay_steps, "alpha": self.alpha, "name": self.name }
CosineDecay
python
airbytehq__airbyte
airbyte-integrations/bases/connector-acceptance-test/connector_acceptance_test/config.py
{ "start": 6743, "end": 7591 }
class ____(BaseConfig): secrets_path: str = Field(None, description="Path in the setup/teardown container at which to copy connector secrets.") client_container_dockerfile_path: str = Field( None, description="Path to Dockerfile to run before each test for which a config is provided." ) setup_command: Optional[List[str]] = Field(None, description="Command for running the setup/teardown container for setup.") teardown_command: Optional[List[str]] = Field(None, description="Command for running the setup/teardown container for teardown.") between_syncs_command: Optional[List[str]] = Field(None, description="Command to run between syncs that occur in a test.") final_teardown_command: Optional[List[str]] = Field(None, description="Command for running teardown after all tests have run.")
ClientContainerConfig
python
pypa__setuptools
setuptools/build_meta.py
{ "start": 19078, "end": 20140 }
class ____(SetuptoolsDeprecationWarning): _SUMMARY = "wheel.bdist_wheel is deprecated, please import it from setuptools" _DETAILS = """ Ensure that any custom bdist_wheel implementation is a subclass of setuptools.command.bdist_wheel.bdist_wheel. """ _DUE_DATE = (2025, 10, 15) # Initially introduced in 2024/10/15, but maybe too disruptive to be enforced? _SEE_URL = "https://github.com/pypa/wheel/pull/631" # The primary backend _BACKEND = _BuildMetaBackend() get_requires_for_build_wheel = _BACKEND.get_requires_for_build_wheel get_requires_for_build_sdist = _BACKEND.get_requires_for_build_sdist prepare_metadata_for_build_wheel = _BACKEND.prepare_metadata_for_build_wheel build_wheel = _BACKEND.build_wheel build_sdist = _BACKEND.build_sdist get_requires_for_build_editable = _BACKEND.get_requires_for_build_editable prepare_metadata_for_build_editable = _BACKEND.prepare_metadata_for_build_editable build_editable = _BACKEND.build_editable # The legacy backend __legacy__ = _BuildMetaLegacyBackend()
_IncompatibleBdistWheel
python
doocs__leetcode
solution/1400-1499/1429.First Unique Number/Solution.py
{ "start": 0, "end": 639 }
class ____: def __init__(self, nums: List[int]): self.cnt = Counter(nums) self.unique = OrderedDict({v: 1 for v in nums if self.cnt[v] == 1}) def showFirstUnique(self) -> int: return -1 if not self.unique else next(v for v in self.unique.keys()) def add(self, value: int) -> None: self.cnt[value] += 1 if self.cnt[value] == 1: self.unique[value] = 1 elif value in self.unique: self.unique.pop(value) # Your FirstUnique object will be instantiated and called as such: # obj = FirstUnique(nums) # param_1 = obj.showFirstUnique() # obj.add(value)
FirstUnique
python
huggingface__transformers
tests/quantization/quanto_integration/test_quanto.py
{ "start": 15986, "end": 16158 }
class ____(QuantoQuantizationTest): EXPECTED_OUTPUTS = "Hello my name is John, I am a professional photographer, I" weights = "int4"
QuantoQuantizationQBitsTensorTest
python
getsentry__sentry
src/sentry/api/event_search.py
{ "start": 23091, "end": 23449 }
class ____(NamedTuple): key: AggregateKey operator: str value: SearchValue def to_query_string(self) -> str: return f"{self.key.name}:{self.operator}{self.value.to_query_string()}" def __str__(self) -> str: return f"{self.key.name}{self.operator}{self.value.raw_value}" @dataclass # pycqa/pycodestyle#1277
AggregateFilter
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constrainedTypeVar13.py
{ "start": 884, "end": 2843 }
class ____(Generic[_T1, _T2, _T3, _P, Unpack[_Ts]]): def meth1( self, val1: _T1, val2: _T2, val3: _T3, cond: bool ) -> list[_T1] | list[_T2] | list[_T3]: if cond: # This should generate an error. return [0] if cond or 3 > 2: if isinstance(val1, str): # This should generate an error. return [0] else: return [0] if cond or 3 > 2: if isinstance(val3, B): return [B()] else: # This should generate an error. return [C()] if cond or 3 > 2: if not isinstance(val3, B) and not isinstance(val3, C): return [A()] return [val1] def meth2(self, val1: _T1) -> _T1: val2 = val1 while True: if isinstance(val2, str): return "hi" val2 = val2 = val1 if isinstance(val2, int): return 0 def meth3(self, val1: _T1, val2: _T3) -> _T1: if isinstance(val2, A): # This should generate an error. return 1 if isinstance(val2, B): if isinstance(val1, str): return "" if isinstance(val1, int): if isinstance(val2, B): # This should generate an error. return "" raise BaseException() def func3(s: AnyStr, y: AnyStr | None = None) -> AnyStr: if isinstance(s, str): if y is None: pass return "" else: raise NotImplementedError def func4(t: _T3) -> _T3: match t: case A(): return A() case B(): return B() case C(): return C() def func5(t: _T3) -> _T3: if isinstance(t, A): return A() elif isinstance(t, B): return B() elif isinstance(t, C): return C()
Class1
python
PrefectHQ__prefect
src/prefect/server/orchestration/core_policy.py
{ "start": 8641, "end": 17905 }
class ____(TaskRunOrchestrationRule): """ Checks relevant concurrency slots are available before entering a Running state. This rule checks if concurrency limits have been set on the tags associated with a TaskRun. If so, a concurrency slot will be secured against each concurrency limit before being allowed to transition into a running state. If a concurrency limit has been reached, the client will be instructed to delay the transition for the duration specified by the "PREFECT_TASK_RUN_TAG_CONCURRENCY_SLOT_WAIT_SECONDS" setting before trying again. If the concurrency limit set on a tag is 0, the transition will be aborted to prevent deadlocks. """ FROM_STATES = ALL_ORCHESTRATION_STATES TO_STATES = {StateType.RUNNING} async def before_transition( self, initial_state: states.State[Any] | None, proposed_state: states.State[Any] | None, context: OrchestrationContext[orm_models.TaskRun, core.TaskRunPolicy], ) -> None: settings = get_current_settings() self._applied_limits: list[str] = [] self._acquired_v2_lease_ids: list[UUID] = [] v1_limits = ( await concurrency_limits.filter_concurrency_limits_for_orchestration( context.session, tags=context.run.tags ) ) v2_names = [f"tag:{tag}" for tag in context.run.tags] v2_limits = await concurrency_limits_v2.bulk_read_concurrency_limits( context.session, names=v2_names ) # Handle V2 limits first (if they exist) v2_tags: set[str] = set() # Track which tags have V2 limits if v2_limits: lease_storage = get_concurrency_lease_storage() # Track which tags have V2 limits to exclude from V1 processing v2_tags = { limit.name.removeprefix("tag:") for limit in v2_limits if limit.active } # Check for zero limits that would deadlock for limit in v2_limits: if limit.active and limit.limit == 0: # Clean up any already acquired V2 leases for lease_id in self._acquired_v2_lease_ids: try: lease = await lease_storage.read_lease( lease_id=lease_id, ) if lease: await concurrency_limits_v2.bulk_decrement_active_slots( session=context.session, concurrency_limit_ids=lease.resource_ids, slots=lease.metadata.slots if lease.metadata else 1, ) await lease_storage.revoke_lease( lease_id=lease.id, ) except Exception: logger.warning( f"Failed to clean up lease {lease_id} during abort", exc_info=True, ) await self.abort_transition( reason=f'The concurrency limit on tag "{limit.name.removeprefix("tag:")}" is 0 and will deadlock if the task tries to run again.', ) # Try to acquire V2 slots with lease (exclude zero limits as they're handled above) active_v2_limits = [ limit for limit in v2_limits if limit.active and limit.limit > 0 ] if active_v2_limits: # Attempt to acquire slots async with provide_database_interface().session_context( begin_transaction=True ) as session: acquired = await concurrency_limits_v2.bulk_increment_active_slots( session=session, concurrency_limit_ids=[limit.id for limit in active_v2_limits], slots=1, ) if not acquired: await session.rollback() # Slots not available, delay transition delay_seconds = clamped_poisson_interval( average_interval=settings.server.tasks.tag_concurrency_slot_wait_seconds, ) await self.delay_transition( delay_seconds=round(delay_seconds), reason=f"Concurrency limit reached for tags: {', '.join([limit.name.removeprefix('tag:') for limit in active_v2_limits])}", ) return # Create lease for acquired slots with minimal metadata first lease = await lease_storage.create_lease( resource_ids=[limit.id for limit in active_v2_limits], ttl=concurrency_limits.V1_LEASE_TTL, metadata=ConcurrencyLimitLeaseMetadata( slots=1, holder=ConcurrencyLeaseHolder( type="task_run", id=context.run.id, ), ), ) self._acquired_v2_lease_ids.append(lease.id) remaining_v1_limits = [limit for limit in v1_limits if limit.tag not in v2_tags] if remaining_v1_limits: run_limits = {limit.tag: limit for limit in v1_limits} for tag, cl in run_limits.items(): limit = cl.concurrency_limit if limit == 0: # limits of 0 will deadlock, and the transition needs to abort for stale_tag in self._applied_limits: stale_limit = run_limits.get(stale_tag, None) if stale_limit: active_slots: set[str] = set(stale_limit.active_slots) active_slots.discard(str(context.run.id)) stale_limit.active_slots = list(active_slots) await self.abort_transition( reason=( f'The concurrency limit on tag "{tag}" is 0 and will deadlock' " if the task tries to run again." ), ) elif len(cl.active_slots) >= limit: # if the limit has already been reached, delay the transition for stale_tag in self._applied_limits: stale_limit = run_limits.get(stale_tag, None) if stale_limit: active_slots = set(stale_limit.active_slots) active_slots.discard(str(context.run.id)) stale_limit.active_slots = list(active_slots) await self.delay_transition( delay_seconds=int( settings.server.tasks.tag_concurrency_slot_wait_seconds ), # PREFECT_TASK_RUN_TAG_CONCURRENCY_SLOT_WAIT_SECONDS.value(), reason=f"Concurrency limit for the {tag} tag has been reached", ) else: # log the TaskRun ID to active_slots self._applied_limits.append(tag) active_slots = set(cl.active_slots) active_slots.add(str(context.run.id)) cl.active_slots = list(active_slots) async def cleanup( self, initial_state: states.State[Any] | None, validated_state: states.State[Any] | None, context: OrchestrationContext[orm_models.TaskRun, core.TaskRunPolicy], ) -> None: lease_storage = get_concurrency_lease_storage() # Clean up V2 leases for lease_id in self._acquired_v2_lease_ids: try: lease = await lease_storage.read_lease( lease_id=lease_id, ) if lease: await concurrency_limits_v2.bulk_decrement_active_slots( session=context.session, concurrency_limit_ids=lease.resource_ids, slots=lease.metadata.slots if lease.metadata else 1, ) await lease_storage.revoke_lease( lease_id=lease.id, ) else: logger.warning(f"Lease {lease_id} not found during cleanup") except Exception: logger.warning(f"Failed to clean up lease {lease_id}", exc_info=True) for tag in self._applied_limits: cl = await concurrency_limits.read_concurrency_limit_by_tag( context.session, tag ) if cl: active_slots = set(cl.active_slots) active_slots.discard(str(context.run.id)) cl.active_slots = list(active_slots)
SecureTaskConcurrencySlots
python
pytorch__pytorch
torch/distributed/tensor/parallel/style.py
{ "start": 1036, "end": 7051 }
class ____(ParallelStyle): """ Partition a compatible nn.Module in a column-wise fashion. Currently supports nn.Linear and nn.Embedding. Users can compose it together with RowwiseParallel to achieve the sharding of more complicated modules. (i.e. MLP, Attention) Keyword Args: input_layouts (Placement, optional): The DTensor layout of input tensor for the nn.Module, this is used to annotate the input tensor to become a DTensor. If not specified, we assume the input tensor to be replicated. output_layouts (Placement, optional): The DTensor layout of the output for the nn.Module, this is used to ensure the output of the nn.Module with the user desired layout. If not specified, the output tensor is sharded on the last dimension. use_local_output (bool, optional): Whether to use local :class:`torch.Tensor` instead of :class:`DTensor` for the module output, default: True. Returns: A :class:`ParallelStyle` object that represents Colwise sharding of the nn.Module. Example:: >>> # xdoctest: +SKIP(failing) >>> from torch.distributed.tensor.parallel import parallelize_module, ColwiseParallel >>> from torch.distributed.device_mesh import init_device_mesh >>> ... >>> m = Model(...) # m is a nn.Module that contains a "w1" nn.Linear submodule >>> tp_mesh = init_device_mesh("cuda", (8,)) >>> >>> # By default, the input of the "w1" Linear will be converted to Replicated DTensor >>> # and the output of "w1" will return :class:`torch.Tensor` that shards on the last dim. >>> >>> sharded_mod = parallelize_module(m, tp_mesh, {"w1": ColwiseParallel()}) >>> ... .. note:: By default ``ColwiseParallel`` output is sharded on the last dimension if the ``output_layouts`` not specified, if there're operators that require specific tensor shape (i.e. before the paired ``RowwiseParallel``), keep in mind that if the output is sharded the operator might need to be adjusted to the sharded size. """ def __init__( self, *, input_layouts: Placement | None = None, output_layouts: Placement | None = None, use_local_output: bool = True, ): super().__init__() self.input_layouts = (input_layouts or Replicate(),) self.output_layouts = (output_layouts or Shard(-1),) # colwise linear runtime sharding (desired sharding): # 1. requires replicate input # 2. shard output on last dim self.desired_input_layouts = (Replicate(),) self.use_local_output = use_local_output @staticmethod def _prepare_input_fn( input_layouts, desired_input_layouts, mod, inputs, device_mesh ): # TODO: figure out dynamo support for instance method and switch this to instance method # annotate module input placements/sharding with input_layouts input_tensor = inputs[0] if not isinstance(input_tensor, DTensor): input_tensor = DTensor.from_local( input_tensor, device_mesh, input_layouts, run_check=False ) # transform the input layouts to the desired layouts of ColwiseParallel if input_layouts != desired_input_layouts: input_tensor = input_tensor.redistribute( placements=desired_input_layouts, async_op=True ) return input_tensor def _partition_linear_fn(self, name, module, device_mesh): # colwise shard weight/bias to Shard(0), weight be Shard(0) # means Colwise as Linear is input * weight^T + bias, where # weight would become Shard(1) for name, param in module.named_parameters(): dist_param = nn.Parameter( distribute_tensor( param, device_mesh, [Shard(0)], src_data_rank=self.src_data_rank ) ) module.register_parameter(name, dist_param) def _partition_embedding_fn(self, name, module, device_mesh): # colwise shard embedding.weight is straight forward as Shard(1) for name, param in module.named_parameters(): dist_param = nn.Parameter( distribute_tensor( param, device_mesh, [Shard(1)], src_data_rank=self.src_data_rank ) ) module.register_parameter(name, dist_param) @staticmethod def _prepare_output_fn(output_layouts, use_local_output, mod, outputs, device_mesh): # outputs is a shard on last dimension DTensor, i.e. Shard(-1) if outputs.placements != output_layouts: outputs = outputs.redistribute(placements=output_layouts, async_op=True) # back to local tensor return outputs.to_local() if use_local_output else outputs def _apply(self, module: nn.Module, device_mesh: DeviceMesh) -> nn.Module: if isinstance(module, nn.Linear): partition_fn = self._partition_linear_fn elif isinstance(module, nn.Embedding): partition_fn = self._partition_embedding_fn else: raise NotImplementedError( "ColwiseParallel currently only support nn.Linear and nn.Embedding!" ) return distribute_module( module, device_mesh, partition_fn, partial( self._prepare_input_fn, self.input_layouts, self.desired_input_layouts ), partial( self._prepare_output_fn, self.output_layouts, self.use_local_output ), ) def __repr__(self) -> str: tmpstr = self.__class__.__name__ + "(" tmpstr += f"input_layouts={self.input_layouts}, " tmpstr += f"output_layouts={self.output_layouts}, " tmpstr += f"use_local_output={self.use_local_output}" tmpstr += ")" return tmpstr
ColwiseParallel
python
numba__numba
numba/cuda/tests/doc_examples/test_cg.py
{ "start": 529, "end": 2905 }
class ____(CUDATestCase): def test_ex_grid_sync(self): # magictoken.ex_grid_sync_kernel.begin from numba import cuda, int32 import numpy as np sig = (int32[:,::1],) @cuda.jit(sig) def sequential_rows(M): col = cuda.grid(1) g = cuda.cg.this_grid() rows = M.shape[0] cols = M.shape[1] for row in range(1, rows): opposite = cols - col - 1 # Each row's elements are one greater than the previous row M[row, col] = M[row - 1, opposite] + 1 # Wait until all threads have written their column element, # and that the write is visible to all other threads g.sync() # magictoken.ex_grid_sync_kernel.end # magictoken.ex_grid_sync_data.begin # Empty input data A = np.zeros((1024, 1024), dtype=np.int32) # A somewhat arbitrary choice (one warp), but generally smaller block sizes # allow more blocks to be launched (noting that other limitations on # occupancy apply such as shared memory size) blockdim = 32 griddim = A.shape[1] // blockdim # magictoken.ex_grid_sync_data.end # Skip this test if the grid size used in the example is too large for # a cooperative launch on the current GPU mb = sequential_rows.overloads[sig].max_cooperative_grid_blocks(blockdim) if mb < griddim: self.skipTest('Device does not support a large enough coop grid') # magictoken.ex_grid_sync_launch.begin # Kernel launch - this is implicitly a cooperative launch sequential_rows[griddim, blockdim](A) # What do the results look like? # print(A) # # [[ 0 0 0 ... 0 0 0] # [ 1 1 1 ... 1 1 1] # [ 2 2 2 ... 2 2 2] # ... # [1021 1021 1021 ... 1021 1021 1021] # [1022 1022 1022 ... 1022 1022 1022] # [1023 1023 1023 ... 1023 1023 1023]] # magictoken.ex_grid_sync_launch.end # Sanity check - are the results what we expect? reference = np.tile(np.arange(1024), (1024, 1)).T np.testing.assert_equal(A, reference) if __name__ == '__main__': unittest.main()
TestCooperativeGroups
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-ads/source_google_ads/components.py
{ "start": 33562, "end": 33729 }
class ____: inside_record: bool = False record_text_buffer: List[str] = field(default_factory=list) record_nesting_depth: int = 0 @dataclass
RecordParseState
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/input/base.py
{ "start": 2288, "end": 2587 }
class ____(Input): """ Abstraction for pipe input. """ @abstractmethod def send_bytes(self, data: bytes) -> None: """Feed byte string into the pipe""" @abstractmethod def send_text(self, data: str) -> None: """Feed a text string into the pipe"""
PipeInput
python
pandas-dev__pandas
pandas/tests/frame/test_constructors.py
{ "start": 116624, "end": 122273 }
class ____: @pytest.fixture(params=[list, dict, None]) def box(self, request): return request.param @pytest.fixture def constructor(self, frame_or_series, box): extra = {"index": range(2)} if frame_or_series is DataFrame: extra["columns"] = ["A"] if box is None: return functools.partial(frame_or_series, **extra) elif box is dict: if frame_or_series is Series: return lambda x, **kwargs: frame_or_series( {0: x, 1: x}, **extra, **kwargs ) else: return lambda x, **kwargs: frame_or_series({"A": x}, **extra, **kwargs) elif frame_or_series is Series: return lambda x, **kwargs: frame_or_series([x, x], **extra, **kwargs) else: return lambda x, **kwargs: frame_or_series({"A": [x, x]}, **extra, **kwargs) @pytest.mark.parametrize("dtype", ["M8[ns]", "m8[ns]"]) def test_from_nat_scalar(self, dtype, constructor): obj = constructor(pd.NaT, dtype=dtype) assert np.all(obj.dtypes == dtype) assert np.all(obj.isna()) def test_from_timedelta_scalar_preserves_nanos(self, constructor): td = Timedelta(1) obj = constructor(td, dtype="m8[ns]") assert get1(obj) == td def test_from_timestamp_scalar_preserves_nanos(self, constructor, fixed_now_ts): ts = fixed_now_ts + Timedelta(1) obj = constructor(ts, dtype="M8[ns]") assert get1(obj) == ts def test_from_timedelta64_scalar_object(self, constructor): td = Timedelta(1) td64 = td.to_timedelta64() obj = constructor(td64, dtype=object) assert isinstance(get1(obj), np.timedelta64) @pytest.mark.parametrize("cls", [np.datetime64, np.timedelta64]) def test_from_scalar_datetimelike_mismatched(self, constructor, cls): scalar = cls("NaT", "ns") dtype = {np.datetime64: "m8[ns]", np.timedelta64: "M8[ns]"}[cls] if cls is np.datetime64: msg1 = "Invalid type for timedelta scalar: <class 'numpy.datetime64'>" else: msg1 = "<class 'numpy.timedelta64'> is not convertible to datetime" msg = "|".join(["Cannot cast", msg1]) with pytest.raises(TypeError, match=msg): constructor(scalar, dtype=dtype) scalar = cls(4, "ns") with pytest.raises(TypeError, match=msg): constructor(scalar, dtype=dtype) @pytest.mark.parametrize("cls", [datetime, np.datetime64]) def test_from_out_of_bounds_ns_datetime( self, constructor, cls, request, box, frame_or_series ): # scalar that won't fit in nanosecond dt64, but will fit in microsecond scalar = datetime(9999, 1, 1) exp_dtype = "M8[us]" # pydatetime objects default to this reso if cls is np.datetime64: scalar = np.datetime64(scalar, "D") exp_dtype = "M8[s]" # closest reso to input result = constructor(scalar) item = get1(result) dtype = tm.get_dtype(result) assert type(item) is Timestamp assert item.asm8.dtype == exp_dtype assert dtype == exp_dtype def test_out_of_s_bounds_datetime64(self, constructor): scalar = np.datetime64(np.iinfo(np.int64).max, "D") result = constructor(scalar) item = get1(result) assert type(item) is np.datetime64 dtype = tm.get_dtype(result) assert dtype == object @pytest.mark.parametrize("cls", [timedelta, np.timedelta64]) def test_from_out_of_bounds_ns_timedelta( self, constructor, cls, request, box, frame_or_series ): # scalar that won't fit in nanosecond td64, but will fit in microsecond if box is list or (frame_or_series is Series and box is dict): mark = pytest.mark.xfail( reason="TimedeltaArray constructor has been updated to cast td64 " "to non-nano, but TimedeltaArray._from_sequence has not", strict=True, ) request.applymarker(mark) scalar = datetime(9999, 1, 1) - datetime(1970, 1, 1) exp_dtype = "m8[us]" # smallest reso that fits if cls is np.timedelta64: scalar = np.timedelta64(scalar, "D") exp_dtype = "m8[s]" # closest reso to input result = constructor(scalar) item = get1(result) dtype = tm.get_dtype(result) assert type(item) is Timedelta assert item.asm8.dtype == exp_dtype assert dtype == exp_dtype @pytest.mark.parametrize("cls", [np.datetime64, np.timedelta64]) def test_out_of_s_bounds_timedelta64(self, constructor, cls): scalar = cls(np.iinfo(np.int64).max, "D") result = constructor(scalar) item = get1(result) assert type(item) is cls dtype = tm.get_dtype(result) assert dtype == object def test_tzaware_data_tznaive_dtype(self, constructor, box, frame_or_series): tz = "US/Eastern" ts = Timestamp("2019", tz=tz) if box is None or (frame_or_series is DataFrame and box is dict): msg = "Cannot unbox tzaware Timestamp to tznaive dtype" err = TypeError else: msg = ( "Cannot convert timezone-aware data to timezone-naive dtype. " r"Use pd.Series\(values\).dt.tz_localize\(None\) instead." ) err = ValueError with pytest.raises(err, match=msg): constructor(ts, dtype="M8[ns]") # TODO: better location for this test?
TestFromScalar
python
apache__airflow
helm-tests/tests/helm_tests/other/test_flower.py
{ "start": 22514, "end": 25966 }
class ____: """Tests flower network policy.""" def test_off_by_default(self): docs = render_chart( show_only=["templates/flower/flower-networkpolicy.yaml"], ) assert len(docs) == 0 def test_defaults(self): docs = render_chart( values={ "networkPolicies": {"enabled": True}, "flower": { "enabled": True, "networkPolicy": { "ingress": { "from": [{"namespaceSelector": {"matchLabels": {"release": "myrelease"}}}] } }, }, }, show_only=["templates/flower/flower-networkpolicy.yaml"], ) assert len(docs) == 1 assert docs[0]["kind"] == "NetworkPolicy" assert jmespath.search("spec.ingress[0].from", docs[0]) == [ {"namespaceSelector": {"matchLabels": {"release": "myrelease"}}} ] assert jmespath.search("spec.ingress[0].ports", docs[0]) == [{"port": 5555}] @pytest.mark.parametrize( ("ports", "expected_ports"), [ ([{"port": "sidecar"}], [{"port": "sidecar"}]), ( [ {"port": "{{ .Values.ports.flowerUI }}"}, {"port": 80}, ], [ {"port": 5555}, {"port": 80}, ], ), ], ) def test_ports_overrides(self, ports, expected_ports): docs = render_chart( values={ "networkPolicies": {"enabled": True}, "flower": { "enabled": True, "networkPolicy": { "ingress": { "from": [{"namespaceSelector": {"matchLabels": {"release": "myrelease"}}}], "ports": ports, } }, }, }, show_only=["templates/flower/flower-networkpolicy.yaml"], ) assert expected_ports == jmespath.search("spec.ingress[0].ports", docs[0]) def test_deprecated_from_param(self): docs = render_chart( values={ "networkPolicies": {"enabled": True}, "flower": { "enabled": True, "extraNetworkPolicies": [ {"namespaceSelector": {"matchLabels": {"release": "myrelease"}}} ], }, }, show_only=["templates/flower/flower-networkpolicy.yaml"], ) assert jmespath.search("spec.ingress[0].from", docs[0]) == [ {"namespaceSelector": {"matchLabels": {"release": "myrelease"}}} ] def test_should_add_component_specific_labels(self): docs = render_chart( values={ "networkPolicies": {"enabled": True}, "flower": { "enabled": True, "labels": {"test_label": "test_label_value"}, }, }, show_only=["templates/flower/flower-networkpolicy.yaml"], ) assert "test_label" in jmespath.search("metadata.labels", docs[0]) assert jmespath.search("metadata.labels", docs[0])["test_label"] == "test_label_value"
TestFlowerNetworkPolicy
python
PrefectHQ__prefect
tests/test_background_tasks.py
{ "start": 8881, "end": 9255 }
class ____: async def test_call(self, async_foo_task: Task[Any, int]): result = await async_foo_task(42) assert result == 42 async def test_call_with_return_state(self, async_foo_task: Task[Any, int]): state = await async_foo_task(42, return_state=True) assert state.is_completed() assert await state.result() == 42
TestCall
python
tensorflow__tensorflow
tensorflow/tools/api/tests/api_compatibility_test.py
{ "start": 7967, "end": 21638 }
class ____(test.TestCase): def __init__(self, *args, **kwargs): super(ApiCompatibilityTest, self).__init__(*args, **kwargs) golden_update_warning_filename = os.path.join( resource_loader.get_root_dir_with_all_resources(), _UPDATE_WARNING_FILE) self._update_golden_warning = file_io.read_file_to_string( golden_update_warning_filename) test_readme_filename = os.path.join( resource_loader.get_root_dir_with_all_resources(), _TEST_README_FILE) self._test_readme_message = file_io.read_file_to_string( test_readme_filename) def _AssertProtoDictEquals(self, expected_dict, actual_dict, verbose=False, update_goldens=False, additional_missing_object_message='', api_version=2): """Diff given dicts of protobufs and report differences a readable way. Args: expected_dict: a dict of TFAPIObject protos constructed from golden files. actual_dict: a dict of TFAPIObject protos constructed by reading from the TF package linked to the test. verbose: Whether to log the full diffs, or simply report which files were different. update_goldens: Whether to update goldens when there are diffs found. additional_missing_object_message: Message to print when a symbol is missing. api_version: TensorFlow API version to test. """ diffs = [] verbose_diffs = [] expected_keys = set(expected_dict.keys()) actual_keys = set(actual_dict.keys()) only_in_expected = expected_keys - actual_keys only_in_actual = actual_keys - expected_keys all_keys = expected_keys | actual_keys # This will be populated below. updated_keys = [] for key in all_keys: diff_message = '' verbose_diff_message = '' # First check if the key is not found in one or the other. if key in only_in_expected: diff_message = 'Object %s expected but not found (removed). %s' % ( key, additional_missing_object_message) verbose_diff_message = diff_message elif key in only_in_actual: diff_message = 'New object %s found (added).' % key verbose_diff_message = diff_message else: # Do not truncate diff self.maxDiff = None # pylint: disable=invalid-name # Now we can run an actual proto diff. try: self.assertProtoEquals(expected_dict[key], actual_dict[key]) except AssertionError as e: updated_keys.append(key) diff_message = 'Change detected in python object: %s.' % key verbose_diff_message = str(e) # All difference cases covered above. If any difference found, add to the # list. if diff_message: diffs.append(diff_message) verbose_diffs.append(verbose_diff_message) # If diffs are found, handle them based on flags. if diffs: diff_count = len(diffs) logging.error(self._test_readme_message) logging.error('%d differences found between API and golden.', diff_count) if update_goldens: # Write files if requested. logging.warning(self._update_golden_warning) # If the keys are only in expected, some objects are deleted. # Remove files. for key in only_in_expected: filepath = _KeyToFilePath(key, api_version) file_io.delete_file(filepath) # If the files are only in actual (current library), these are new # modules. Write them to files. Also record all updates in files. for key in only_in_actual | set(updated_keys): filepath = _KeyToFilePath(key, api_version) file_io.write_string_to_file( filepath, text_format.MessageToString(actual_dict[key])) else: # Include the actual differences to help debugging. for d, verbose_d in zip(diffs, verbose_diffs): logging.error(' %s', d) logging.error(' %s', verbose_d) # Fail if we cannot fix the test by updating goldens. self.fail('%d differences found between API and golden.' % diff_count) else: logging.info('No differences found between API and golden.') def testNoSubclassOfMessage(self): visitor = public_api.PublicAPIVisitor(_VerifyNoSubclassOfMessageVisitor) visitor.do_not_descend_map['tf'].append('contrib') # visitor.do_not_descend_map['tf'].append('keras') # Skip compat.v1 and compat.v2 since they are validated in separate tests. visitor.private_map['tf.compat'] = ['v1', 'v2'] traverse.traverse(tf, visitor) def testNoSubclassOfMessageV1(self): if not hasattr(tf.compat, 'v1'): return visitor = public_api.PublicAPIVisitor(_VerifyNoSubclassOfMessageVisitor) visitor.do_not_descend_map['tf'].append('contrib') if FLAGS.only_test_core_api: visitor.do_not_descend_map['tf'].extend(_NON_CORE_PACKAGES) visitor.private_map['tf.compat'] = ['v1', 'v2'] traverse.traverse(tf.compat.v1, visitor) def testNoSubclassOfMessageV2(self): if not hasattr(tf.compat, 'v2'): return visitor = public_api.PublicAPIVisitor(_VerifyNoSubclassOfMessageVisitor) visitor.do_not_descend_map['tf'].append('contrib') if FLAGS.only_test_core_api: visitor.do_not_descend_map['tf'].extend(_NON_CORE_PACKAGES) visitor.private_map['tf.compat'] = ['v1', 'v2'] traverse.traverse(tf.compat.v2, visitor) def _checkBackwardsCompatibility(self, root, golden_file_patterns, api_version, additional_private_map=None, omit_golden_symbols_map=None): # Extract all API stuff. visitor = python_object_to_proto_visitor.PythonObjectToProtoVisitor() public_api_visitor = public_api.PublicAPIVisitor(visitor) public_api_visitor.private_map['tf'].append('contrib') if api_version == 2: public_api_visitor.private_map['tf'].append('enable_v2_behavior') public_api_visitor.do_not_descend_map['tf.GPUOptions'] = ['Experimental'] # Do not descend into these numpy classes because their signatures may be # different between internal and OSS. public_api_visitor.do_not_descend_map['tf.experimental.numpy'] = [ 'bool_', 'complex_', 'complex128', 'complex64', 'float_', 'float16', 'float32', 'float64', 'inexact', 'int_', 'int16', 'int32', 'int64', 'int8', 'object_', 'string_', 'uint16', 'uint32', 'uint64', 'uint8', 'unicode_', 'iinfo'] public_api_visitor.do_not_descend_map['tf'].append('keras') if FLAGS.only_test_core_api: public_api_visitor.do_not_descend_map['tf'].extend(_NON_CORE_PACKAGES) if api_version == 2: public_api_visitor.do_not_descend_map['tf'].extend(_V2_APIS_FROM_KERAS) else: public_api_visitor.do_not_descend_map['tf'].extend(['layers']) public_api_visitor.do_not_descend_map['tf.nn'] = ['rnn_cell'] if additional_private_map: public_api_visitor.private_map.update(additional_private_map) traverse.traverse(root, public_api_visitor) proto_dict = visitor.GetProtos() # Read all golden files. golden_file_list = file_io.get_matching_files(golden_file_patterns) if FLAGS.only_test_core_api: golden_file_list = _FilterNonCoreGoldenFiles(golden_file_list) if api_version == 2: golden_file_list = _FilterV2KerasRelatedGoldenFiles(golden_file_list) else: golden_file_list = _FilterV1KerasRelatedGoldenFiles(golden_file_list) def _ReadFileToProto(filename): """Read a filename, create a protobuf from its contents.""" ret_val = api_objects_pb2.TFAPIObject() text_format.Merge(file_io.read_file_to_string(filename), ret_val) return ret_val golden_proto_dict = { _FileNameToKey(filename): _ReadFileToProto(filename) for filename in golden_file_list } golden_proto_dict = _FilterGoldenProtoDict(golden_proto_dict, omit_golden_symbols_map) proto_dict = _FilterGoldenProtoDict(proto_dict, omit_golden_symbols_map) # Diff them. Do not fail if called with update. # If the test is run to update goldens, only report diffs but do not fail. self._AssertProtoDictEquals( golden_proto_dict, proto_dict, verbose=FLAGS.verbose_diffs, update_goldens=FLAGS.update_goldens, api_version=api_version) def testAPIBackwardsCompatibility(self): api_version = 1 if hasattr(tf, '_major_api_version') and tf._major_api_version == 2: api_version = 2 golden_file_patterns = [ os.path.join(resource_loader.get_root_dir_with_all_resources(), _KeyToFilePath('*', api_version)), _GetTFNumpyGoldenPattern(api_version)] omit_golden_symbols_map = {} if (api_version == 2 and FLAGS.only_test_core_api and not _TENSORBOARD_AVAILABLE): # In TF 2.0 these summary symbols are imported from TensorBoard. omit_golden_symbols_map['tensorflow.summary'] = [ 'audio', 'histogram', 'image', 'scalar', 'text' ] omit_golden_symbols_map.update( self._ignored_is_instance_types(['tensorflow.__internal__.FuncGraph']) ) self._checkBackwardsCompatibility( tf, golden_file_patterns, api_version, # Skip compat.v1 and compat.v2 since they are validated # in separate tests. additional_private_map={'tf.compat': ['v1', 'v2']}, omit_golden_symbols_map=omit_golden_symbols_map) # Check that V2 API does not have contrib self.assertTrue(api_version == 1 or not hasattr(tf, 'contrib')) def testAPIBackwardsCompatibilityV1(self): api_version = 1 golden_file_patterns = os.path.join( resource_loader.get_root_dir_with_all_resources(), _KeyToFilePath('*', api_version)) omit_golden_symbols_map = {'tensorflow': ['pywrap_tensorflow']} omit_golden_symbols_map.update( self._ignored_is_instance_types(['tensorflow.python_io.TFRecordWriter']) ) # In OSS we have a different version of ABSL. omit_golden_symbols_map['tensorflow.logging'] = ['log_if'] self._checkBackwardsCompatibility( tf.compat.v1, golden_file_patterns, api_version, additional_private_map={ 'tf': ['pywrap_tensorflow'], 'tf.compat': ['v1', 'v2'], }, omit_golden_symbols_map=omit_golden_symbols_map) def testAPIBackwardsCompatibilityV2(self): api_version = 2 golden_file_patterns = [ os.path.join(resource_loader.get_root_dir_with_all_resources(), _KeyToFilePath('*', api_version)), _GetTFNumpyGoldenPattern(api_version)] omit_golden_symbols_map = {} if FLAGS.only_test_core_api and not _TENSORBOARD_AVAILABLE: # In TF 2.0 these summary symbols are imported from TensorBoard. omit_golden_symbols_map['tensorflow.summary'] = [ 'audio', 'histogram', 'image', 'scalar', 'text' ] omit_golden_symbols_map.update( self._ignored_is_instance_types(['tensorflow.__internal__.FuncGraph']) ) self._checkBackwardsCompatibility( tf.compat.v2, golden_file_patterns, api_version, additional_private_map={'tf.compat': ['v1', 'v2']}, omit_golden_symbols_map=omit_golden_symbols_map) def _ignored_is_instance_types(self, extra_types=None): # In case a new type is defined within a pywrap_<module_name>.so library, # it will end up having proper type and location in distributed OSS wheel # package eventually, but that conversion happens after this test is ran. # # Making this test depend on wheel itself also breaks because wheels use # _upb as underlying protobuf implementation while internal TF uses cpp # implementation (resulting in different is_instance values for protobuf # metadata types in golden pbtxt depending on which protobuf implementation # is being used during test execution). The cpp implementation is not even # included anymore in protobuf oss wheels. # # We end up in a situation when we cannot make this test pass internally and # externally on the same set of golden expected .pbtxt inputs. It is rare # and minor discrepancy, so just ignore the is_instance checks for the few # problematic types, they are guaraneed to have proper types in final wheel # anyway. ignored_is_instance_types = [ 'tensorflow.DType', 'tensorflow.dtypes.DType', 'tensorflow.__internal__.SymbolicTensor', 'tensorflow.Graph', 'tensorflow.Operation', 'tensorflow.io.TFRecordWriter' ] + extra_types if extra_types else [] return {k: 'is_instance' for k in ignored_is_instance_types} if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( '--update_goldens', type=bool, default=False, help=_UPDATE_GOLDENS_HELP) parser.add_argument( '--only_test_core_api', type=bool, default=True, # only_test_core_api default value help=_ONLY_TEST_CORE_API_HELP) parser.add_argument( '--verbose_diffs', type=bool, default=True, help=_VERBOSE_DIFFS_HELP) FLAGS, unparsed = parser.parse_known_args() _InitPathConstants() # Now update argv, so that unittest library does not get confused. sys.argv = [sys.argv[0]] + unparsed test.main()
ApiCompatibilityTest
python
MongoEngine__mongoengine
mongoengine/errors.py
{ "start": 952, "end": 1285 }
class ____(MongoEngineException): """Raised when trying to set a field not declared in a :class:`~mongoengine.Document` or an :class:`~mongoengine.EmbeddedDocument`. To avoid this behavior on data loading, you should set the :attr:`strict` to ``False`` in the :attr:`meta` dictionary. """
FieldDoesNotExist
python
doocs__leetcode
solution/1800-1899/1815.Maximum Number of Groups Getting Fresh Donuts/Solution2.py
{ "start": 0, "end": 650 }
class ____: def maxHappyGroups(self, batchSize: int, groups: List[int]) -> int: @cache def dfs(state, x): if state == mask: return 0 vis = [False] * batchSize res = 0 for i, v in enumerate(g): if state >> i & 1 == 0 and not vis[v]: vis[v] = True y = (x + v) % batchSize res = max(res, dfs(state | 1 << i, y)) return res + (x == 0) g = [v % batchSize for v in groups if v % batchSize] mask = (1 << len(g)) - 1 return len(groups) - len(g) + dfs(0, 0)
Solution
python
ray-project__ray
rllib/algorithms/dreamerv3/torch/dreamerv3_torch_rl_module.py
{ "start": 687, "end": 2982 }
class ____(TorchRLModule, DreamerV3RLModule): """The torch-specific RLModule class for DreamerV3. Serves mainly as a thin-wrapper around the `DreamerModel` (a torch.nn.Module) class. """ framework = "torch" @override(TorchRLModule) def _forward_inference(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: # Call the Dreamer-Model's forward_inference method and return a dict. with torch.no_grad(): actions, next_state = self.dreamer_model.forward_inference( observations=batch[Columns.OBS], previous_states=batch[Columns.STATE_IN], is_first=batch["is_first"], ) return self._forward_inference_or_exploration_helper(batch, actions, next_state) @override(TorchRLModule) def _forward_exploration(self, batch: Dict[str, Any], **kwargs) -> Dict[str, Any]: # Call the Dreamer-Model's forward_exploration method and return a dict. with torch.no_grad(): actions, next_state = self.dreamer_model.forward_exploration( observations=batch[Columns.OBS], previous_states=batch[Columns.STATE_IN], is_first=batch["is_first"], ) return self._forward_inference_or_exploration_helper(batch, actions, next_state) @override(RLModule) def _forward_train(self, batch: Dict[str, Any], **kwargs): # Call the Dreamer-Model's forward_train method and return its outputs as-is. return self.dreamer_model.forward_train( observations=batch[Columns.OBS], actions=batch[Columns.ACTIONS], is_first=batch["is_first"], ) def _forward_inference_or_exploration_helper(self, batch, actions, next_state): # Unfold time dimension. shape = batch[Columns.OBS].shape B, T = shape[0], shape[1] actions = actions.view((B, T) + actions.shape[1:]) output = { Columns.ACTIONS: actions, ACTIONS_ONE_HOT: actions, Columns.STATE_OUT: next_state, } # Undo one-hot actions? if isinstance(self.action_space, gym.spaces.Discrete): output[Columns.ACTIONS] = torch.argmax(actions, dim=-1) return output
DreamerV3TorchRLModule
python
numba__numba
numba/tests/test_compiler_flags.py
{ "start": 602, "end": 1335 }
class ____(TestCase): def test_fastmath_in_overload(self): def fastmath_status(): pass @overload(fastmath_status) def ov_fastmath_status(): flags = ConfigStack().top() val = "Has fastmath" if flags.fastmath else "No fastmath" def codegen(): return val return codegen @njit(fastmath=True) def set_fastmath(): return fastmath_status() @njit() def foo(): a = fastmath_status() b = set_fastmath() return (a, b) a, b = foo() self.assertEqual(a, "No fastmath") self.assertEqual(b, "Has fastmath")
TestCompilerFlagCachedOverload
python
graphql-python__graphene
setup.py
{ "start": 563, "end": 2667 }
class ____(TestCommand): user_options = [("pytest-args=", "a", "Arguments to pass to py.test")] def initialize_options(self): TestCommand.initialize_options(self) self.pytest_args = [] def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.pytest_args) sys.exit(errno) tests_require = [ "pytest>=8,<9", "pytest-benchmark>=4,<5", "pytest-cov>=5,<6", "pytest-mock>=3,<4", "pytest-asyncio>=0.16,<2", "coveralls>=3.3,<5", ] dev_requires = [ "ruff==0.5.0", "types-python-dateutil>=2.8.1,<3", "mypy>=1.10,<2", ] + tests_require setup( name="graphene", version=version, description="GraphQL Framework for Python", long_description=codecs.open( "README.md", "r", encoding="ascii", errors="replace" ).read(), long_description_content_type="text/markdown", url="https://github.com/graphql-python/graphene", author="Syrus Akbary", author_email="me@syrusakbary.com", license="MIT", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Topic :: Software Development :: Libraries", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", ], keywords="api graphql protocol rest relay graphene", packages=find_packages(exclude=["examples*"]), install_requires=[ "graphql-core>=3.1,<3.3", "graphql-relay>=3.1,<3.3", "python-dateutil>=2.7.0,<3", "typing-extensions>=4.7.1,<5", ], tests_require=tests_require, extras_require={"test": tests_require, "dev": dev_requires}, cmdclass={"test": PyTest}, )
PyTest
python
tornadoweb__tornado
tornado/test/testing_test.py
{ "start": 7497, "end": 10509 }
class ____(AsyncTestCase): def setUp(self): super().setUp() self.finished = False def tearDown(self): self.assertTrue(self.finished) super().tearDown() @gen_test def test_sync(self): self.finished = True @gen_test def test_async(self): yield gen.moment self.finished = True def test_timeout(self): # Set a short timeout and exceed it. @gen_test(timeout=0.1) def test(self): yield gen.sleep(1) # This can't use assertRaises because we need to inspect the # exc_info triple (and not just the exception object) try: test(self) self.fail("did not get expected exception") except ioloop.TimeoutError: # The stack trace should blame the add_timeout line, not just # unrelated IOLoop/testing internals. self.assertIn("gen.sleep(1)", traceback.format_exc()) self.finished = True def test_no_timeout(self): # A test that does not exceed its timeout should succeed. @gen_test(timeout=1) def test(self): yield gen.sleep(0.1) test(self) self.finished = True def test_timeout_environment_variable(self): @gen_test(timeout=0.5) def test_long_timeout(self): yield gen.sleep(0.25) # Uses provided timeout of 0.5 seconds, doesn't time out. with set_environ("ASYNC_TEST_TIMEOUT", "0.1"): test_long_timeout(self) self.finished = True def test_no_timeout_environment_variable(self): @gen_test(timeout=0.01) def test_short_timeout(self): yield gen.sleep(1) # Uses environment-variable timeout of 0.1, times out. with set_environ("ASYNC_TEST_TIMEOUT", "0.1"): with self.assertRaises(ioloop.TimeoutError): test_short_timeout(self) self.finished = True def test_with_method_args(self): @gen_test def test_with_args(self, *args): self.assertEqual(args, ("test",)) yield gen.moment test_with_args(self, "test") self.finished = True def test_with_method_kwargs(self): @gen_test def test_with_kwargs(self, **kwargs): self.assertDictEqual(kwargs, {"test": "test"}) yield gen.moment test_with_kwargs(self, test="test") self.finished = True def test_native_coroutine(self): @gen_test async def test(self): self.finished = True test(self) def test_native_coroutine_timeout(self): # Set a short timeout and exceed it. @gen_test(timeout=0.1) async def test(self): await gen.sleep(1) try: test(self) self.fail("did not get expected exception") except ioloop.TimeoutError: self.finished = True if __name__ == "__main__": unittest.main()
GenTest
python
sympy__sympy
sympy/core/relational.py
{ "start": 25598, "end": 27701 }
class ____(Relational): """An unequal relation between two objects. Explanation =========== Represents that two objects are not equal. If they can be shown to be definitively equal, this will reduce to False; if definitively unequal, this will reduce to True. Otherwise, the relation is maintained as an Unequality object. Examples ======== >>> from sympy import Ne >>> from sympy.abc import x, y >>> Ne(y, x+x**2) Ne(y, x**2 + x) See Also ======== Equality Notes ===== This class is not the same as the != operator. The != operator tests for exact structural equality between two expressions; this class compares expressions mathematically. This class is effectively the inverse of Equality. As such, it uses the same algorithms, including any available `_eval_Eq` methods. """ rel_op = '!=' __slots__ = () def __new__(cls, lhs, rhs, **options) -> Unequality | BooleanFalse | BooleanTrue: # type: ignore lhs = _sympify(lhs) rhs = _sympify(rhs) evaluate = options.pop('evaluate', global_parameters.evaluate) if evaluate: val = is_neq(lhs, rhs) if val is None: return cls(lhs, rhs, evaluate=False) else: return _sympify(val) return Relational.__new__(cls, lhs, rhs, **options) @classmethod def _eval_relation(cls, lhs, rhs): return _sympify(lhs != rhs) @property def binary_symbols(self): if S.true in self.args or S.false in self.args: if self.lhs.is_Symbol: return {self.lhs} elif self.rhs.is_Symbol: return {self.rhs} return set() def _eval_simplify(self, **kwargs): # simplify as an equality eq = Equality(*self.args)._eval_simplify(**kwargs) if isinstance(eq, Equality): # send back Ne with the new args return self.func(*eq.args) return eq.negated # result of Ne is the negated Eq Ne = Unequality
Unequality
python
PyCQA__pylint
tests/functional/u/unsubscriptable_value.py
{ "start": 1586, "end": 1712 }
class ____(LibSubscriptable): pass MaybeSubscriptable()[0] # subscriptable classes (through metaclasses)
MaybeSubscriptable
python
GoogleCloudPlatform__python-docs-samples
appengine/standard/memcache/guestbook/main.py
{ "start": 1354, "end": 4465 }
class ____(webapp2.RequestHandler): def get(self): self.response.out.write("<html><body>") guestbook_name = self.request.get("guestbook_name") greetings = self.get_greetings(guestbook_name) stats = memcache.get_stats() self.response.write("<b>Cache Hits:{}</b><br>".format(stats["hits"])) self.response.write("<b>Cache Misses:{}</b><br><br>".format(stats["misses"])) self.response.write(greetings) self.response.write( """ <form action="/sign?{}" method="post"> <div><textarea name="content" rows="3" cols="60"></textarea></div> <div><input type="submit" value="Sign Guestbook"></div> </form> <hr> <form>Guestbook name: <input value="{}" name="guestbook_name"> <input type="submit" value="switch"></form> </body> </html>""".format( urllib.urlencode({"guestbook_name": guestbook_name}), cgi.escape(guestbook_name), ) ) # [START gae_memcache_guestbook_check_memcache] def get_greetings(self, guestbook_name): """ get_greetings() Checks the cache to see if there are cached greetings. If not, call render_greetings and set the cache Args: guestbook_name: Guestbook entity group key (string). Returns: A string of HTML containing greetings. """ greetings = memcache.get("{}:greetings".format(guestbook_name)) if greetings is None: greetings = self.render_greetings(guestbook_name) try: added = memcache.add( "{}:greetings".format(guestbook_name), greetings, 10 ) if not added: logging.error("Memcache set failed.") except ValueError: logging.error("Memcache set failed - data larger than 1MB") return greetings # [END gae_memcache_guestbook_check_memcache] # [START gae_memcache_guestbook_query_datastore] def render_greetings(self, guestbook_name): """ render_greetings() Queries the database for greetings, iterate through the results and create the HTML. Args: guestbook_name: Guestbook entity group key (string). Returns: A string of HTML containing greetings """ greetings = ndb.gql( "SELECT * " "FROM Greeting " "WHERE ANCESTOR IS :1 " "ORDER BY date DESC LIMIT 10", guestbook_key(guestbook_name), ) output = cStringIO.StringIO() for greeting in greetings: if greeting.author: output.write("<b>{}</b> wrote:".format(greeting.author)) else: output.write("An anonymous person wrote:") output.write( "<blockquote>{}</blockquote>".format(cgi.escape(greeting.content)) ) return output.getvalue() # [END gae_memcache_guestbook_query_datastore]
MainPage
python
jazzband__prettytable
tests/test_prettytable.py
{ "start": 4361, "end": 6469 }
class ____: """Make sure that building a table row-by-row and column-by-column yield the same results""" @pytest.mark.parametrize( ["left_hand", "right_hand"], [ ( lf("row_prettytable"), lf("col_prettytable"), ), ( lf("row_prettytable"), lf("mix_prettytable"), ), ], ) def test_equivalence_ascii( self, left_hand: PrettyTable, right_hand: PrettyTable ) -> None: assert left_hand.get_string() == right_hand.get_string() @pytest.mark.parametrize( ["left_hand", "right_hand"], [ ( lf("row_prettytable"), lf("col_prettytable"), ), ( lf("row_prettytable"), lf("mix_prettytable"), ), ], ) def test_equivalence_html( self, left_hand: PrettyTable, right_hand: PrettyTable ) -> None: assert left_hand.get_html_string() == right_hand.get_html_string() @pytest.mark.parametrize( ["left_hand", "right_hand"], [ ( lf("row_prettytable"), lf("col_prettytable"), ), ( lf("row_prettytable"), lf("mix_prettytable"), ), ], ) def test_equivalence_latex( self, left_hand: PrettyTable, right_hand: PrettyTable ) -> None: assert left_hand.get_latex_string() == right_hand.get_latex_string() @pytest.mark.parametrize( ["left_hand", "right_hand"], [ ( lf("row_prettytable"), lf("col_prettytable"), ), ( lf("row_prettytable"), lf("mix_prettytable"), ), ], ) def test_equivalence_mediawiki( self, left_hand: PrettyTable, right_hand: PrettyTable ) -> None: assert left_hand.get_mediawiki_string() == right_hand.get_mediawiki_string()
TestBuildEquivalence
python
simplejson__simplejson
simplejson/tests/test_subclass.py
{ "start": 190, "end": 393 }
class ____(float): def __repr__(self): return 'invalid json' __str__ = __repr__ # class AlternateDecimal(Decimal): # def __repr__(self): # return 'invalid json'
AlternateFloat
python
redis__redis-py
redis/auth/token.py
{ "start": 579, "end": 866 }
class ____: def __init__(self, token: TokenInterface): self._token = token def get_token(self) -> TokenInterface: return self._token def get_ttl_ms(self) -> float: return self._token.get_expires_at_ms() - self._token.get_received_at_ms()
TokenResponse
python
pdm-project__pdm
tests/test_plugin.py
{ "start": 210, "end": 4420 }
class ____(BaseCommand): def add_arguments(self, parser) -> None: parser.add_argument("-n", "--name", help="The person's name") def handle(self, project, options) -> None: greeting = "Hello world" if options.name: greeting = f"Hello, {options.name}" print(greeting) def new_command(core): core.register_command(HelloCommand, "hello") def replace_command(core): core.register_command(HelloCommand, "info") def add_new_config(core): core.add_config("foo", ConfigItem("Test config", "bar")) def make_entry_point(plugin): ret = mock.Mock() ret.load.return_value = plugin return ret def test_plugin_new_command(pdm, mocker, project, core): mocker.patch.object( importlib_metadata, "entry_points", return_value=[make_entry_point(new_command)], ) core.init_parser() core.load_plugins() result = pdm(["--help"], obj=project) assert "hello" in result.output result = pdm(["hello"], obj=project) assert result.output.strip() == "Hello world" result = pdm(["hello", "-n", "Frost"], obj=project) assert result.output.strip() == "Hello, Frost" def test_plugin_replace_command(pdm, mocker, project, core): mocker.patch.object( importlib_metadata, "entry_points", return_value=[make_entry_point(replace_command)], ) core.init_parser() core.load_plugins() result = pdm(["info"], obj=project) assert result.output.strip() == "Hello world" result = pdm(["info", "-n", "Frost"], obj=project) assert result.output.strip() == "Hello, Frost" def test_load_multiple_plugins(pdm, mocker, core): mocker.patch.object( importlib_metadata, "entry_points", return_value=[make_entry_point(new_command), make_entry_point(add_new_config)], ) core.init_parser() core.load_plugins() result = pdm(["hello"]) assert result.output.strip() == "Hello world", result.outputs result = pdm(["config", "foo"]) assert result.output.strip() == "bar" def test_old_entry_point_compatibility(pdm, mocker, core): def get_entry_points(group): if group == "pdm": return [make_entry_point(new_command)] if group == "pdm.plugin": return [make_entry_point(add_new_config)] return [] mocker.patch.object(importlib_metadata, "entry_points", side_effect=get_entry_points) core.init_parser() core.load_plugins() result = pdm(["hello"]) assert result.output.strip() == "Hello world" result = pdm(["config", "foo"]) assert result.output.strip() == "bar" @pytest.mark.usefixtures("local_finder") def test_project_plugin_library(pdm, project, core, monkeypatch): monkeypatch.setattr(sys, "path", sys.path[:]) project.pyproject.settings["plugins"] = ["pdm-hello"] pdm(["install", "--plugins"], obj=project, strict=True) assert project.root.joinpath(".pdm-plugins").exists() assert "pdm-hello" not in project.environment.get_working_set() with cd(project.root): core.load_plugins() result = pdm(["hello", "Frost"], strict=True) assert result.stdout.strip() == "Hello, Frost!" @pytest.mark.parametrize( "req_str", [ "-e file:///${PROJECT_ROOT}/plugins/test-plugin-pdm", "-e test_plugin_pdm @ file:///${PROJECT_ROOT}/plugins/test-plugin-pdm", ], ) @pytest.mark.usefixtures("local_finder") def test_install_local_plugin_without_name(pdm, project, core, req_str): import shutil from . import FIXTURES test_plugin_path = FIXTURES / "projects" / "test-plugin-pdm" project.root.joinpath("plugins").mkdir(exist_ok=True) shutil.copytree(test_plugin_path, project.root / "plugins" / "test-plugin-pdm", dirs_exist_ok=True) project.pyproject.settings["plugins"] = [req_str] project.pyproject.write() with cd(project.root): result = pdm(["install", "--plugins", "-vv"], obj=project, strict=True) assert project.root.joinpath(".pdm-plugins").exists() core.load_plugins() result = pdm(["hello", "--name", "Frost"], strict=True) assert result.stdout.strip() == "Hello, Frost"
HelloCommand
python
yaml__pyyaml
lib/yaml/events.py
{ "start": 1834, "end": 1873 }
class ____(NodeEvent): pass
AliasEvent
python
scipy__scipy
scipy/stats/_distn_infrastructure.py
{ "start": 16452, "end": 19254 }
class ____: # generic type compatibility with scipy-stubs __class_getitem__ = classmethod(types.GenericAlias) def __init__(self, dist, *args, **kwds): self.args = args self.kwds = kwds # create a new instance self.dist = dist.__class__(**dist._updated_ctor_param()) shapes, _, _ = self.dist._parse_args(*args, **kwds) self.a, self.b = self.dist._get_support(*shapes) @property def random_state(self): return self.dist._random_state @random_state.setter def random_state(self, seed): self.dist._random_state = check_random_state(seed) def cdf(self, x): return self.dist.cdf(x, *self.args, **self.kwds) def logcdf(self, x): return self.dist.logcdf(x, *self.args, **self.kwds) def ppf(self, q): return self.dist.ppf(q, *self.args, **self.kwds) def isf(self, q): return self.dist.isf(q, *self.args, **self.kwds) def rvs(self, size=None, random_state=None): kwds = self.kwds.copy() kwds.update({'size': size, 'random_state': random_state}) return self.dist.rvs(*self.args, **kwds) def sf(self, x): return self.dist.sf(x, *self.args, **self.kwds) def logsf(self, x): return self.dist.logsf(x, *self.args, **self.kwds) def stats(self, moments='mv'): kwds = self.kwds.copy() kwds.update({'moments': moments}) return self.dist.stats(*self.args, **kwds) def median(self): return self.dist.median(*self.args, **self.kwds) def mean(self): return self.dist.mean(*self.args, **self.kwds) def var(self): return self.dist.var(*self.args, **self.kwds) def std(self): return self.dist.std(*self.args, **self.kwds) def moment(self, order=None): return self.dist.moment(order, *self.args, **self.kwds) def entropy(self): return self.dist.entropy(*self.args, **self.kwds) def interval(self, confidence=None): return self.dist.interval(confidence, *self.args, **self.kwds) def expect(self, func=None, lb=None, ub=None, conditional=False, **kwds): # expect method only accepts shape parameters as positional args # hence convert self.args, self.kwds, also loc/scale # See the .expect method docstrings for the meaning of # other parameters. a, loc, scale = self.dist._parse_args(*self.args, **self.kwds) if isinstance(self.dist, rv_discrete): return self.dist.expect(func, a, loc, lb, ub, conditional, **kwds) else: return self.dist.expect(func, a, loc, scale, lb, ub, conditional, **kwds) def support(self): return self.dist.support(*self.args, **self.kwds)
rv_frozen
python
getsentry__sentry
src/sentry/overwatch_webhooks/overwatch_consent/service.py
{ "start": 530, "end": 1479 }
class ____(RpcService): key = "overwatch_consent" local_mode = SiloMode.REGION @classmethod def get_local_implementation(cls) -> RpcService: from sentry.overwatch_webhooks.overwatch_consent.impl import ( DatabaseBackedOverwatchConsentService, ) return DatabaseBackedOverwatchConsentService() @regional_rpc_method(resolve=ByRegionName()) @abstractmethod def get_organization_consent_status( self, *, organization_ids: list[int], region_name: str ) -> dict[int, RpcOrganizationConsentStatus]: """ Get consent status for multiple organizations in a region. :param organization_ids: List of organization IDs to check :param region_name: The region name :return: Dictionary mapping organization ID to consent status """ pass overwatch_consent_service = OverwatchConsentService.create_delegation()
OverwatchConsentService
python
Lightning-AI__lightning
src/lightning/pytorch/demos/boring_classes.py
{ "start": 5846, "end": 6837 }
class ____(LightningDataModule): """ .. warning:: This is meant for testing/debugging and is experimental. """ def __init__(self) -> None: super().__init__() def setup(self, stage: str) -> None: if stage == "fit": self.random_train = RandomIterableDataset(32, 512) if stage in ("fit", "validate"): self.random_val = RandomIterableDataset(32, 128) if stage == "test": self.random_test = RandomIterableDataset(32, 256) if stage == "predict": self.random_predict = RandomIterableDataset(32, 64) def train_dataloader(self) -> DataLoader: return DataLoader(self.random_train) def val_dataloader(self) -> DataLoader: return DataLoader(self.random_val) def test_dataloader(self) -> DataLoader: return DataLoader(self.random_test) def predict_dataloader(self) -> DataLoader: return DataLoader(self.random_predict)
BoringDataModuleNoLen
python
PrefectHQ__prefect
src/integrations/prefect-aws/tests/cli/test_ecs_worker.py
{ "start": 1623, "end": 14806 }
class ____: def setup_method(self): self.runner = CliRunner() @patch("prefect_aws._cli.ecs_worker.load_template") def test_deploy_service_dry_run( self, mock_load_template, aws_credentials, mock_aws_resources ): """Test deploy-service command with dry-run.""" mock_load_template.return_value = {"AWSTemplateFormatVersion": "2010-09-09"} result = self.runner.invoke( app, [ "ecs-worker", "deploy-service", "--work-pool-name", "test-pool", "--stack-name", "test-stack", "--prefect-api-url", "https://api.prefect.cloud/api", "--existing-cluster-identifier", mock_aws_resources["cluster_name"], "--existing-vpc-id", mock_aws_resources["vpc_id"], "--existing-subnet-ids", ",".join(mock_aws_resources["subnet_ids"]), "--prefect-api-key", "test-key", "--dry-run", ], ) assert result.exit_code == 0 assert "DRY RUN" in result.stdout assert "test-stack" in result.stdout @patch("prefect_aws._cli.ecs_worker.load_template") def test_deploy_service_no_wait( self, mock_load_template, aws_credentials, mock_aws_resources ): """Test deploy-service command with --no-wait flag.""" mock_load_template.return_value = { "AWSTemplateFormatVersion": "2010-09-09", "Resources": {}, } result = self.runner.invoke( app, [ "ecs-worker", "deploy-service", "--work-pool-name", "test-pool", "--stack-name", "test-stack", "--prefect-api-url", "https://api.prefect.cloud/api", "--existing-cluster-identifier", mock_aws_resources["cluster_name"], "--existing-vpc-id", mock_aws_resources["vpc_id"], "--existing-subnet-ids", ",".join(mock_aws_resources["subnet_ids"]), "--prefect-api-key", "test-key", "--no-wait", ], ) assert result.exit_code == 0 assert "Check status with:" in result.stdout @patch("prefect_aws._cli.ecs_worker.validate_aws_credentials") def test_deploy_service_invalid_credentials(self, mock_validate_creds): """Test deploy-service command with invalid credentials.""" mock_validate_creds.return_value = False result = self.runner.invoke( app, [ "ecs-worker", "deploy-service", "--work-pool-name", "test-pool", "--stack-name", "test-stack", "--prefect-api-url", "https://api.prefect.cloud/api", "--prefect-api-key", "test-key", "--existing-cluster-identifier", "test-cluster", "--existing-vpc-id", "vpc-12345", "--existing-subnet-ids", "subnet-1,subnet-2", ], ) assert result.exit_code == 1 # Check both stdout and stderr as behavior varies across Typer versions output = result.stdout try: output += result.stderr except (ValueError, AttributeError): pass # stderr not separately captured assert "Invalid AWS credentials" in output @patch("prefect_aws._cli.ecs_worker.load_template") @patch("typer.confirm") def test_deploy_service_self_hosted_server( self, mock_confirm, mock_load_template, aws_credentials, mock_aws_resources ): """Test deploy-service command with self-hosted Prefect server.""" mock_load_template.return_value = {"AWSTemplateFormatVersion": "2010-09-09"} mock_confirm.return_value = False # No authentication needed result = self.runner.invoke( app, [ "ecs-worker", "deploy-service", "--work-pool-name", "test-pool", "--stack-name", "test-stack", "--prefect-api-url", "http://localhost:4200/api", "--existing-cluster-identifier", mock_aws_resources["cluster_name"], "--existing-vpc-id", mock_aws_resources["vpc_id"], "--existing-subnet-ids", ",".join(mock_aws_resources["subnet_ids"]), "--dry-run", ], ) assert result.exit_code == 0 assert "DRY RUN" in result.stdout assert "test-stack" in result.stdout @patch("prefect_aws._cli.ecs_worker.load_template") def test_deploy_service_with_auth_string_parameters( self, mock_load_template, aws_credentials, mock_aws_resources ): """Test deploy-service command with auth string parameters.""" mock_load_template.return_value = {"AWSTemplateFormatVersion": "2010-09-09"} result = self.runner.invoke( app, [ "ecs-worker", "deploy-service", "--work-pool-name", "test-pool", "--stack-name", "test-stack", "--prefect-api-url", "http://localhost:4200/api", "--existing-cluster-identifier", mock_aws_resources["cluster_name"], "--existing-vpc-id", mock_aws_resources["vpc_id"], "--existing-subnet-ids", ",".join(mock_aws_resources["subnet_ids"]), "--prefect-auth-string", "user:pass", "--dry-run", ], ) assert result.exit_code == 0 assert "DRY RUN" in result.stdout assert "test-stack" in result.stdout @patch("prefect_aws._cli.ecs_worker.load_template") def test_deploy_events_dry_run( self, mock_load_template, aws_credentials, mock_aws_resources ): """Test deploy-events command with dry-run.""" mock_load_template.return_value = {"AWSTemplateFormatVersion": "2010-09-09"} result = self.runner.invoke( app, [ "ecs-worker", "deploy-events", "--work-pool-name", "test-pool", "--stack-name", "test-events", "--existing-cluster-arn", mock_aws_resources["cluster_arn"], "--dry-run", ], ) assert result.exit_code == 0 assert "DRY RUN" in result.stdout assert "test-events" in result.stdout def test_list_stacks(self, aws_credentials): """Test list stacks command.""" with mock_aws(): # Create a test stack with CLI tags cf = boto3.client("cloudformation", region_name="us-east-1") cf.create_stack( StackName="test-stack", TemplateBody='{"AWSTemplateFormatVersion": "2010-09-09", "Resources": {}}', Tags=[ {"Key": "ManagedBy", "Value": "prefect-aws-cli"}, {"Key": "DeploymentType", "Value": "ecs-worker"}, {"Key": "StackType", "Value": "service"}, {"Key": "WorkPoolName", "Value": "test-pool"}, {"Key": "CreatedAt", "Value": "2023-01-01T00:00:00Z"}, ], ) result = self.runner.invoke(app, ["ecs-worker", "list"]) assert result.exit_code == 0 # Output should contain stack information assert "test-stack" in result.stdout def test_list_stacks_json_format(self, aws_credentials): """Test list stacks command with JSON output.""" with mock_aws(): # Create a test stack with CLI tags cf = boto3.client("cloudformation", region_name="us-east-1") cf.create_stack( StackName="test-stack", TemplateBody='{"AWSTemplateFormatVersion": "2010-09-09", "Resources": {}}', Tags=[ {"Key": "ManagedBy", "Value": "prefect-aws-cli"}, {"Key": "DeploymentType", "Value": "ecs-worker"}, {"Key": "StackType", "Value": "service"}, {"Key": "WorkPoolName", "Value": "test-pool"}, {"Key": "CreatedAt", "Value": "2023-01-01T00:00:00Z"}, ], ) result = self.runner.invoke(app, ["ecs-worker", "list", "--format", "json"]) assert result.exit_code == 0 # Should be valid JSON json.loads(result.stdout) def test_stack_status(self, aws_credentials): """Test stack status command.""" with mock_aws(): # Create a test stack with CLI tags cf = boto3.client("cloudformation", region_name="us-east-1") cf.create_stack( StackName="test-stack", TemplateBody='{"AWSTemplateFormatVersion": "2010-09-09", "Resources": {}}', Tags=[ {"Key": "ManagedBy", "Value": "prefect-aws-cli"}, {"Key": "DeploymentType", "Value": "ecs-worker"}, {"Key": "StackType", "Value": "service"}, {"Key": "WorkPoolName", "Value": "test-pool"}, ], ) result = self.runner.invoke(app, ["ecs-worker", "status", "test-stack"]) assert result.exit_code == 0 assert "test-stack" in result.stdout assert "CREATE_COMPLETE" in result.stdout def test_stack_status_not_cli_managed(self, aws_credentials): """Test stack status command for non-CLI managed stack.""" with mock_aws(): # Create a test stack without CLI tags cf = boto3.client("cloudformation", region_name="us-east-1") cf.create_stack( StackName="test-stack", TemplateBody='{"AWSTemplateFormatVersion": "2010-09-09", "Resources": {}}', Tags=[ {"Key": "Owner", "Value": "someone-else"}, ], ) result = self.runner.invoke(app, ["ecs-worker", "status", "test-stack"]) assert result.exit_code == 1 # Check both stdout and stderr as behavior varies across Typer versions output = result.stdout try: output += result.stderr except (ValueError, AttributeError): pass # stderr not separately captured assert "not deployed by prefect-aws CLI" in output def test_delete_stack_force(self, aws_credentials): """Test delete stack command with force flag.""" with mock_aws(): # Create a test stack with CLI tags cf = boto3.client("cloudformation", region_name="us-east-1") cf.create_stack( StackName="test-stack", TemplateBody='{"AWSTemplateFormatVersion": "2010-09-09", "Resources": {}}', Tags=[ {"Key": "ManagedBy", "Value": "prefect-aws-cli"}, {"Key": "DeploymentType", "Value": "ecs-worker"}, ], ) result = self.runner.invoke( app, ["ecs-worker", "delete", "test-stack", "--force"] ) assert result.exit_code == 0 # Verify the stack was deleted try: cf.describe_stacks(StackName="test-stack") # If we get here, the stack wasn't deleted assert False, "Stack should have been deleted" except cf.exceptions.ClientError as e: # Stack should not exist anymore assert "does not exist" in str(e) or "DELETE_COMPLETE" in str(e) def test_delete_stack_no_wait(self, aws_credentials): """Test delete stack command with --no-wait flag.""" with mock_aws(): # Create a test stack with CLI tags cf = boto3.client("cloudformation", region_name="us-east-1") cf.create_stack( StackName="test-stack", TemplateBody='{"AWSTemplateFormatVersion": "2010-09-09", "Resources": {}}', Tags=[ {"Key": "ManagedBy", "Value": "prefect-aws-cli"}, {"Key": "DeploymentType", "Value": "ecs-worker"}, ], ) result = self.runner.invoke( app, ["ecs-worker", "delete", "test-stack", "--force", "--no-wait"] ) assert result.exit_code == 0 assert "Check status with:" in result.stdout
TestECSWorkerCLI
python
scikit-learn__scikit-learn
sklearn/multioutput.py
{ "start": 11425, "end": 15021 }
class ____(RegressorMixin, _MultiOutputEstimator): """Multi target regression. This strategy consists of fitting one regressor per target. This is a simple strategy for extending regressors that do not natively support multi-target regression. .. versionadded:: 0.18 Parameters ---------- estimator : estimator object An estimator object implementing :term:`fit` and :term:`predict`. n_jobs : int or None, optional (default=None) The number of jobs to run in parallel. :meth:`fit`, :meth:`predict` and :meth:`partial_fit` (if supported by the passed estimator) will be parallelized for each target. When individual estimators are fast to train or predict, using ``n_jobs > 1`` can result in slower performance due to the parallelism overhead. ``None`` means `1` unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all available processes / threads. See :term:`Glossary <n_jobs>` for more details. .. versionchanged:: 0.20 `n_jobs` default changed from `1` to `None`. Attributes ---------- estimators_ : list of ``n_output`` estimators Estimators used for predictions. n_features_in_ : int Number of features seen during :term:`fit`. Only defined if the underlying `estimator` exposes such an attribute when fit. .. versionadded:: 0.24 feature_names_in_ : ndarray of shape (`n_features_in_`,) Names of features seen during :term:`fit`. Only defined if the underlying estimators expose such an attribute when fit. .. versionadded:: 1.0 See Also -------- RegressorChain : A multi-label model that arranges regressions into a chain. MultiOutputClassifier : Classifies each output independently rather than chaining. Examples -------- >>> import numpy as np >>> from sklearn.datasets import load_linnerud >>> from sklearn.multioutput import MultiOutputRegressor >>> from sklearn.linear_model import Ridge >>> X, y = load_linnerud(return_X_y=True) >>> regr = MultiOutputRegressor(Ridge(random_state=123)).fit(X, y) >>> regr.predict(X[[0]]) array([[176, 35.1, 57.1]]) """ def __init__(self, estimator, *, n_jobs=None): super().__init__(estimator, n_jobs=n_jobs) @_available_if_estimator_has("partial_fit") def partial_fit(self, X, y, sample_weight=None, **partial_fit_params): """Incrementally fit the model to data, for each output variable. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input data. y : {array-like, sparse matrix} of shape (n_samples, n_outputs) Multi-output targets. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If `None`, then samples are equally weighted. Only supported if the underlying regressor supports sample weights. **partial_fit_params : dict of str -> object Parameters passed to the ``estimator.partial_fit`` method of each sub-estimator. Only available if `enable_metadata_routing=True`. See the :ref:`User Guide <metadata_routing>`. .. versionadded:: 1.3 Returns ------- self : object Returns a fitted instance. """ super().partial_fit(X, y, sample_weight=sample_weight, **partial_fit_params)
MultiOutputRegressor
python
networkx__networkx
networkx/algorithms/tests/test_cluster.py
{ "start": 10838, "end": 12748 }
class ____: @classmethod def setup_class(cls): pytest.importorskip("numpy") def test_clustering(self): G = nx.Graph() assert list(nx.clustering(G).values()) == [] assert nx.clustering(G) == {} def test_path(self): G = nx.path_graph(10) assert list(nx.clustering(G).values()) == [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ] assert nx.clustering(G) == { 0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, } def test_cubical(self): G = nx.cubical_graph() assert list(nx.clustering(G).values()) == [0, 0, 0, 0, 0, 0, 0, 0] assert nx.clustering(G, 1) == 0 assert list(nx.clustering(G, [1, 2]).values()) == [0, 0] assert nx.clustering(G, 1) == 0 assert nx.clustering(G, [1, 2]) == {1: 0, 2: 0} def test_k5(self): G = nx.complete_graph(5) assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1] assert nx.average_clustering(G) == 1 G.remove_edge(1, 2) assert list(nx.clustering(G).values()) == [ 5 / 6, 1, 1, 5 / 6, 5 / 6, ] assert nx.clustering(G, [1, 4]) == {1: 1, 4: 0.83333333333333337} def test_k5_signed(self): G = nx.complete_graph(5) assert list(nx.clustering(G).values()) == [1, 1, 1, 1, 1] assert nx.average_clustering(G) == 1 G.remove_edge(1, 2) G.add_edge(0, 1, weight=-1) assert list(nx.clustering(G, weight="weight").values()) == [ 1 / 6, -1 / 3, 1, 3 / 6, 3 / 6, ]
TestClustering
python
getsentry__sentry
tests/sentry/releases/endpoints/test_project_release_file_details.py
{ "start": 795, "end": 7064 }
class ____(APITestCase): def test_simple(self) -> None: self.login_as(user=self.user) project = self.create_project(name="foo") release = Release.objects.create(organization_id=project.organization_id, version="1") release.add_project(project) releasefile = ReleaseFile.objects.create( organization_id=project.organization_id, release_id=release.id, file=File.objects.create(name="application.js", type="release.file"), name="http://example.com/application.js", ) url = reverse( "sentry-api-0-project-release-file-details", kwargs={ "organization_id_or_slug": project.organization.slug, "project_id_or_slug": project.slug, "version": release.version, "file_id": releasefile.id, }, ) response = self.client.get(url) assert response.status_code == 200, response.content assert response.data["id"] == str(releasefile.id) def test_file_download(self) -> None: self.login_as(user=self.user) project = self.create_project(name="foo") release = Release.objects.create(organization_id=project.organization_id, version="1") release.add_project(project) from io import BytesIO f = File.objects.create(name="applications.js", type="release.file") f.putfile(BytesIO(b"File contents here")) releasefile = ReleaseFile.objects.create( organization_id=project.organization_id, project_id=project.id, release_id=release.id, file=f, name=" http://example.com/appli\n\rcatios n.js\n\n\r ", ) url = reverse( "sentry-api-0-project-release-file-details", kwargs={ "organization_id_or_slug": project.organization.slug, "project_id_or_slug": project.slug, "version": release.version, "file_id": releasefile.id, }, ) # Download as a user with sufficient role self.organization.update_option("sentry:debug_files_role", "admin") user = self.create_user("baz@localhost") self.create_member(user=user, organization=project.organization, role="owner") self.login_as(user=user) response = self.client.get(url + "?download=1") assert response.status_code == 200, response.content assert response.get("Content-Disposition") == 'attachment; filename="appli catios n.js"' assert response.get("Content-Length") == str(f.size) assert response.get("Content-Type") == "application/octet-stream" assert b"File contents here" == close_streaming_response(response) # Download as a superuser self.login_as(user=self.user) response = self.client.get(url + "?download=1") assert response.get("Content-Type") == "application/octet-stream" assert b"File contents here" == close_streaming_response(response) # # Download as a user without sufficient role self.organization.update_option("sentry:debug_files_role", "owner") user_no_role = self.create_user("bar@localhost") self.create_member(user=user_no_role, organization=project.organization, role="member") self.login_as(user=user_no_role) response = self.client.get(url + "?download=1") assert response.status_code == 403, response.content # Download as a user with no permissions user_no_permission = self.create_user("baz@localhost", username="baz") self.login_as(user=user_no_permission) response = self.client.get(url + "?download=1") assert response.status_code == 403, response.content def _get(self, file_id, postfix=""): url = reverse( "sentry-api-0-project-release-file-details", kwargs={ "organization_id_or_slug": self.project.organization.slug, "project_id_or_slug": self.project.slug, "version": self.release.version, "file_id": file_id, }, ) return self.client.get(url + postfix) def test_invalid_id(self) -> None: # Invalid base64 self.login_as(user=self.user) response = self._get("foo666") assert response.status_code == 404, response.content # Valid base 64, but missing dist separator: response = self._get(urlsafe_b64encode(b"foo666").decode()) assert response.status_code == 404, response.content def test_archived(self) -> None: self.login_as(user=self.user) self.create_release_archive() id = urlsafe_b64encode(b"_~/index.js") response = self._get(id.decode()) assert response.status_code == 200 assert response.data["id"] == id # Get a file with a nonexisting dist: id = urlsafe_b64encode(b"mydist_~/index.js") response = self._get(id.decode()) assert response.status_code == 404 # Get a file that does not exist in index: id = urlsafe_b64encode(b"_~/foobar.js") response = self._get(id.decode()) assert response.status_code == 404 def test_download_archived(self) -> None: self.login_as(user=self.user) self.create_release_archive() id = urlsafe_b64encode(b"_~/index.js").decode() response = self._get(id) checksum = response.data["sha1"] response = self._get(id, "?download=1") assert response.status_code == 200 body = close_streaming_response(response) assert sha1(body).hexdigest() == checksum def test_archived_with_dist(self) -> None: self.login_as(user=self.user) dist = Distribution.objects.create( organization_id=self.organization.id, release_id=self.release.id, name="foo" ) self.create_release_archive(dist=dist) id = urlsafe_b64encode(b"foo_~/index.js") response = self._get(id.decode()) assert response.status_code == 200 assert response.data["id"] == id, urlsafe_b64decode(response.data["id"])
ReleaseFileDetailsTest
python
getsentry__sentry
src/sentry/api/serializers/types.py
{ "start": 348, "end": 886 }
class ____(TypedDict, total=False): ref: str | None url: str | None dateReleased: datetime | None dateCreated: datetime | None dateStarted: datetime | None owner: dict[str, Any] | None lastCommit: dict[str, Any] | None lastDeploy: LastDeploy | None firstEvent: datetime | None lastEvent: datetime | None currentProjectMeta: dict[str, Any] | None userAgent: str | None adoptionStages: dict[str, Any] | None # Only included if with_adoption_stages is True
ReleaseSerializerResponseOptional
python
sqlalchemy__sqlalchemy
test/base/test_events.py
{ "start": 26705, "end": 33661 }
class ____(TearDownLocalEventsFixture, fixtures.TestBase): def setup_test(self): class TargetEvents(event.Events): def event_one(self, target, arg): pass class BaseTarget: dispatch = event.dispatcher(TargetEvents) class TargetFactory(BaseTarget): def create(self): return TargetElement(self) class TargetElement(BaseTarget): def __init__(self, parent): self.dispatch = self.dispatch._join(parent.dispatch) def create(self): return TargetElement(self) def run_event(self, arg): list(self.dispatch.event_one) self.dispatch.event_one(self, arg) self.BaseTarget = BaseTarget self.TargetFactory = TargetFactory self.TargetElement = TargetElement def test_neither(self): element = self.TargetFactory().create() element.run_event(1) element.run_event(2) element.run_event(3) def test_kw_ok(self): l1 = Mock() def listen(**kw): l1(kw) event.listen(self.TargetFactory, "event_one", listen, named=True) element = self.TargetFactory().create() element.run_event(1) element.run_event(2) eq_( l1.mock_calls, [ call({"target": element, "arg": 1}), call({"target": element, "arg": 2}), ], ) def test_parent_class_only(self): l1 = Mock() event.listen(self.TargetFactory, "event_one", l1) element = self.TargetFactory().create() element.run_event(1) element.run_event(2) element.run_event(3) eq_( l1.mock_calls, [call(element, 1), call(element, 2), call(element, 3)], ) def test_parent_class_child_class(self): l1 = Mock() l2 = Mock() event.listen(self.TargetFactory, "event_one", l1) event.listen(self.TargetElement, "event_one", l2) element = self.TargetFactory().create() element.run_event(1) element.run_event(2) element.run_event(3) eq_( l1.mock_calls, [call(element, 1), call(element, 2), call(element, 3)], ) eq_( l2.mock_calls, [call(element, 1), call(element, 2), call(element, 3)], ) def test_join_twice(self): """test #12289""" l1 = Mock() l2 = Mock() first_target_element = self.TargetFactory().create() second_target_element = first_target_element.create() event.listen(second_target_element, "event_one", l2) event.listen(first_target_element, "event_one", l1) second_target_element.run_event(1) eq_( l1.mock_calls, [call(second_target_element, 1)], ) eq_( l2.mock_calls, [call(second_target_element, 1)], ) first_target_element.run_event(2) eq_( l1.mock_calls, [call(second_target_element, 1), call(first_target_element, 2)], ) eq_( l2.mock_calls, [call(second_target_element, 1)], ) def test_parent_class_child_instance_apply_after(self): l1 = Mock() l2 = Mock() event.listen(self.TargetFactory, "event_one", l1) element = self.TargetFactory().create() element.run_event(1) event.listen(element, "event_one", l2) element.run_event(2) element.run_event(3) eq_( l1.mock_calls, [call(element, 1), call(element, 2), call(element, 3)], ) eq_(l2.mock_calls, [call(element, 2), call(element, 3)]) def test_parent_class_child_instance_apply_before(self): l1 = Mock() l2 = Mock() event.listen(self.TargetFactory, "event_one", l1) element = self.TargetFactory().create() event.listen(element, "event_one", l2) element.run_event(1) element.run_event(2) element.run_event(3) eq_( l1.mock_calls, [call(element, 1), call(element, 2), call(element, 3)], ) eq_( l2.mock_calls, [call(element, 1), call(element, 2), call(element, 3)], ) def test_parent_instance_child_class_apply_before(self): l1 = Mock() l2 = Mock() event.listen(self.TargetElement, "event_one", l2) factory = self.TargetFactory() event.listen(factory, "event_one", l1) element = factory.create() element.run_event(1) element.run_event(2) element.run_event(3) eq_( l1.mock_calls, [call(element, 1), call(element, 2), call(element, 3)], ) eq_( l2.mock_calls, [call(element, 1), call(element, 2), call(element, 3)], ) def test_parent_instance_child_class_apply_after(self): l1 = Mock() l2 = Mock() event.listen(self.TargetElement, "event_one", l2) factory = self.TargetFactory() element = factory.create() element.run_event(1) event.listen(factory, "event_one", l1) element.run_event(2) element.run_event(3) # if _JoinedListener fixes .listeners # at construction time, then we don't get # the new listeners. # eq_(l1.mock_calls, []) # alternatively, if _JoinedListener shares the list # using a @property, then we get them, at the arguable # expense of the extra method call to access the .listeners # collection eq_(l1.mock_calls, [call(element, 2), call(element, 3)]) eq_( l2.mock_calls, [call(element, 1), call(element, 2), call(element, 3)], ) def test_parent_instance_child_instance_apply_before(self): l1 = Mock() l2 = Mock() factory = self.TargetFactory() event.listen(factory, "event_one", l1) element = factory.create() event.listen(element, "event_one", l2) element.run_event(1) element.run_event(2) element.run_event(3) eq_( l1.mock_calls, [call(element, 1), call(element, 2), call(element, 3)], ) eq_( l2.mock_calls, [call(element, 1), call(element, 2), call(element, 3)], ) def test_parent_events_child_no_events(self): l1 = Mock() factory = self.TargetFactory() event.listen(self.TargetElement, "event_one", l1) element = factory.create() element.run_event(1) element.run_event(2) element.run_event(3) eq_( l1.mock_calls, [call(element, 1), call(element, 2), call(element, 3)], )
JoinTest
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 14436, "end": 16382 }
class ____(Operation): def __init__(self, axis=None, keepdims=False, *, name=None): super().__init__(name=name) if isinstance(axis, int): axis = [axis] self.axis = axis self.keepdims = keepdims def call(self, x): return backend.numpy.amin(x, axis=self.axis, keepdims=self.keepdims) def compute_output_spec(self, x): return KerasTensor( reduce_shape(x.shape, axis=self.axis, keepdims=self.keepdims), dtype=x.dtype, ) @keras_export(["keras.ops.amin", "keras.ops.numpy.amin"]) def amin(x, axis=None, keepdims=False): """Returns the minimum of an array or minimum value along an axis. Args: x: Input tensor. axis: Axis along which to compute the minimum. By default (`axis=None`), find the minimum value in all the dimensions of the input array. keepdims: If `True`, axes which are reduced are left in the result as dimensions that are broadcast to the size of the original input tensor. Defaults to `False`. Returns: An array with the minimum value. If `axis=None`, the result is a scalar value representing the minimum element in the entire array. If `axis` is given, the result is an array with the minimum values along the specified axis. Examples: >>> x = keras.ops.convert_to_tensor([1, 3, 5, 2, 3, 6]) >>> keras.ops.amin(x) array(1, dtype=int32) >>> x = keras.ops.convert_to_tensor([[1, 6, 8], [7, 5, 3]]) >>> keras.ops.amin(x, axis=0) array([1,5,3], dtype=int32) >>> x = keras.ops.convert_to_tensor([[1, 6, 8], [7, 5, 3]]) >>> keras.ops.amin(x, axis=1, keepdims=True) array([[1],[3]], dtype=int32) """ if any_symbolic_tensors((x,)): return Amin(axis=axis, keepdims=keepdims).symbolic_call(x) return backend.numpy.amin(x, axis=axis, keepdims=keepdims)
Amin
python
fluentpython__example-code-2e
24-class-metaprog/tinyenums/microenum_demo.py
{ "start": 165, "end": 224 }
class ____(MicroEnum): cocoa coconut vanilla
Flavor
python
kamyu104__LeetCode-Solutions
Python/search-suggestions-system.py
{ "start": 1937, "end": 2750 }
class ____(object): def suggestedProducts(self, products, searchWord): """ :type products: List[str] :type searchWord: str :rtype: List[List[str]] """ products.sort() trie = TrieNode2() for i in xrange(len(products)): trie.insert(products, i) result = [[] for _ in xrange(len(searchWord))] for i, c in enumerate(searchWord): if c not in trie.leaves: break trie = trie.leaves[c] result[i] = map(lambda x: products[x], trie.infos) return result # Time: ctor: O(n * l * log(n * l)), n is the number of products # , l is the average length of product name # suggest: O(l^2 * n) # Space: O(n * l) import bisect
Solution2
python
lazyprogrammer__machine_learning_examples
airline/rnn.py
{ "start": 689, "end": 5069 }
class ____(object): def __init__(self, hidden_layer_sizes): self.hidden_layer_sizes = hidden_layer_sizes def fit(self, X, Y, activation=T.tanh, learning_rate=1e-1, mu=0.5, reg=0, epochs=2000, show_fig=False): N, t, D = X.shape self.hidden_layers = [] Mi = D for Mo in self.hidden_layer_sizes: ru = GRU(Mi, Mo, activation) self.hidden_layers.append(ru) Mi = Mo Wo = np.random.randn(Mi) / np.sqrt(Mi) bo = 0.0 self.Wo = theano.shared(Wo) self.bo = theano.shared(bo) self.params = [self.Wo, self.bo] for ru in self.hidden_layers: self.params += ru.params lr = T.scalar('lr') thX = T.matrix('X') thY = T.scalar('Y') Yhat = self.forward(thX)[-1] # let's return py_x too so we can draw a sample instead self.predict_op = theano.function( inputs=[thX], outputs=Yhat, allow_input_downcast=True, ) cost = T.mean((thY - Yhat)*(thY - Yhat)) grads = T.grad(cost, self.params) dparams = [theano.shared(p.get_value()*0) for p in self.params] updates = [ (p, p + mu*dp - lr*g) for p, dp, g in zip(self.params, dparams, grads) ] + [ (dp, mu*dp - lr*g) for dp, g in zip(dparams, grads) ] self.train_op = theano.function( inputs=[lr, thX, thY], outputs=cost, updates=updates ) costs = [] for i in xrange(epochs): t0 = datetime.now() X, Y = shuffle(X, Y) n_correct = 0 n_total = 0 cost = 0 for j in xrange(N): c = self.train_op(learning_rate, X[j], Y[j]) cost += c if i % 10 == 0: print "i:", i, "cost:", cost, "time for epoch:", (datetime.now() - t0) if (i+1) % 500 == 0: learning_rate /= 10 costs.append(cost) if show_fig: plt.plot(costs) plt.show() def forward(self, X): Z = X for h in self.hidden_layers: Z = h.output(Z) return Z.dot(self.Wo) + self.bo def score(self, X, Y): Yhat = self.predict(X) return myr2(Y, Yhat) def predict(self, X): N = len(X) Yhat = np.empty(N) for i in xrange(N): Yhat[i] = self.predict_op(X[i]) return Yhat # we need to skip the 3 footer rows # skipfooter does not work with the default engine, 'c' # so we need to explicitly set it to 'python' df = pd.read_csv('international-airline-passengers.csv', engine='python', skipfooter=3) # rename the columns because they are ridiculous df.columns = ['month', 'num_passengers'] # plot the data so we know what it looks like # plt.plot(df.num_passengers) # plt.show() # let's try with only the time series itself series = df.num_passengers.as_matrix() # series = (series - series.mean()) / series.std() # normalize the values so they have mean 0 and variance 1 series = series.astype(np.float32) series = series - series.min() series = series / series.max() # let's see if we can use D past values to predict the next value N = len(series) for D in (2,3,4,5): n = N - D X = np.zeros((n, D)) for d in xrange(D): X[:,d] = series[d:d+n] Y = series[D:D+n] print "series length:", n Xtrain = X[:n/2] Ytrain = Y[:n/2] Xtest = X[n/2:] Ytest = Y[n/2:] Ntrain = len(Xtrain) Xtrain = Xtrain.reshape(Ntrain, D, 1) Ntest = len(Xtest) Xtest = Xtest.reshape(Ntest, D, 1) model = RNN([50]) model.fit(Xtrain, Ytrain, activation=T.tanh) print "train score:", model.score(Xtrain, Ytrain) print "test score:", model.score(Xtest, Ytest) # plot the prediction with true values plt.plot(series) train_series = np.empty(n) train_series[:n/2] = model.predict(Xtrain) train_series[n/2:] = np.nan # prepend d nan's since the train series is only of size N - D plt.plot(np.concatenate([np.full(d, np.nan), train_series])) test_series = np.empty(n) test_series[:n/2] = np.nan test_series[n/2:] = model.predict(Xtest) plt.plot(np.concatenate([np.full(d, np.nan), test_series])) plt.show()
RNN
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/events.py
{ "start": 9095, "end": 9548 }
class ____(Enum): """Enumerate the reasons an asset may have failed to materialize. Can be used to provide more granular information about the failure to the user. """ FAILED_TO_MATERIALIZE = "FAILED_TO_MATERIALIZE" # The asset failed to materialize UPSTREAM_FAILED_TO_MATERIALIZE = "UPSTREAM_FAILED_TO_MATERIALIZE" RUN_TERMINATED = "RUN_TERMINATED" UNKNOWN = "UNKNOWN" @whitelist_for_serdes
AssetMaterializationFailureReason
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/table.py
{ "start": 574, "end": 833 }
class ____(graphene.ObjectType): nullable = graphene.NonNull(graphene.Boolean) unique = graphene.NonNull(graphene.Boolean) other = non_null_list(graphene.String) class Meta: name = "TableColumnConstraints"
GrapheneTableColumnConstraints
python
scipy__scipy
scipy/signal/tests/test_filter_design.py
{ "start": 140063, "end": 156261 }
class ____: def test_degenerate(self, xp): # 0-order filter is just a passthrough # Even-order filters have DC gain of -rp dB b, a = cheby1(0, 10*math.log10(2), xp.asarray(1), analog=True) assert_array_almost_equal( b, xp.asarray([1 / math.sqrt(2)], dtype=xp.float64) ) xp_assert_equal(a, xp.asarray([1.0], dtype=xp.float64)) # 1-order filter is same for all types b, a = cheby1(1, 10*math.log10(2), xp.asarray(1), analog=True) assert_array_almost_equal(b, xp.asarray([1.], dtype=xp.float64)) assert_array_almost_equal(a, xp.asarray([1., 1], dtype=xp.float64)) z, p, k = cheby1(1, 0.1, xp.asarray(0.3), output='zpk') xp_assert_equal(z, xp.asarray([-1.0], dtype=xp.float64)) xp_assert_close( p, xp.asarray([-5.390126972799615e-01 + 0j], dtype=xp.complex128), rtol=1e-14 if not DEFAULT_F32 else 1e-7 ) assert math.isclose( k, 7.695063486399808e-01, rel_tol=1e-14 if not DEFAULT_F32 else 1e-7 ) def test_basic(self, xp): for N in range(25): wn = xp.asarray(0.01) z, p, k = cheby1(N, 1, wn, 'low', analog=True, output='zpk') assert_array_almost_equal(z, xp.asarray([], dtype=xp.float64)) assert p.shape[0] == N assert xp.all(xp.real(p) <= 0) # No poles in right half of S-plane for N in range(25): wn = xp.asarray(0.01) z, p, k = cheby1(N, 1, wn, 'high', analog=False, output='zpk') xp_assert_equal(z, xp.ones(N, dtype=xp.float64)) # All zeros exactly at DC assert xp.all(xp.abs(p) <= 1) # No poles outside unit circle # Same test as TestNormalize b, a = cheby1(8, 0.5, xp.asarray(0.048)) xp_assert_close( b, xp.asarray([2.150733144728282e-11, 1.720586515782626e-10, 6.022052805239190e-10, 1.204410561047838e-09, 1.505513201309798e-09, 1.204410561047838e-09, 6.022052805239190e-10, 1.720586515782626e-10, 2.150733144728282e-11], dtype=xp.float64), rtol=0, atol=1.5e-14 ) xp_assert_close( a, xp.asarray([1.000000000000000e+00, -7.782402035027959e+00, 2.654354569747454e+01, -5.182182531666387e+01, 6.334127355102684e+01, -4.963358186631157e+01, 2.434862182949389e+01, -6.836925348604676e+00, 8.412934944449140e-01], dtype=xp.float64), rtol=0, atol=5e-14 if not DEFAULT_F32 else 1e-7 ) b, a = cheby1(4, 1, xp.asarray([0.4, 0.7]), btype='band') assert_array_almost_equal( b, xp.asarray([0.0084, 0, -0.0335, 0, 0.0502, 0, -0.0335, 0, 0.0084], dtype=xp.float64), decimal=4 ) assert_array_almost_equal( a, xp.asarray([1.0, 1.1191, 2.862, 2.2986, 3.4137, 1.8653, 1.8982, 0.5676, 0.4103], dtype=xp.float64), decimal=4 ) b2, a2 = cheby1(5, 3, xp.asarray(1), analog=True) assert_array_almost_equal( b2, xp.asarray([0.0626], dtype=xp.float64), decimal=4 ) assert_array_almost_equal( a2, xp.asarray([1, 0.5745, 1.4150, 0.5489, 0.4080, 0.0626], dtype=xp.float64), decimal=4) b, a = cheby1(8, 0.5, xp.asarray(0.1)) assert_array_almost_equal( b, 1.0e-006 * xp.asarray( [0.00703924326028, 0.05631394608227, 0.19709881128793, 0.39419762257586, 0.49274702821983, 0.39419762257586, 0.19709881128793, 0.05631394608227, 0.00703924326028 ], dtype=xp.float64 ), decimal=13 ) assert_array_almost_equal( a, xp.asarray( [1.00000000000000, -7.44912258934158, 24.46749067762108, -46.27560200466141, 55.11160187999928, -42.31640010161038, 20.45543300484147, -5.69110270561444, 0.69770374759022 ], dtype=xp.float64 ), decimal=13 if not DEFAULT_F32 else 6 ) b, a = cheby1(8, 0.5, xp.asarray(0.25)) assert_array_almost_equal( b, 1.0e-003 * xp.asarray( [0.00895261138923, 0.07162089111382, 0.25067311889837, 0.50134623779673, 0.62668279724591, 0.50134623779673, 0.25067311889837, 0.07162089111382, 0.00895261138923 ], dtype=xp.float64 ), decimal=13) assert_array_almost_equal( a, xp.asarray( [1.00000000000000, -5.97529229188545, 16.58122329202101, -27.71423273542923, 30.39509758355313, -22.34729670426879, 10.74509800434910, -3.08924633697497, 0.40707685889802 ], dtype=xp.float64 ), decimal=13) def test_highpass(self, xp): # high even order z, p, k = cheby1(24, 0.7, xp.asarray(0.2), 'high', output='zpk') z2 = xp.ones(24, dtype=xp.float64) p2 = [-6.136558509657073e-01 + 2.700091504942893e-01j, -6.136558509657073e-01 - 2.700091504942893e-01j, -3.303348340927516e-01 + 6.659400861114254e-01j, -3.303348340927516e-01 - 6.659400861114254e-01j, 8.779713780557169e-03 + 8.223108447483040e-01j, 8.779713780557169e-03 - 8.223108447483040e-01j, 2.742361123006911e-01 + 8.356666951611864e-01j, 2.742361123006911e-01 - 8.356666951611864e-01j, 4.562984557158206e-01 + 7.954276912303594e-01j, 4.562984557158206e-01 - 7.954276912303594e-01j, 5.777335494123628e-01 + 7.435821817961783e-01j, 5.777335494123628e-01 - 7.435821817961783e-01j, 6.593260977749194e-01 + 6.955390907990932e-01j, 6.593260977749194e-01 - 6.955390907990932e-01j, 7.149590948466562e-01 + 6.559437858502012e-01j, 7.149590948466562e-01 - 6.559437858502012e-01j, 7.532432388188739e-01 + 6.256158042292060e-01j, 7.532432388188739e-01 - 6.256158042292060e-01j, 7.794365244268271e-01 + 6.042099234813333e-01j, 7.794365244268271e-01 - 6.042099234813333e-01j, 7.967253874772997e-01 + 5.911966597313203e-01j, 7.967253874772997e-01 - 5.911966597313203e-01j, 8.069756417293870e-01 + 5.862214589217275e-01j, 8.069756417293870e-01 - 5.862214589217275e-01j] p2 = xp.asarray(p2, dtype=xp.complex128) k2 = 6.190427617192018e-04 xp_assert_equal(z, z2) xp_assert_close( _sort_cmplx(p, xp=xp), _sort_cmplx(p2, xp=xp), rtol=1e-10 if not DEFAULT_F32 else 1e-7 ) assert math.isclose(k, k2, rel_tol=1e-10 if not DEFAULT_F32 else 1e-6) # high odd order z, p, k = cheby1(23, 0.8, xp.asarray(0.3), 'high', output='zpk') z2 = xp.ones(23, dtype=xp.float64) p2 = [-7.676400532011010e-01, -6.754621070166477e-01 + 3.970502605619561e-01j, -6.754621070166477e-01 - 3.970502605619561e-01j, -4.528880018446727e-01 + 6.844061483786332e-01j, -4.528880018446727e-01 - 6.844061483786332e-01j, -1.986009130216447e-01 + 8.382285942941594e-01j, -1.986009130216447e-01 - 8.382285942941594e-01j, 2.504673931532608e-02 + 8.958137635794080e-01j, 2.504673931532608e-02 - 8.958137635794080e-01j, 2.001089429976469e-01 + 9.010678290791480e-01j, 2.001089429976469e-01 - 9.010678290791480e-01j, 3.302410157191755e-01 + 8.835444665962544e-01j, 3.302410157191755e-01 - 8.835444665962544e-01j, 4.246662537333661e-01 + 8.594054226449009e-01j, 4.246662537333661e-01 - 8.594054226449009e-01j, 4.919620928120296e-01 + 8.366772762965786e-01j, 4.919620928120296e-01 - 8.366772762965786e-01j, 5.385746917494749e-01 + 8.191616180796720e-01j, 5.385746917494749e-01 - 8.191616180796720e-01j, 5.855636993537203e-01 + 8.060680937701062e-01j, 5.855636993537203e-01 - 8.060680937701062e-01j, 5.688812849391721e-01 + 8.086497795114683e-01j, 5.688812849391721e-01 - 8.086497795114683e-01j] p2 = xp.asarray(p2, dtype=xp.complex128) k2 = 1.941697029206324e-05 xp_assert_equal(z, z2) xp_assert_close( _sort_cmplx(p, xp=xp), _sort_cmplx(p2, xp=xp), rtol=1e-10 if not DEFAULT_F32 else 1e-7 ) assert math.isclose( k, k2, rel_tol=1e-10 if not DEFAULT_F32 else 1e-6 ) z, p, k = cheby1(10, 1, xp.asarray(1000), 'high', analog=True, output='zpk') z2 = xp.zeros(10, dtype=xp.float64) p2 = [-3.144743169501551e+03 + 3.511680029092744e+03j, -3.144743169501551e+03 - 3.511680029092744e+03j, -5.633065604514602e+02 + 2.023615191183945e+03j, -5.633065604514602e+02 - 2.023615191183945e+03j, -1.946412183352025e+02 + 1.372309454274755e+03j, -1.946412183352025e+02 - 1.372309454274755e+03j, -7.987162953085479e+01 + 1.105207708045358e+03j, -7.987162953085479e+01 - 1.105207708045358e+03j, -2.250315039031946e+01 + 1.001723931471477e+03j, -2.250315039031946e+01 - 1.001723931471477e+03j] p2 = xp.asarray(p2, dtype=xp.complex128) k2 = 8.912509381337453e-01 xp_assert_equal(z, z2) xp_assert_close(_sort_cmplx(p, xp=xp), _sort_cmplx(p2, xp=xp), rtol=1e-13) assert math.isclose(k, k2, rel_tol=1e-15) def test_bandpass(self, xp): z, p, k = cheby1(8, 1, xp.asarray([0.3, 0.4]), 'bp', output='zpk') z2 = [1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1] p2 = [3.077784854851463e-01 + 9.453307017592942e-01j, 3.077784854851463e-01 - 9.453307017592942e-01j, 3.280567400654425e-01 + 9.272377218689016e-01j, 3.280567400654425e-01 - 9.272377218689016e-01j, 3.677912763284301e-01 + 9.038008865279966e-01j, 3.677912763284301e-01 - 9.038008865279966e-01j, 4.194425632520948e-01 + 8.769407159656157e-01j, 4.194425632520948e-01 - 8.769407159656157e-01j, 4.740921994669189e-01 + 8.496508528630974e-01j, 4.740921994669189e-01 - 8.496508528630974e-01j, 5.234866481897429e-01 + 8.259608422808477e-01j, 5.234866481897429e-01 - 8.259608422808477e-01j, 5.844717632289875e-01 + 8.052901363500210e-01j, 5.844717632289875e-01 - 8.052901363500210e-01j, 5.615189063336070e-01 + 8.100667803850766e-01j, 5.615189063336070e-01 - 8.100667803850766e-01j] z2 = xp.asarray(z2, dtype=xp.float64) p2 = xp.asarray(p2, dtype=xp.complex128) k2 = 5.007028718074307e-09 xp_assert_equal(z, z2, check_dtype=False) xp_assert_close( _sort_cmplx(p, xp=xp), _sort_cmplx(p2, xp=xp), rtol=1e-13 if not DEFAULT_F32 else 1e-7 ) assert math.isclose(k, k2, rel_tol=1e-13 if not DEFAULT_F32 else 1e-6) def test_bandstop(self, xp): z, p, k = cheby1(7, 1, xp.asarray([0.5, 0.6]), 'stop', output='zpk') z2 = [-1.583844403245361e-01 + 9.873775210440450e-01j, -1.583844403245361e-01 - 9.873775210440450e-01j, -1.583844403245361e-01 + 9.873775210440450e-01j, -1.583844403245361e-01 - 9.873775210440450e-01j, -1.583844403245361e-01 + 9.873775210440450e-01j, -1.583844403245361e-01 - 9.873775210440450e-01j, -1.583844403245361e-01 + 9.873775210440450e-01j, -1.583844403245361e-01 - 9.873775210440450e-01j, -1.583844403245361e-01 + 9.873775210440450e-01j, -1.583844403245361e-01 - 9.873775210440450e-01j, -1.583844403245361e-01 + 9.873775210440450e-01j, -1.583844403245361e-01 - 9.873775210440450e-01j, -1.583844403245361e-01 + 9.873775210440450e-01j, -1.583844403245361e-01 - 9.873775210440450e-01j] p2 = [-8.942974551472813e-02 + 3.482480481185926e-01j, -8.942974551472813e-02 - 3.482480481185926e-01j, 1.293775154041798e-01 + 8.753499858081858e-01j, 1.293775154041798e-01 - 8.753499858081858e-01j, 3.399741945062013e-02 + 9.690316022705607e-01j, 3.399741945062013e-02 - 9.690316022705607e-01j, 4.167225522796539e-04 + 9.927338161087488e-01j, 4.167225522796539e-04 - 9.927338161087488e-01j, -3.912966549550960e-01 + 8.046122859255742e-01j, -3.912966549550960e-01 - 8.046122859255742e-01j, -3.307805547127368e-01 + 9.133455018206508e-01j, -3.307805547127368e-01 - 9.133455018206508e-01j, -3.072658345097743e-01 + 9.443589759799366e-01j, -3.072658345097743e-01 - 9.443589759799366e-01j] z2 = xp.asarray(z2, dtype=xp.complex128) p2 = xp.asarray(p2, dtype=xp.complex128) k2 = 3.619438310405028e-01 xp_assert_close( _sort_cmplx(z, xp=xp), _sort_cmplx(z2, xp=xp), rtol=1e-13 if not DEFAULT_F32 else 1e-6 ) xp_assert_close( _sort_cmplx(p, xp=xp), _sort_cmplx(p2, xp=xp), rtol=1e-13 if not DEFAULT_F32 else 1e-6 ) assert math.isclose( k, k2, rel_tol=0, abs_tol=5e-16 if not DEFAULT_F32 else 1e-7 ) @xfail_xp_backends("cupy", reason="inaccurate on CuPy") def test_ba_output(self, xp): # with transfer function conversion, without digital conversion b, a = cheby1(5, 0.9, xp.asarray([210, 310.0]), 'stop', analog=True) b2 = [1.000000000000006e+00, 0, 3.255000000000020e+05, 0, 4.238010000000026e+10, 0, 2.758944510000017e+15, 0, 8.980364380050052e+19, 0, 1.169243442282517e+24 ] a2 = [1.000000000000000e+00, 4.630555945694342e+02, 4.039266454794788e+05, 1.338060988610237e+08, 5.844333551294591e+10, 1.357346371637638e+13, 3.804661141892782e+15, 5.670715850340080e+17, 1.114411200988328e+20, 8.316815934908471e+21, 1.169243442282517e+24 ] b2, a2 = map(lambda t: xp.asarray(t, dtype=xp.float64), (b2, a2)) xp_assert_close(b, b2, rtol=1e-14 if not DEFAULT_F32 else 1e-7) xp_assert_close(a, a2, rtol=1e-14 if not DEFAULT_F32 else 1e-7) def test_fs_param(self): for fs in (900, 900.1, 1234.567): for N in (0, 1, 2, 3, 10): for fc in (100, 100.1, 432.12345): for btype in ('lp', 'hp'): ba1 = cheby1(N, 1, fc, btype, fs=fs) ba2 = cheby1(N, 1, fc/(fs/2), btype) for ba1_, ba2_ in zip(ba1, ba2): xp_assert_close(ba1_, ba2_) for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)): for btype in ('bp', 'bs'): ba1 = cheby1(N, 1, fc, btype, fs=fs) for seq in (list, tuple, array): fcnorm = seq([f/(fs/2) for f in fc]) ba2 = cheby1(N, 1, fcnorm, btype) for ba1_, ba2_ in zip(ba1, ba2): xp_assert_close(ba1_, ba2_) @skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883") @make_xp_test_case(cheby2)
TestCheby1
python
kamyu104__LeetCode-Solutions
Python/minimum-operations-to-reduce-an-integer-to-0.py
{ "start": 451, "end": 748 }
class ____(object): def minOperations(self, n): """ :type n: int :rtype: int """ result = 0 while n: if n&1: n >>= 1 n += n&1 result += 1 n >>= 1 return result
Solution2
python
pypa__hatch
tests/backend/builders/test_sdist.py
{ "start": 1098, "end": 2421 }
class ____: def test_default(self, isolation): builder = SdistBuilder(str(isolation)) assert builder.config.core_metadata_constructor is builder.config.core_metadata_constructor assert builder.config.core_metadata_constructor is get_core_metadata_constructors()[DEFAULT_METADATA_VERSION] def test_not_string(self, isolation): config = {"tool": {"hatch": {"build": {"targets": {"sdist": {"core-metadata-version": 42}}}}}} builder = SdistBuilder(str(isolation), config=config) with pytest.raises( TypeError, match="Field `tool.hatch.build.targets.sdist.core-metadata-version` must be a string" ): _ = builder.config.core_metadata_constructor def test_unknown(self, isolation): config = {"tool": {"hatch": {"build": {"targets": {"sdist": {"core-metadata-version": "9000"}}}}}} builder = SdistBuilder(str(isolation), config=config) with pytest.raises( ValueError, match=( f"Unknown metadata version `9000` for field `tool.hatch.build.targets.sdist.core-metadata-version`. " f"Available: {', '.join(sorted(get_core_metadata_constructors()))}" ), ): _ = builder.config.core_metadata_constructor
TestCoreMetadataConstructor
python
sympy__sympy
sympy/stats/frv_types.py
{ "start": 5337, "end": 7243 }
class ____(SingleFiniteDistribution): _argnames = ('sides',) @staticmethod def check(sides): _value_check((sides.is_positive, sides.is_integer), "number of sides must be a positive integer.") @property def is_symbolic(self): return not self.sides.is_number @property def high(self): return self.sides @property def low(self): return S.One @property def set(self): if self.is_symbolic: return Intersection(S.Naturals0, Interval(0, self.sides)) return set(map(Integer, range(1, self.sides + 1))) def pmf(self, x): x = sympify(x) if not (x.is_number or x.is_Symbol or is_random(x)): raise ValueError("'x' expected as an argument of type 'number', 'Symbol', or " "'RandomSymbol' not %s" % (type(x))) cond = Ge(x, 1) & Le(x, self.sides) & Contains(x, S.Integers) return Piecewise((S.One/self.sides, cond), (S.Zero, True)) def Die(name, sides=6): r""" Create a Finite Random Variable representing a fair die. Parameters ========== sides : Integer Represents the number of sides of the Die, by default is 6 Examples ======== >>> from sympy.stats import Die, density >>> from sympy import Symbol >>> D6 = Die('D6', 6) # Six sided Die >>> density(D6).dict {1: 1/6, 2: 1/6, 3: 1/6, 4: 1/6, 5: 1/6, 6: 1/6} >>> D4 = Die('D4', 4) # Four sided Die >>> density(D4).dict {1: 1/4, 2: 1/4, 3: 1/4, 4: 1/4} >>> n = Symbol('n', positive=True, integer=True) >>> Dn = Die('Dn', n) # n sided Die >>> density(Dn).dict Density(DieDistribution(n)) >>> density(Dn).dict.subs(n, 4).doit() {1: 1/4, 2: 1/4, 3: 1/4, 4: 1/4} Returns ======= RandomSymbol """ return rv(name, DieDistribution, sides)
DieDistribution