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
fluentpython__example-code-2e
24-class-metaprog/metabunch/nutshell3e/bunch.py
{ "start": 3447, "end": 3752 }
class ____(metaclass=MetaBunch): """ For convenience: inheriting from Bunch can be used to get the new metaclass (same as defining metaclass= yourself). In v2, remove the (metaclass=MetaBunch) above and add instead __metaclass__=MetaBunch as the class body. """ pass
Bunch
python
PyCQA__pylint
tests/message/unittest_message_definition.py
{ "start": 1254, "end": 1651 }
class ____(BaseChecker): def __init__(self) -> None: super().__init__(PyLinter()) name = "FalseChecker" msgs = { "W1234": ("message one", "msg-symbol-one", "msg description"), "W1235": ( "message two", "msg-symbol-two", "msg description", {"old_names": [("W1230", "msg-symbol-one")]}, ), }
FalseChecker
python
Textualize__textual
docs/examples/styles/link_background_hover.py
{ "start": 64, "end": 778 }
class ____(App): CSS_PATH = "link_background_hover.tcss" def compose(self): yield Label( "Visit the [link='https://textualize.io']Textualize[/link] website.", id="lbl1", # (1)! ) yield Label( "Click [@click=app.bell]here[/] for the bell sound.", id="lbl2", # (2)! ) yield Label( "You can also click [@click=app.bell]here[/] for the bell sound.", id="lbl3", # (3)! ) yield Label( "[@click=app.quit]Exit this application.[/]", id="lbl4", # (4)! ) if __name__ == "__main__": app = LinkHoverBackgroundApp() app.run()
LinkHoverBackgroundApp
python
redis__redis-py
tests/entraid_utils.py
{ "start": 858, "end": 5646 }
class ____(Enum): MANAGED_IDENTITY = "managed_identity" SERVICE_PRINCIPAL = "service_principal" DEFAULT_AZURE_CREDENTIAL = "default_azure_credential" def identity_provider(request) -> IdentityProviderInterface: if hasattr(request, "param"): kwargs = request.param.get("idp_kwargs", {}) else: kwargs = {} if request.param.get("mock_idp", None) is not None: return mock_identity_provider() auth_type = kwargs.get("auth_type", AuthType.SERVICE_PRINCIPAL) config = get_identity_provider_config(request=request) if auth_type == AuthType.MANAGED_IDENTITY: return _create_provider_from_managed_identity(config) if auth_type == AuthType.DEFAULT_AZURE_CREDENTIAL: return _create_provider_from_default_azure_credential(config) return _create_provider_from_service_principal(config) def get_identity_provider_config( request, ) -> Union[ ManagedIdentityProviderConfig, ServicePrincipalIdentityProviderConfig, DefaultAzureCredentialIdentityProviderConfig, ]: if hasattr(request, "param"): kwargs = request.param.get("idp_kwargs", {}) else: kwargs = {} auth_type = kwargs.pop("auth_type", AuthType.SERVICE_PRINCIPAL) if auth_type == AuthType.MANAGED_IDENTITY: return _get_managed_identity_provider_config(request) if auth_type == AuthType.DEFAULT_AZURE_CREDENTIAL: return _get_default_azure_credential_provider_config(request) return _get_service_principal_provider_config(request) def _get_managed_identity_provider_config(request) -> ManagedIdentityProviderConfig: resource = os.getenv("AZURE_RESOURCE") id_value = os.getenv("AZURE_USER_ASSIGNED_MANAGED_ID", None) if hasattr(request, "param"): kwargs = request.param.get("idp_kwargs", {}) else: kwargs = {} identity_type = kwargs.pop("identity_type", ManagedIdentityType.SYSTEM_ASSIGNED) id_type = kwargs.pop("id_type", ManagedIdentityIdType.OBJECT_ID) return ManagedIdentityProviderConfig( identity_type=identity_type, resource=resource, id_type=id_type, id_value=id_value, kwargs=kwargs, ) def _get_service_principal_provider_config( request, ) -> ServicePrincipalIdentityProviderConfig: client_id = os.getenv("AZURE_CLIENT_ID") client_credential = os.getenv("AZURE_CLIENT_SECRET") tenant_id = os.getenv("AZURE_TENANT_ID") scopes = os.getenv("AZURE_REDIS_SCOPES", None) if hasattr(request, "param"): kwargs = request.param.get("idp_kwargs", {}) token_kwargs = request.param.get("token_kwargs", {}) timeout = request.param.get("timeout", None) else: kwargs = {} token_kwargs = {} timeout = None if isinstance(scopes, str): scopes = scopes.split(",") return ServicePrincipalIdentityProviderConfig( client_id=client_id, client_credential=client_credential, scopes=scopes, timeout=timeout, token_kwargs=token_kwargs, tenant_id=tenant_id, app_kwargs=kwargs, ) def _get_default_azure_credential_provider_config( request, ) -> DefaultAzureCredentialIdentityProviderConfig: scopes = os.getenv("AZURE_REDIS_SCOPES", ()) if hasattr(request, "param"): kwargs = request.param.get("idp_kwargs", {}) token_kwargs = request.param.get("token_kwargs", {}) else: kwargs = {} token_kwargs = {} if isinstance(scopes, str): scopes = scopes.split(",") return DefaultAzureCredentialIdentityProviderConfig( scopes=scopes, app_kwargs=kwargs, token_kwargs=token_kwargs ) def get_entra_id_credentials_provider(request, cred_provider_kwargs): idp = identity_provider(request) expiration_refresh_ratio = cred_provider_kwargs.get( "expiration_refresh_ratio", DEFAULT_EXPIRATION_REFRESH_RATIO ) lower_refresh_bound_millis = cred_provider_kwargs.get( "lower_refresh_bound_millis", DEFAULT_LOWER_REFRESH_BOUND_MILLIS ) max_attempts = cred_provider_kwargs.get("max_attempts", DEFAULT_MAX_ATTEMPTS) delay_in_ms = cred_provider_kwargs.get("delay_in_ms", DEFAULT_DELAY_IN_MS) token_mgr_config = TokenManagerConfig( expiration_refresh_ratio=expiration_refresh_ratio, lower_refresh_bound_millis=lower_refresh_bound_millis, token_request_execution_timeout_in_ms=DEFAULT_TOKEN_REQUEST_EXECUTION_TIMEOUT_IN_MS, # noqa retry_policy=RetryPolicy( max_attempts=max_attempts, delay_in_ms=delay_in_ms, ), ) return EntraIdCredentialsProvider( identity_provider=idp, token_manager_config=token_mgr_config, initial_delay_in_ms=delay_in_ms, )
AuthType
python
PrefectHQ__prefect
src/prefect/transactions.py
{ "start": 15314, "end": 26819 }
class ____(BaseTransaction): """ A model representing the state of an asynchronous transaction. """ async def begin(self) -> None: if ( self.store and self.key and self.isolation_level == IsolationLevel.SERIALIZABLE ): self.logger.debug(f"Acquiring lock for transaction {self.key!r}") await self.store.aacquire_lock(self.key, holder=self._holder) if ( not self.overwrite and self.store and self.key and await self.store.aexists(key=self.key) ): self.state = TransactionState.COMMITTED async def read(self) -> ResultRecord[Any] | None: if self.store and self.key: return await self.store.aread(key=self.key, holder=self._holder) return None async def reset(self) -> None: parent = self.get_parent() if parent: # parent takes responsibility parent.add_child(self) if self._token: self.__var__.reset(self._token) self._token = None # do this below reset so that get_transaction() returns the relevant txn if parent and self.state == TransactionState.ROLLED_BACK: maybe_coro = parent.rollback() if inspect.isawaitable(maybe_coro): await maybe_coro async def commit(self) -> bool: if self.state in [TransactionState.ROLLED_BACK, TransactionState.COMMITTED]: if ( self.store and self.key and self.isolation_level == IsolationLevel.SERIALIZABLE ): self.logger.debug(f"Releasing lock for transaction {self.key!r}") self.store.release_lock(self.key, holder=self._holder) return False try: for child in self.children: if isinstance(child, AsyncTransaction): await child.commit() else: child.commit() for hook in self.on_commit_hooks: await self.run_hook(hook, "commit") if self.store and self.key and self.write_on_commit: if isinstance(self._staged_value, ResultRecord): await self.store.apersist_result_record( result_record=self._staged_value, holder=self._holder ) else: await self.store.awrite( key=self.key, obj=self._staged_value, holder=self._holder ) self.state = TransactionState.COMMITTED if ( self.store and self.key and self.isolation_level == IsolationLevel.SERIALIZABLE ): self.logger.debug(f"Releasing lock for transaction {self.key!r}") self.store.release_lock(self.key, holder=self._holder) return True except SerializationError as exc: if self.logger: self.logger.warning( f"Encountered an error while serializing result for transaction {self.key!r}: {exc}" " Code execution will continue, but the transaction will not be committed.", ) await self.rollback() return False except Exception: if self.logger: self.logger.exception( f"An error was encountered while committing transaction {self.key!r}", exc_info=True, ) await self.rollback() return False async def run_hook(self, hook: Callable[..., Any], hook_type: str) -> None: hook_name = get_hook_name(hook) # Undocumented way to disable logging for a hook. Subject to change. should_log = getattr(hook, "log_on_run", True) if should_log: self.logger.info(f"Running {hook_type} hook {hook_name!r}") try: if inspect.iscoroutinefunction(hook): await hook(self) else: await anyio.to_thread.run_sync(hook, self) except Exception as exc: if should_log: self.logger.error( f"An error was encountered while running {hook_type} hook {hook_name!r}", ) raise exc else: if should_log: self.logger.info( f"{hook_type.capitalize()} hook {hook_name!r} finished running successfully" ) async def rollback(self) -> bool: if self.state in [TransactionState.ROLLED_BACK, TransactionState.COMMITTED]: return False try: for hook in reversed(self.on_rollback_hooks): await self.run_hook(hook, "rollback") self.state: TransactionState = TransactionState.ROLLED_BACK for child in reversed(self.children): if isinstance(child, AsyncTransaction): await child.rollback() else: child.rollback() return True except Exception: if self.logger: self.logger.exception( f"An error was encountered while rolling back transaction {self.key!r}", exc_info=True, ) return False finally: if ( self.store and self.key and self.isolation_level == IsolationLevel.SERIALIZABLE ): self.logger.debug(f"Releasing lock for transaction {self.key!r}") self.store.release_lock(self.key, holder=self._holder) async def __aenter__(self) -> Self: self.prepare_transaction() await self.begin() self._token = self.__var__.set(self) return self async def __aexit__(self, *exc_info: Any) -> None: exc_type, exc_val, _ = exc_info if not self._token: raise RuntimeError( "Asymmetric use of context. Context exit called without an enter." ) if exc_type: await self.rollback() await self.reset() raise exc_val if self.commit_mode == CommitMode.EAGER: await self.commit() # if parent, let them take responsibility if self.get_parent(): await self.reset() return if self.commit_mode == CommitMode.OFF: # if no one took responsibility to commit, rolling back # note that rollback returns if already committed await self.rollback() elif self.commit_mode == CommitMode.LAZY: # no one left to take responsibility for committing await self.commit() await self.reset() def __enter__(self) -> NoReturn: raise NotImplementedError( "AsyncTransaction does not support the `with` statement. Use the `async with` statement instead." ) def __exit__(self, *exc_info: Any) -> NoReturn: raise NotImplementedError( "AsyncTransaction does not support the `with` statement. Use the `async with` statement instead." ) def get_transaction() -> BaseTransaction | None: return BaseTransaction.get_active() @contextmanager def transaction( key: str | None = None, store: ResultStore | None = None, commit_mode: CommitMode | None = None, isolation_level: IsolationLevel | None = None, overwrite: bool = False, write_on_commit: bool = True, logger: logging.Logger | LoggingAdapter | None = None, ) -> Generator[Transaction, None, None]: """ A context manager for opening and managing a transaction. Args: - key: An identifier to use for the transaction - store: The store to use for persisting the transaction result. If not provided, a default store will be used based on the current run context. - commit_mode: The commit mode controlling when the transaction and child transactions are committed - overwrite: Whether to overwrite an existing transaction record in the store - write_on_commit: Whether to write the result to the store on commit. If not provided, will default will be determined by the current run context. If no run context is available, the value of `PREFECT_RESULTS_PERSIST_BY_DEFAULT` will be used. Yields: - Transaction: An object representing the transaction state """ # if there is no key, we won't persist a record if key and not store: store = get_result_store() # Avoid inheriting a NullFileSystem for metadata_storage from a flow's result store if store and isinstance(store.metadata_storage, NullFileSystem): store = store.model_copy(update={"metadata_storage": None}) try: _logger: Union[logging.Logger, LoggingAdapter] = logger or get_run_logger() except MissingContextError: _logger = get_logger("transactions") with Transaction( key=key, store=store, commit_mode=commit_mode, isolation_level=isolation_level, overwrite=overwrite, write_on_commit=write_on_commit, logger=_logger, ) as txn: yield txn @asynccontextmanager async def atransaction( key: str | None = None, store: ResultStore | None = None, commit_mode: CommitMode | None = None, isolation_level: IsolationLevel | None = None, overwrite: bool = False, write_on_commit: bool = True, logger: logging.Logger | LoggingAdapter | None = None, ) -> AsyncGenerator[AsyncTransaction, None]: """ An asynchronous context manager for opening and managing an asynchronous transaction. Args: - key: An identifier to use for the transaction - store: The store to use for persisting the transaction result. If not provided, a default store will be used based on the current run context. - commit_mode: The commit mode controlling when the transaction and child transactions are committed - overwrite: Whether to overwrite an existing transaction record in the store - write_on_commit: Whether to write the result to the store on commit. If not provided, the default will be determined by the current run context. If no run context is available, the value of `PREFECT_RESULTS_PERSIST_BY_DEFAULT` will be used. Yields: - AsyncTransaction: An object representing the transaction state """ # if there is no key, we won't persist a record if key and not store: store = get_result_store() # Avoid inheriting a NullFileSystem for metadata_storage from a flow's result store if store and isinstance(store.metadata_storage, NullFileSystem): store = store.model_copy(update={"metadata_storage": None}) try: _logger: Union[logging.Logger, LoggingAdapter] = logger or get_run_logger() except MissingContextError: _logger = get_logger("transactions") async with AsyncTransaction( key=key, store=store, commit_mode=commit_mode, isolation_level=isolation_level, overwrite=overwrite, write_on_commit=write_on_commit, logger=_logger, ) as txn: yield txn
AsyncTransaction
python
ipython__ipython
IPython/utils/ipstruct.py
{ "start": 878, "end": 11856 }
class ____(dict): """A dict subclass with attribute style access. This dict subclass has a a few extra features: * Attribute style access. * Protection of class members (like keys, items) when using attribute style access. * The ability to restrict assignment to only existing keys. * Intelligent merging. * Overloaded operators. """ _allownew = True def __init__(self, *args, **kw): """Initialize with a dictionary, another Struct, or data. Parameters ---------- *args : dict, Struct Initialize with one dict or Struct **kw : dict Initialize with key, value pairs. Examples -------- >>> s = Struct(a=10,b=30) >>> s.a 10 >>> s.b 30 >>> s2 = Struct(s,c=30) >>> sorted(s2.keys()) ['a', 'b', 'c'] """ object.__setattr__(self, '_allownew', True) dict.__init__(self, *args, **kw) def __setitem__(self, key, value): """Set an item with check for allownew. Examples -------- >>> s = Struct() >>> s['a'] = 10 >>> s.allow_new_attr(False) >>> s['a'] = 10 >>> s['a'] 10 >>> try: ... s['b'] = 20 ... except KeyError: ... print('this is not allowed') ... this is not allowed """ if not self._allownew and key not in self: raise KeyError( "can't create new attribute %s when allow_new_attr(False)" % key) dict.__setitem__(self, key, value) def __setattr__(self, key, value): """Set an attr with protection of class members. This calls :meth:`self.__setitem__` but convert :exc:`KeyError` to :exc:`AttributeError`. Examples -------- >>> s = Struct() >>> s.a = 10 >>> s.a 10 >>> try: ... s.get = 10 ... except AttributeError: ... print("you can't set a class member") ... you can't set a class member """ # If key is an str it might be a class member or instance var if isinstance(key, str): # I can't simply call hasattr here because it calls getattr, which # calls self.__getattr__, which returns True for keys in # self._data. But I only want keys in the class and in # self.__dict__ if key in self.__dict__ or hasattr(Struct, key): raise AttributeError( 'attr %s is a protected member of class Struct.' % key ) try: self.__setitem__(key, value) except KeyError as e: raise AttributeError(e) from e def __getattr__(self, key): """Get an attr by calling :meth:`dict.__getitem__`. Like :meth:`__setattr__`, this method converts :exc:`KeyError` to :exc:`AttributeError`. Examples -------- >>> s = Struct(a=10) >>> s.a 10 >>> type(s.get) <...method'> >>> try: ... s.b ... except AttributeError: ... print("I don't have that key") ... I don't have that key """ try: result = self[key] except KeyError as e: raise AttributeError(key) from e else: return result def __iadd__(self, other): """s += s2 is a shorthand for s.merge(s2). Examples -------- >>> s = Struct(a=10,b=30) >>> s2 = Struct(a=20,c=40) >>> s += s2 >>> sorted(s.keys()) ['a', 'b', 'c'] """ self.merge(other) return self def __add__(self,other): """s + s2 -> New Struct made from s.merge(s2). Examples -------- >>> s1 = Struct(a=10,b=30) >>> s2 = Struct(a=20,c=40) >>> s = s1 + s2 >>> sorted(s.keys()) ['a', 'b', 'c'] """ sout = self.copy() sout.merge(other) return sout def __sub__(self,other): """s1 - s2 -> remove keys in s2 from s1. Examples -------- >>> s1 = Struct(a=10,b=30) >>> s2 = Struct(a=40) >>> s = s1 - s2 >>> s {'b': 30} """ sout = self.copy() sout -= other return sout def __isub__(self,other): """Inplace remove keys from self that are in other. Examples -------- >>> s1 = Struct(a=10,b=30) >>> s2 = Struct(a=40) >>> s1 -= s2 >>> s1 {'b': 30} """ for k in other.keys(): if k in self: del self[k] return self def __dict_invert(self, data): """Helper function for merge. Takes a dictionary whose values are lists and returns a dict with the elements of each list as keys and the original keys as values. """ outdict = {} for k,lst in data.items(): if isinstance(lst, str): lst = lst.split() for entry in lst: outdict[entry] = k return outdict def dict(self): return self def copy(self): """Return a copy as a Struct. Examples -------- >>> s = Struct(a=10,b=30) >>> s2 = s.copy() >>> type(s2) is Struct True """ return Struct(dict.copy(self)) def hasattr(self, key): """hasattr function available as a method. Implemented like has_key. Examples -------- >>> s = Struct(a=10) >>> s.hasattr('a') True >>> s.hasattr('b') False >>> s.hasattr('get') False """ return key in self def allow_new_attr(self, allow = True): """Set whether new attributes can be created in this Struct. This can be used to catch typos by verifying that the attribute user tries to change already exists in this Struct. """ object.__setattr__(self, '_allownew', allow) def merge(self, __loc_data__=None, __conflict_solve=None, **kw): """Merge two Structs with customizable conflict resolution. This is similar to :meth:`update`, but much more flexible. First, a dict is made from data+key=value pairs. When merging this dict with the Struct S, the optional dictionary 'conflict' is used to decide what to do. If conflict is not given, the default behavior is to preserve any keys with their current value (the opposite of the :meth:`update` method's behavior). Parameters ---------- __loc_data__ : dict, Struct The data to merge into self __conflict_solve : dict The conflict policy dict. The keys are binary functions used to resolve the conflict and the values are lists of strings naming the keys the conflict resolution function applies to. Instead of a list of strings a space separated string can be used, like 'a b c'. **kw : dict Additional key, value pairs to merge in Notes ----- The `__conflict_solve` dict is a dictionary of binary functions which will be used to solve key conflicts. Here is an example:: __conflict_solve = dict( func1=['a','b','c'], func2=['d','e'] ) In this case, the function :func:`func1` will be used to resolve keys 'a', 'b' and 'c' and the function :func:`func2` will be used for keys 'd' and 'e'. This could also be written as:: __conflict_solve = dict(func1='a b c',func2='d e') These functions will be called for each key they apply to with the form:: func1(self['a'], other['a']) The return value is used as the final merged value. As a convenience, merge() provides five (the most commonly needed) pre-defined policies: preserve, update, add, add_flip and add_s. The easiest explanation is their implementation:: preserve = lambda old,new: old update = lambda old,new: new add = lambda old,new: old + new add_flip = lambda old,new: new + old # note change of order! add_s = lambda old,new: old + ' ' + new # only for str! You can use those four words (as strings) as keys instead of defining them as functions, and the merge method will substitute the appropriate functions for you. For more complicated conflict resolution policies, you still need to construct your own functions. Examples -------- This show the default policy: >>> s = Struct(a=10,b=30) >>> s2 = Struct(a=20,c=40) >>> s.merge(s2) >>> sorted(s.items()) [('a', 10), ('b', 30), ('c', 40)] Now, show how to specify a conflict dict: >>> s = Struct(a=10,b=30) >>> s2 = Struct(a=20,b=40) >>> conflict = {'update':'a','add':'b'} >>> s.merge(s2,conflict) >>> sorted(s.items()) [('a', 20), ('b', 70)] """ data_dict = dict(__loc_data__,**kw) # policies for conflict resolution: two argument functions which return # the value that will go in the new struct preserve = lambda old,new: old update = lambda old,new: new add = lambda old,new: old + new add_flip = lambda old,new: new + old # note change of order! add_s = lambda old,new: old + ' ' + new # default policy is to keep current keys when there's a conflict conflict_solve = dict.fromkeys(self, preserve) # the conflict_solve dictionary is given by the user 'inverted': we # need a name-function mapping, it comes as a function -> names # dict. Make a local copy (b/c we'll make changes), replace user # strings for the three builtin policies and invert it. if __conflict_solve: inv_conflict_solve_user = __conflict_solve.copy() for name, func in [('preserve',preserve), ('update',update), ('add',add), ('add_flip',add_flip), ('add_s',add_s)]: if name in inv_conflict_solve_user.keys(): inv_conflict_solve_user[func] = inv_conflict_solve_user[name] del inv_conflict_solve_user[name] conflict_solve.update(self.__dict_invert(inv_conflict_solve_user)) for key in data_dict: if key not in self: self[key] = data_dict[key] else: self[key] = conflict_solve[key](self[key],data_dict[key])
Struct
python
spack__spack
lib/spack/spack/test/variant.py
{ "start": 13884, "end": 32259 }
class ____: def test_invalid_values(self) -> None: # Value with invalid type a = VariantMap(Spec()) with pytest.raises(TypeError): a["foo"] = 2 # Duplicate variant a["foo"] = MultiValuedVariant("foo", ("bar", "baz")) with pytest.raises(DuplicateVariantError): a["foo"] = MultiValuedVariant("foo", ("bar",)) with pytest.raises(DuplicateVariantError): a["foo"] = SingleValuedVariant("foo", "bar") with pytest.raises(DuplicateVariantError): a["foo"] = BoolValuedVariant("foo", True) # Non matching names between key and vspec.name with pytest.raises(KeyError): a["bar"] = MultiValuedVariant("foo", ("bar",)) def test_set_item(self) -> None: # Check that all the three types of variants are accepted a = VariantMap(Spec()) a["foo"] = BoolValuedVariant("foo", True) a["bar"] = SingleValuedVariant("bar", "baz") a["foobar"] = MultiValuedVariant("foobar", ("a", "b", "c", "d", "e")) def test_substitute(self) -> None: # Check substitution of a key that exists a = VariantMap(Spec()) a["foo"] = BoolValuedVariant("foo", True) a.substitute(SingleValuedVariant("foo", "bar")) # Trying to substitute something that is not # in the map will raise a KeyError with pytest.raises(KeyError): a.substitute(BoolValuedVariant("bar", True)) def test_satisfies_and_constrain(self) -> None: # foo=bar foobar=fee feebar=foo a = VariantMap(Spec()) a["foo"] = MultiValuedVariant("foo", ("bar",)) a["foobar"] = SingleValuedVariant("foobar", "fee") a["feebar"] = SingleValuedVariant("feebar", "foo") # foo=bar,baz foobar=fee shared=True b = VariantMap(Spec()) b["foo"] = MultiValuedVariant("foo", ("bar", "baz")) b["foobar"] = SingleValuedVariant("foobar", "fee") b["shared"] = BoolValuedVariant("shared", True) # concrete, different values do not intersect / satisfy each other assert not a.intersects(b) and not b.intersects(a) assert not a.satisfies(b) and not b.satisfies(a) # foo=bar,baz foobar=fee feebar=foo shared=True c = VariantMap(Spec()) c["foo"] = MultiValuedVariant("foo", ("bar", "baz")) c["foobar"] = SingleValuedVariant("foobar", "fee") c["feebar"] = SingleValuedVariant("feebar", "foo") c["shared"] = BoolValuedVariant("shared", True) # concrete values cannot be constrained with pytest.raises(spack.variant.UnsatisfiableVariantSpecError): a.constrain(b) def test_copy(self) -> None: a = VariantMap(Spec()) a["foo"] = BoolValuedVariant("foo", True) a["bar"] = SingleValuedVariant("bar", "baz") a["foobar"] = MultiValuedVariant("foobar", ("a", "b", "c", "d", "e")) c = a.copy() assert a == c def test_str(self) -> None: c = VariantMap(Spec()) c["foo"] = MultiValuedVariant("foo", ("bar", "baz")) c["foobar"] = SingleValuedVariant("foobar", "fee") c["feebar"] = SingleValuedVariant("feebar", "foo") c["shared"] = BoolValuedVariant("shared", True) assert str(c) == "+shared feebar=foo foo:=bar,baz foobar=fee" def test_disjoint_set_initialization_errors(): # Constructing from non-disjoint sets should raise an exception with pytest.raises(spack.error.SpecError) as exc_info: disjoint_sets(("a", "b"), ("b", "c")) assert "sets in input must be disjoint" in str(exc_info.value) # A set containing the reserved item 'none' along with other items # should raise an exception with pytest.raises(spack.error.SpecError) as exc_info: disjoint_sets(("a", "b"), ("none", "c")) assert "The value 'none' represents the empty set," in str(exc_info.value) def test_disjoint_set_initialization(): # Test that no error is thrown when the sets are disjoint d = disjoint_sets(("a",), ("b", "c"), ("e", "f")) assert d.default == "none" assert d.multi is True assert set(x for x in d) == set(["none", "a", "b", "c", "e", "f"]) def test_disjoint_set_fluent_methods(): # Construct an object without the empty set d = disjoint_sets(("a",), ("b", "c"), ("e", "f")).prohibit_empty_set() assert set(("none",)) not in d.sets # Call this 2 times to check that no matter whether # the empty set was allowed or not before, the state # returned is consistent. for _ in range(2): d = d.allow_empty_set() assert set(("none",)) in d.sets assert "none" in d assert "none" in [x for x in d] assert "none" in d.feature_values # Marking a value as 'non-feature' removes it from the # list of feature values, but not for the items returned # when iterating over the object. d = d.with_non_feature_values("none") assert "none" in d assert "none" in [x for x in d] assert "none" not in d.feature_values # Call this 2 times to check that no matter whether # the empty set was allowed or not before, the state # returned is consistent. for _ in range(2): d = d.prohibit_empty_set() assert set(("none",)) not in d.sets assert "none" not in d assert "none" not in [x for x in d] assert "none" not in d.feature_values @pytest.mark.regression("32694") @pytest.mark.parametrize("other", [True, False]) def test_conditional_value_comparable_to_bool(other): value = spack.variant.ConditionalValue("98", when=Spec("@1.0")) comparison = value == other assert comparison is False @pytest.mark.regression("40405") def test_wild_card_valued_variants_equivalent_to_str(): """ There was a bug prioro to PR 40406 in that variants with wildcard values "*" were being overwritten in the variant constructor. The expected/appropriate behavior is for it to behave like value=str and this test demonstrates that the two are now equivalent """ str_var = spack.variant.Variant( name="str_var", default="none", values=str, description="str variant", multi=True, validator=None, ) wild_var = spack.variant.Variant( name="wild_var", default="none", values="*", description="* variant", multi=True, validator=None, ) several_arbitrary_values = ("doe", "re", "mi") # "*" case wild_output = wild_var.make_variant(*several_arbitrary_values) wild_var.validate_or_raise(wild_output, "test-package") # str case str_output = str_var.make_variant(*several_arbitrary_values) str_var.validate_or_raise(str_output, "test-package") # equivalence each instance already validated assert str_output.value == wild_output.value def test_variant_definitions(mock_packages): pkg = spack.repo.PATH.get_pkg_class("variant-values") # two variant names assert len(pkg.variant_names()) == 2 assert "build_system" in pkg.variant_names() assert "v" in pkg.variant_names() # this name doesn't exist assert len(pkg.variant_definitions("no-such-variant")) == 0 # there are 4 definitions but one is completely shadowed by another assert len(pkg.variants) == 4 # variant_items ignores the shadowed definition assert len(list(pkg.variant_items())) == 3 # variant_definitions also ignores the shadowed definition defs = [vdef for _, vdef in pkg.variant_definitions("v")] assert len(defs) == 2 assert defs[0].default == "foo" assert defs[0].values == ("foo",) assert defs[1].default == "bar" assert defs[1].values == ("foo", "bar") @pytest.mark.parametrize( "pkg_name,value,spec,def_ids", [ ("variant-values", "foo", "", [0, 1]), ("variant-values", "bar", "", [1]), ("variant-values", "foo", "@1.0", [0]), ("variant-values", "foo", "@2.0", [1]), ("variant-values", "foo", "@3.0", [1]), ("variant-values", "foo", "@4.0", []), ("variant-values", "bar", "@2.0", [1]), ("variant-values", "bar", "@3.0", [1]), ("variant-values", "bar", "@4.0", []), # now with a global override ("variant-values-override", "bar", "", [0]), ("variant-values-override", "bar", "@1.0", [0]), ("variant-values-override", "bar", "@2.0", [0]), ("variant-values-override", "bar", "@3.0", [0]), ("variant-values-override", "bar", "@4.0", [0]), ("variant-values-override", "baz", "", [0]), ("variant-values-override", "baz", "@2.0", [0]), ("variant-values-override", "baz", "@3.0", [0]), ("variant-values-override", "baz", "@4.0", [0]), ], ) def test_prevalidate_variant_value(mock_packages, pkg_name, value, spec, def_ids): pkg = spack.repo.PATH.get_pkg_class(pkg_name) all_defs = [vdef for _, vdef in pkg.variant_definitions("v")] valid_defs = spack.variant.prevalidate_variant_value( pkg, SingleValuedVariant("v", value), spack.spec.Spec(spec) ) assert len(valid_defs) == len(def_ids) for vdef, i in zip(valid_defs, def_ids): assert vdef is all_defs[i] @pytest.mark.parametrize( "pkg_name,value,spec", [ ("variant-values", "baz", ""), ("variant-values", "bar", "@1.0"), ("variant-values", "bar", "@4.0"), ("variant-values", "baz", "@3.0"), ("variant-values", "baz", "@4.0"), # and with override ("variant-values-override", "foo", ""), ("variant-values-override", "foo", "@1.0"), ("variant-values-override", "foo", "@2.0"), ("variant-values-override", "foo", "@3.0"), ("variant-values-override", "foo", "@4.0"), ], ) def test_strict_invalid_variant_values(mock_packages, pkg_name, value, spec): pkg = spack.repo.PATH.get_pkg_class(pkg_name) with pytest.raises(spack.variant.InvalidVariantValueError): spack.variant.prevalidate_variant_value( pkg, SingleValuedVariant("v", value), spack.spec.Spec(spec), strict=True ) @pytest.mark.parametrize( "pkg_name,spec,satisfies,def_id", [ ("variant-values", "@1.0", "v=foo", 0), ("variant-values", "@2.0", "v=bar", 1), ("variant-values", "@3.0", "v=bar", 1), ("variant-values-override", "@1.0", "v=baz", 0), ("variant-values-override", "@2.0", "v=baz", 0), ("variant-values-override", "@3.0", "v=baz", 0), ], ) def test_concretize_variant_default_with_multiple_defs( mock_packages, config, pkg_name, spec, satisfies, def_id ): pkg = spack.repo.PATH.get_pkg_class(pkg_name) pkg_defs = [vdef for _, vdef in pkg.variant_definitions("v")] spec = spack.concretize.concretize_one(f"{pkg_name}{spec}") assert spec.satisfies(satisfies) assert spec.package.get_variant("v") is pkg_defs[def_id] @pytest.mark.parametrize( "spec,variant_name,narrowed_type", [ # dev_path is a special case ("foo dev_path=/path/to/source", "dev_path", spack.variant.VariantType.SINGLE), # reserved name: won't be touched ("foo patches=2349dc44", "patches", spack.variant.VariantType.MULTI), # simple case -- one definition applies ("variant-values@1.0 v=foo", "v", spack.variant.VariantType.SINGLE), # simple, but with bool valued variant ("pkg-a bvv=true", "bvv", spack.variant.VariantType.BOOL), # takes the second definition, which overrides the single-valued one ("variant-values@2.0 v=bar", "v", spack.variant.VariantType.MULTI), ], ) def test_substitute_abstract_variants_narrowing(mock_packages, spec, variant_name, narrowed_type): spec = Spec(spec) spack.spec.substitute_abstract_variants(spec) assert spec.variants[variant_name].type == narrowed_type def test_substitute_abstract_variants_failure(mock_packages): with pytest.raises(spack.spec.InvalidVariantForSpecError): # variant doesn't exist at version spack.spec.substitute_abstract_variants(Spec("variant-values@4.0 v=bar")) def test_abstract_variant_satisfies_abstract_abstract(): # rhs should be a subset of lhs assert Spec("foo=bar").satisfies("foo=bar") assert Spec("foo=bar,baz").satisfies("foo=bar") assert Spec("foo=bar,baz").satisfies("foo=bar,baz") assert not Spec("foo=bar").satisfies("foo=baz") assert not Spec("foo=bar").satisfies("foo=bar,baz") assert Spec("foo=bar").satisfies("foo=*") # rhs empty set assert Spec("foo=*").satisfies("foo=*") # lhs and rhs empty set assert not Spec("foo=*").satisfies("foo=bar") # lhs empty set, rhs not def test_abstract_variant_satisfies_concrete_abstract(): # rhs should be a subset of lhs assert Spec("foo:=bar").satisfies("foo=bar") assert Spec("foo:=bar,baz").satisfies("foo=bar") assert Spec("foo:=bar,baz").satisfies("foo=bar,baz") assert not Spec("foo:=bar").satisfies("foo=baz") assert not Spec("foo:=bar").satisfies("foo=bar,baz") assert Spec("foo:=bar").satisfies("foo=*") # rhs empty set def test_abstract_variant_satisfies_abstract_concrete(): # always false since values can be added to the lhs assert not Spec("foo=bar").satisfies("foo:=bar") assert not Spec("foo=bar,baz").satisfies("foo:=bar") assert not Spec("foo=bar,baz").satisfies("foo:=bar,baz") assert not Spec("foo=bar").satisfies("foo:=baz") assert not Spec("foo=bar").satisfies("foo:=bar,baz") assert not Spec("foo=*").satisfies("foo:=bar") # lhs empty set def test_abstract_variant_satisfies_concrete_concrete(): # concrete values only satisfy each other when equal assert Spec("foo:=bar").satisfies("foo:=bar") assert not Spec("foo:=bar,baz").satisfies("foo:=bar") assert not Spec("foo:=bar").satisfies("foo:=bar,baz") assert Spec("foo:=bar,baz").satisfies("foo:=bar,baz") def test_abstract_variant_intersects_abstract_abstract(): # always true since the union of values satisfies both assert Spec("foo=bar").intersects("foo=bar") assert Spec("foo=bar,baz").intersects("foo=bar") assert Spec("foo=bar,baz").intersects("foo=bar,baz") assert Spec("foo=bar").intersects("foo=baz") assert Spec("foo=bar").intersects("foo=bar,baz") assert Spec("foo=bar").intersects("foo=*") # rhs empty set assert Spec("foo=*").intersects("foo=*") # lhs and rhs empty set assert Spec("foo=*").intersects("foo=bar") # lhs empty set, rhs not def test_abstract_variant_intersects_concrete_abstract(): assert Spec("foo:=bar").intersects("foo=bar") assert Spec("foo:=bar,baz").intersects("foo=bar") assert Spec("foo:=bar,baz").intersects("foo=bar,baz") assert not Spec("foo:=bar").intersects("foo=baz") # rhs has at least baz, lhs has not assert not Spec("foo:=bar").intersects("foo=bar,baz") # rhs has at least baz, lhs has not assert Spec("foo:=bar").intersects("foo=*") # rhs empty set def test_abstract_variant_intersects_abstract_concrete(): assert Spec("foo=bar").intersects("foo:=bar") assert not Spec("foo=bar,baz").intersects("foo:=bar") # lhs has at least baz, rhs has not assert Spec("foo=bar,baz").intersects("foo:=bar,baz") assert not Spec("foo=bar").intersects("foo:=baz") # lhs has at least bar, rhs has not assert Spec("foo=bar").intersects("foo:=bar,baz") assert Spec("foo=*").intersects("foo:=bar") # lhs empty set def test_abstract_variant_intersects_concrete_concrete(): # concrete values only intersect each other when equal assert Spec("foo:=bar").intersects("foo:=bar") assert not Spec("foo:=bar,baz").intersects("foo:=bar") assert not Spec("foo:=bar").intersects("foo:=bar,baz") assert Spec("foo:=bar,baz").intersects("foo:=bar,baz") def test_abstract_variant_constrain_abstract_abstract(): s1 = Spec("foo=bar") s2 = Spec("foo=*") assert s1.constrain("foo=baz") assert s1 == Spec("foo=bar,baz") assert s2.constrain("foo=baz") assert s2 == Spec("foo=baz") def test_abstract_variant_constrain_abstract_concrete_fail(): with pytest.raises(UnsatisfiableVariantSpecError): Spec("foo=bar").constrain("foo:=baz") def test_abstract_variant_constrain_abstract_concrete_ok(): s1 = Spec("foo=bar") s2 = Spec("foo=*") assert s1.constrain("foo:=bar") # the change is concreteness assert s1 == Spec("foo:=bar") assert s2.constrain("foo:=bar") assert s2 == Spec("foo:=bar") def test_abstract_variant_constrain_concrete_concrete_fail(): with pytest.raises(UnsatisfiableVariantSpecError): Spec("foo:=bar").constrain("foo:=bar,baz") def test_abstract_variant_constrain_concrete_concrete_ok(): s = Spec("foo:=bar") assert not s.constrain("foo:=bar") # no change def test_abstract_variant_constrain_concrete_abstract_fail(): s = Spec("foo:=bar") with pytest.raises(UnsatisfiableVariantSpecError): s.constrain("foo=baz") def test_abstract_variant_constrain_concrete_abstract_ok(): s = Spec("foo:=bar,baz") assert not s.constrain("foo=bar") # no change in value or concreteness assert not s.constrain("foo=*") def test_patches_variant(): """patches=x,y,z is a variant with special satisfies behavior when the rhs is abstract; it allows string prefix matching of the lhs.""" assert Spec("patches:=abcdef").satisfies("patches=ab") assert Spec("patches:=abcdef").satisfies("patches=abcdef") assert not Spec("patches:=abcdef").satisfies("patches=xyz") assert Spec("patches:=abcdef,xyz").satisfies("patches=xyz") assert not Spec("patches:=abcdef").satisfies("patches=abcdefghi") # but when the rhs is concrete, it must match exactly assert Spec("patches:=abcdef").satisfies("patches:=abcdef") assert not Spec("patches:=abcdef").satisfies("patches:=ab") assert not Spec("patches:=abcdef,xyz").satisfies("patches:=abc,xyz") assert not Spec("patches:=abcdef").satisfies("patches:=abcdefghi") def test_constrain_narrowing(): s = Spec("foo=*") assert s.variants["foo"].type == spack.variant.VariantType.MULTI assert not s.variants["foo"].concrete s.constrain("+foo") assert s.variants["foo"].type == spack.variant.VariantType.BOOL assert s.variants["foo"].concrete
TestVariantMapTest
python
huggingface__transformers
src/transformers/models/roc_bert/modeling_roc_bert.py
{ "start": 69020, "end": 72287 }
class ____(RoCBertPreTrainedModel): # Copied from transformers.models.bert.modeling_bert.BertForTokenClassification.__init__ with Bert->RoCBert,bert->roc_bert def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.roc_bert = RoCBertModel(config, add_pooling_layer=False) classifier_dropout = ( config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob ) self.dropout = nn.Dropout(classifier_dropout) self.classifier = nn.Linear(config.hidden_size, config.num_labels) # Initialize weights and apply final processing self.post_init() @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.Tensor] = None, input_shape_ids: Optional[torch.Tensor] = None, input_pronunciation_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, token_type_ids: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, inputs_embeds: Optional[torch.Tensor] = None, labels: Optional[torch.Tensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, TokenClassifierOutput]: r""" input_shape_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the shape vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input_shape_ids) input_pronunciation_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the pronunciation vocabulary. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input_pronunciation_ids) labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. """ outputs = self.roc_bert( input_ids, input_shape_ids=input_shape_ids, input_pronunciation_ids=input_pronunciation_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, inputs_embeds=inputs_embeds, return_dict=True, **kwargs, ) sequence_output = outputs[0] sequence_output = self.dropout(sequence_output) logits = self.classifier(sequence_output) loss = None if labels is not None: loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) return TokenClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) @auto_docstring
RoCBertForTokenClassification
python
python-openxml__python-docx
tests/opc/unitdata/rels.py
{ "start": 233, "end": 614 }
class ____: """ Provides common behavior for all data builders. """ @property def element(self): """Return element based on XML generated by builder""" return parse_xml(self.xml) def with_indent(self, indent): """Add integer `indent` spaces at beginning of element XML""" self._indent = indent return self
BaseBuilder
python
jina-ai__jina
tests/integration/reduce/test_reduce.py
{ "start": 3325, "end": 3479 }
class ____(Executor): @requests def endpoint(self, docs: DocumentArray, **kwargs): for doc in docs: doc.text = 'exec1'
Executor1
python
python-openxml__python-docx
src/docx/text/tabstops.py
{ "start": 2445, "end": 3896 }
class ____(ElementProxy): """An individual tab stop applying to a paragraph or style. Accessed using list semantics on its containing |TabStops| object. """ def __init__(self, element): super(TabStop, self).__init__(element, None) self._tab = element @property def alignment(self): """A member of :ref:`WdTabAlignment` specifying the alignment setting for this tab stop. Read/write. """ return self._tab.val @alignment.setter def alignment(self, value): self._tab.val = value @property def leader(self): """A member of :ref:`WdTabLeader` specifying a repeating character used as a "leader", filling in the space spanned by this tab. Assigning |None| produces the same result as assigning `WD_TAB_LEADER.SPACES`. Read/write. """ return self._tab.leader @leader.setter def leader(self, value): self._tab.leader = value @property def position(self): """A |Length| object representing the distance of this tab stop from the inside edge of the paragraph. May be positive or negative. Read/write. """ return self._tab.pos @position.setter def position(self, value): tab = self._tab tabs = tab.getparent() self._tab = tabs.insert_tab_in_order(value, tab.val, tab.leader) tabs.remove(tab)
TabStop
python
getsentry__sentry
tests/sentry/auth/test_idpmigration.py
{ "start": 440, "end": 3335 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.user = self.create_user() self.login_as(self.user) self.email = "test@example.com" self.org = self.create_organization() self.provider = AuthProvider.objects.create(organization_id=self.org.id, provider="dummy") IDENTITY_ID = "drgUQCLzOyfHxmTyVs0G" def test_send_one_time_account_confirm_link(self) -> None: with assume_test_silo_mode(SiloMode.REGION): om = OrganizationMember.objects.create(organization=self.org, user_id=self.user.id) link = idpmigration.send_one_time_account_confirm_link( self.user, self.org, self.provider, self.email, self.IDENTITY_ID ) assert re.match(r"auth:one-time-key:\w{32}", link.verification_key) value = json.loads(cast(str, idpmigration._get_redis_client().get(link.verification_key))) assert value["user_id"] == self.user.id assert value["email"] == self.email assert value["member_id"] == om.id assert value["organization_id"] == self.org.id assert value["identity_id"] == self.IDENTITY_ID assert value["provider"] == "dummy" def test_send_without_org_membership(self) -> None: link = idpmigration.send_one_time_account_confirm_link( self.user, self.org, self.provider, self.email, self.IDENTITY_ID ) value = json.loads(cast(str, idpmigration._get_redis_client().get(link.verification_key))) assert value["user_id"] == self.user.id assert value["email"] == self.email assert value["member_id"] is None assert value["organization_id"] == self.org.id assert value["identity_id"] == self.IDENTITY_ID assert value["provider"] == "dummy" def test_verify_account(self) -> None: link = idpmigration.send_one_time_account_confirm_link( self.user, self.org, self.provider, self.email, self.IDENTITY_ID ) path = reverse( "sentry-idp-email-verification", args=[link.verification_code], ) response = self.client.get(path) assert self.client.session[idpmigration.SSO_VERIFICATION_KEY] == link.verification_code assert response.status_code == 200 assert response.templates[0].name == "sentry/idp_account_verified.html" def test_verify_account_wrong_key(self) -> None: idpmigration.send_one_time_account_confirm_link( self.user, self.org, self.provider, self.email, self.IDENTITY_ID ) path = reverse( "sentry-idp-email-verification", args=["d14Ja9N2eQfPfVzcydS6vzcxWecZJG2z2"], ) response = self.client.get(path) assert response.status_code == 200 assert response.templates[0].name == "sentry/idp_account_not_verified.html"
IDPMigrationTests
python
huggingface__transformers
src/transformers/modeling_outputs.py
{ "start": 79608, "end": 81221 }
class ____(ModelOutput): """ Base class for outputs of image classification models. Args: loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided): Classification (or regression if config.num_labels==1) loss. logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`): Classification (or regression if config.num_labels==1) scores (before SoftMax). hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`): Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each stage) of shape `(batch_size, sequence_length, hidden_size)`. Hidden-states (also called feature maps) of the model at the output of each stage. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, patch_size, sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. """ loss: Optional[torch.FloatTensor] = None logits: Optional[torch.FloatTensor] = None hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None attentions: Optional[tuple[torch.FloatTensor, ...]] = None @dataclass
ImageClassifierOutput
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 18129, "end": 18437 }
class ____(MetaFeature): def _calculate(self, X, y, logger, feat_type): values = [val for val in helper_functions.get_value("NumSymbols") if val > 0] std = np.nanstd(values) return std if np.isfinite(std) else 0 @metafeatures.define("SymbolsSum", dependency="NumSymbols")
SymbolsSTD
python
doocs__leetcode
solution/2700-2799/2767.Partition String Into Minimum Beautiful Substrings/Solution.py
{ "start": 0, "end": 619 }
class ____: def minimumBeautifulSubstrings(self, s: str) -> int: @cache def dfs(i: int) -> int: if i >= n: return 0 if s[i] == "0": return inf x = 0 ans = inf for j in range(i, n): x = x << 1 | int(s[j]) if x in ss: ans = min(ans, 1 + dfs(j + 1)) return ans n = len(s) x = 1 ss = {x} for i in range(n): x *= 5 ss.add(x) ans = dfs(0) return -1 if ans == inf else ans
Solution
python
ray-project__ray
python/ray/serve/_private/request_router/common.py
{ "start": 756, "end": 1812 }
class ____: """A request that is pending execution by a replica.""" args: List[Any] """Positional arguments for the request.""" kwargs: Dict[Any, Any] """Keyword arguments for the request.""" metadata: RequestMetadata """Metadata for the request, including request ID and whether it's streaming.""" created_at: float = field(default_factory=lambda: time.time()) """Timestamp when the request was created.""" future: asyncio.Future = field(default_factory=lambda: asyncio.Future()) """An asyncio Future that will be set when the request is routed.""" routing_context: RequestRoutingContext = field( default_factory=RequestRoutingContext ) """Context for request routing, used to track routing attempts and backoff.""" resolved: bool = False """Whether the arguments have been resolved.""" def reset_future(self): """Reset the `asyncio.Future`, must be called if this request is re-used.""" self.future = asyncio.Future() @dataclass(frozen=True)
PendingRequest
python
scrapy__scrapy
scrapy/exporters.py
{ "start": 8234, "end": 10964 }
class ____(BaseItemExporter): def __init__( self, file: BytesIO, include_headers_line: bool = True, join_multivalued: str = ",", errors: str | None = None, **kwargs: Any, ): super().__init__(dont_fail=True, **kwargs) if not self.encoding: self.encoding = "utf-8" self.include_headers_line = include_headers_line self.stream = TextIOWrapper( file, line_buffering=False, write_through=True, encoding=self.encoding, newline="", # Windows needs this https://github.com/scrapy/scrapy/issues/3034 errors=errors, ) self.csv_writer = csv.writer(self.stream, **self._kwargs) self._headers_not_written = True self._join_multivalued = join_multivalued def serialize_field( self, field: Mapping[str, Any] | Field, name: str, value: Any ) -> Any: serializer: Callable[[Any], Any] = field.get("serializer", self._join_if_needed) return serializer(value) def _join_if_needed(self, value: Any) -> Any: if isinstance(value, (list, tuple)): try: return self._join_multivalued.join(value) except TypeError: # list in value may not contain strings pass return value def export_item(self, item: Any) -> None: if self._headers_not_written: self._headers_not_written = False self._write_headers_and_set_fields_to_export(item) fields = self._get_serialized_fields(item, default_value="", include_empty=True) values = list(self._build_row(x for _, x in fields)) self.csv_writer.writerow(values) def finish_exporting(self) -> None: self.stream.detach() # Avoid closing the wrapped file. def _build_row(self, values: Iterable[Any]) -> Iterable[Any]: for s in values: try: yield to_unicode(s, self.encoding) except TypeError: yield s def _write_headers_and_set_fields_to_export(self, item: Any) -> None: if self.include_headers_line: if not self.fields_to_export: # use declared field names, or keys if the item is a dict self.fields_to_export = ItemAdapter(item).field_names() fields: Iterable[str] if isinstance(self.fields_to_export, Mapping): fields = self.fields_to_export.values() else: assert self.fields_to_export fields = self.fields_to_export row = list(self._build_row(fields)) self.csv_writer.writerow(row)
CsvItemExporter
python
automl__auto-sklearn
test/test_pipeline/components/regression/test_extra_trees.py
{ "start": 166, "end": 998 }
class ____(BaseRegressionComponentTest): __test__ = True res = dict() res["default_boston"] = 0.8539264243687228 res["boston_n_calls"] = 9 res["default_boston_iterative"] = res["default_boston"] res["default_boston_sparse"] = 0.411211701806908 res["default_boston_iterative_sparse"] = res["default_boston_sparse"] res["default_diabetes"] = 0.3885150255877827 res["diabetes_n_calls"] = 9 res["default_diabetes_iterative"] = res["default_diabetes"] res["default_diabetes_sparse"] = 0.2422804139169642 res["default_diabetes_iterative_sparse"] = res["default_diabetes_sparse"] sk_mod = sklearn.ensemble.ExtraTreesRegressor module = ExtraTreesRegressor step_hyperparameter = { "name": "n_estimators", "value": module.get_max_iter(), }
ExtraTreesComponentTest
python
ApeWorX__ape
src/ape/cli/choices.py
{ "start": 5522, "end": 10796 }
class ____(PromptChoice): """ Prompts the user to select an alias from their accounts. Useful for adhoc scripts to lessen the need to hard-code aliases. """ DEFAULT_PROMPT = "Select an account" def __init__( self, key: _ACCOUNT_TYPE_FILTER = None, prompt_message: Optional[str] = None, name: str = "account", ): # NOTE: we purposely skip the constructor of `PromptChoice` self._key_filter = key self._prompt_message = prompt_message or self.DEFAULT_PROMPT self.name = name @cached_property def choices(self) -> Sequence[str]: # type: ignore[override] from ape.types.basic import _LazySequence return _LazySequence(self._choices_iterator) def convert( self, value: Any, param: Optional[Parameter], ctx: Optional[Context] ) -> Optional["AccountAPI"]: if value is None: return None if isinstance(value, str) and value.isnumeric(): alias = super().convert(value, param, ctx) else: alias = value from ape.utils.basemodel import ManagerAccessMixin as access accounts = access.account_manager if isinstance(alias, str) and alias.upper().startswith("TEST::"): idx_str = alias.upper().replace("TEST::", "") if not idx_str.isnumeric(): if alias in accounts.aliases: # Was actually a similar-alias. return accounts.load(alias) self.fail(f"Cannot reference test account by '{value}'.", param=param) account_idx = int(idx_str) if 0 <= account_idx < len(accounts.test_accounts): return accounts.test_accounts[int(idx_str)] self.fail(f"Index '{idx_str}' is not valid.", param=param) elif alias and alias in accounts.aliases: return accounts.load(alias) self.fail(f"Account with alias '{alias}' not found.", param=param) def print_choices(self): choices = dict(enumerate(self.choices, 0)) did_print = False for idx, choice in choices.items(): if not choice.startswith("TEST::"): click.echo(f"{idx}. {choice}") did_print = True from ape.utils.basemodel import ManagerAccessMixin as access accounts = access.account_manager len_test_accounts = len(accounts.test_accounts) - 1 if len_test_accounts > 0: msg = "'TEST::account_idx', where `account_idx` is in [0..{len_test_accounts}]\n" if did_print: msg = f"Or {msg}" click.echo(msg) elif did_print: click.echo() @property def _choices_iterator(self) -> Iterator[str]: # NOTE: Includes test accounts unless filtered out by key. for account in _get_accounts(key=self._key_filter): if account and (alias := account.alias): yield alias def select_account(self) -> "AccountAPI": """ Returns the selected account. Returns: :class:`~ape.api.accounts.AccountAPI` """ from ape.utils.basemodel import ManagerAccessMixin as access accounts = access.account_manager if not self.choices or len(self.choices) == 0: raise AccountsError("No accounts found.") elif len(self.choices) == 1 and self.choices[0].startswith("TEST::"): return accounts.test_accounts[int(self.choices[0].replace("TEST::", ""))] elif len(self.choices) == 1: return accounts.load(self.choices[0]) self.print_choices() return click.prompt(self._prompt_message, type=self) def fail_from_invalid_choice(self, param): return self.fail("Invalid choice. Type the number or the alias.", param=param) _NETWORK_FILTER = Optional[Union[list[str], str]] _NONE_NETWORK = "__NONE_NETWORK__" def get_networks( ecosystem: _NETWORK_FILTER = None, network: _NETWORK_FILTER = None, provider: _NETWORK_FILTER = None, ) -> Sequence: # NOTE: Use str-keys and lru_cache. return _get_networks_sequence_from_cache( _network_filter_to_key(ecosystem), _network_filter_to_key(network), _network_filter_to_key(provider), ) @cache def _get_networks_sequence_from_cache(ecosystem_key: str, network_key: str, provider_key: str): networks = import_module("ape.utils.basemodel").ManagerAccessMixin.network_manager module = import_module("ape.types.basic") return module._LazySequence( networks.get_network_choices( ecosystem_filter=_key_to_network_filter(ecosystem_key), network_filter=_key_to_network_filter(network_key), provider_filter=_key_to_network_filter(provider_key), ) ) def _network_filter_to_key(filter_: _NETWORK_FILTER) -> str: if filter_ is None: return "__none__" elif isinstance(filter_, list): return ",".join(filter_) return filter_ def _key_to_network_filter(key: str) -> _NETWORK_FILTER: if key == "__none__": return None elif "," in key: return [n.strip() for n in key.split(",")] return key
AccountAliasPromptChoice
python
walkccc__LeetCode
solutions/1329. Sort the Matrix Diagonally/1329.py
{ "start": 0, "end": 417 }
class ____: def diagonalSort(self, mat: list[list[int]]) -> list[list[int]]: m = len(mat) n = len(mat[0]) count = collections.defaultdict(list) for i in range(m): for j in range(n): count[i - j].append(mat[i][j]) for value in count.values(): value.sort(reverse=1) for i in range(m): for j in range(n): mat[i][j] = count[i - j].pop() return mat
Solution
python
walkccc__LeetCode
solutions/3398. Smallest Substring With Identical Characters I/3398.py
{ "start": 0, "end": 721 }
class ____: def minLength(self, s: str, numOps: int) -> int: def getMinOps(k: int) -> int: """ Returns the minimum number of operations needed to make all groups of identical characters of length k or less. """ if k == 1: res = sum(1 for i, c in enumerate(s) if int(c) == i % 2) return min(res, len(s) - res) res = 0 runningLen = 1 for a, b in itertools.pairwise(s): if a == b: runningLen += 1 else: res += runningLen // (k + 1) runningLen = 1 return res + runningLen // (k + 1) return bisect_left(range(1, len(s) + 1), True, key=lambda m: getMinOps(m) <= numOps)
Solution
python
Netflix__metaflow
metaflow/plugins/pypi/pip.py
{ "start": 400, "end": 709 }
class ____(MetaflowException): headline = "Pip ran into an error while setting up environment" def __init__(self, error): if isinstance(error, (list,)): error = "\n".join(error) msg = "{error}".format(error=error) super(PipException, self).__init__(msg)
PipException
python
scipy__scipy
scipy/interpolate/tests/test_bsplines.py
{ "start": 143283, "end": 146902 }
class ____: def _get_xyk(self, m=10, k=3, xp=np): x = xp.arange(m, dtype=xp.float64) * xp.pi / m y = [xp.sin(x), xp.cos(x)] return x, y, k @pytest.mark.parametrize('s', [0, 0.1, 1e-3, 1e-5]) def test_simple_vs_splprep(self, s): # Check/document the interface vs splPrep # The four values of `s` are to probe all code paths and shortcuts m, k = 10, 3 x = np.arange(m) * np.pi / m y = [np.sin(x), np.cos(x)] # the number of knots depends on `s` (this is by construction) num_knots = {0: 14, 0.1: 8, 1e-3: 8 + 1, 1e-5: 8 + 2} # construct the splines (t, c, k), u_ = splprep(y, s=s) spl, u = make_splprep(y, s=s) # parameters xp_assert_close(u, u_, atol=1e-15) # knots xp_assert_close(spl.t, t, atol=1e-15) assert len(t) == num_knots[s] # coefficients: note the transpose cc = np.asarray(c).T xp_assert_close(spl.c, cc, atol=1e-15) # values: note axis=1 xp_assert_close(spl(u), BSpline(t, c, k, axis=1)(u), atol=1e-15) @pytest.mark.parametrize('s', [0, 0.1, 1e-3, 1e-5]) def test_array_not_list(self, s): # the argument of splPrep is either a list of arrays or a 2D array (sigh) _, y, _ = self._get_xyk() assert isinstance(y, list) assert np.shape(y)[0] == 2 # assert the behavior of FITPACK's splrep tck, u = splprep(y, s=s) tck_a, u_a = splprep(np.asarray(y), s=s) xp_assert_close(u, u_a, atol=s) xp_assert_close(tck[0], tck_a[0], atol=1e-15) assert len(tck[1]) == len(tck_a[1]) xp_assert_close(tck[1], tck_a[1], atol=1e-15) assert tck[2] == tck_a[2] assert np.shape(splev(u, tck)) == np.shape(y) spl, u = make_splprep(y, s=s) xp_assert_close(u, u_a, atol=1e-15) xp_assert_close(spl.t, tck_a[0], atol=1e-15) xp_assert_close(spl.c.T, tck_a[1], atol=1e-15) assert spl.k == tck_a[2] assert spl(u).shape == np.shape(y) spl, u = make_splprep(np.asarray(y), s=s) xp_assert_close(u, u_a, atol=1e-15) xp_assert_close(spl.t, tck_a[0], atol=1e-15) xp_assert_close(spl.c.T, tck_a[1], atol=1e-15) assert spl.k == tck_a[2] assert spl(u).shape == np.shape(y) with assert_raises(ValueError): make_splprep(np.asarray(y).T, s=s) def test_default_s_is_zero(self, xp): x, y, k = self._get_xyk(m=10, xp=xp) spl, u = make_splprep(y) xp_assert_close(spl(u), xp.stack(y), atol=1e-15) def test_s_zero_vs_near_zero(self, xp): # s=0 and s \approx 0 are consistent x, y, k = self._get_xyk(m=10, xp=xp) spl_i, u_i = make_splprep(y, s=0) spl_n, u_n = make_splprep(y, s=1e-15) xp_assert_close(u_i, u_n, atol=1e-15) xp_assert_close(spl_i(u_i), xp.stack(y), atol=1e-15) xp_assert_close(spl_n(u_n), xp.stack(y), atol=1e-7) assert spl_i.axis == spl_n.axis assert spl_i.c.shape == spl_n.c.shape def test_1D(self): x = np.arange(8, dtype=float) with assert_raises(ValueError): splprep(x) with assert_raises(ValueError): make_splprep(x, s=0) with assert_raises(ValueError): make_splprep(x, s=0.1) tck, u_ = splprep([x], s=1e-5) spl, u = make_splprep([x], s=1e-5) assert spl(u).shape == (1, 8) xp_assert_close(spl(u), [x], atol=1e-15) @make_xp_test_case(make_splprep)
TestMakeSplprep
python
scipy__scipy
scipy/stats/tests/test_hypotests.py
{ "start": 1024, "end": 3959 }
class ____: @pytest.mark.parametrize('dtype', [None, 'float32', 'float64']) def test_statistic_1(self, dtype, xp): # first example in Goerg & Kaiser, also in original paper of # Epps & Singleton. Note: values do not match exactly, the # value of the interquartile range varies depending on how # quantiles are computed if is_numpy(xp) and xp.__version__ < "2.0" and dtype == 'float32': pytest.skip("Pre-NEP 50 doesn't respect dtypes") dtype = xp_default_dtype(xp) if dtype is None else getattr(xp, dtype) x = xp.asarray([-0.35, 2.55, 1.73, 0.73, 0.35, 2.69, 0.46, -0.94, -0.37, 12.07], dtype=dtype) y = xp.asarray([-1.15, -0.15, 2.48, 3.25, 3.71, 4.29, 5.00, 7.74, 8.38, 8.60], dtype=dtype) w, p = epps_singleton_2samp(x, y) xp_assert_close(w, xp.asarray(15.14, dtype=dtype), atol=0.03) xp_assert_close(p, xp.asarray(0.00442, dtype=dtype), atol=0.0001) def test_statistic_2(self, xp): # second example in Goerg & Kaiser, again not a perfect match x = xp.asarray([0, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 5, 5, 5, 5, 6, 10, 10, 10, 10]) y = xp.asarray([10, 4, 0, 5, 10, 10, 0, 5, 6, 7, 10, 3, 1, 7, 0, 8, 1, 5, 8, 10]) w, p = epps_singleton_2samp(x, y) xp_assert_close(w, xp.asarray(8.900), atol=1e-3) xp_assert_close(p, xp.asarray(0.06364), atol=5e-5) def test_epps_singleton_array_like(self): # only relevant for NumPy x, y = np.arange(30), np.arange(28) w1, p1 = epps_singleton_2samp(list(x), list(y)) w2, p2 = epps_singleton_2samp(tuple(x), tuple(y)) w3, p3 = epps_singleton_2samp(x, y) assert_(w1 == w2 == w3) assert_(p1 == p2 == p3) def test_epps_singleton_size(self, xp): # warns if sample contains fewer than 5 elements x, y = xp.asarray([1, 2, 3, 4]), xp.arange(10) with eager_warns(SmallSampleWarning, match=too_small_1d_not_omit, xp=xp): res = epps_singleton_2samp(x, y) xp_assert_equal(res.statistic, xp.asarray(xp.nan)) xp_assert_equal(res.pvalue, xp.asarray(xp.nan)) def test_epps_singleton_nonfinite(self, xp): rng = np.random.default_rng(83249872384543) x = rng.random(size=(10, 11)) y = rng.random(size=(10, 12)) i = np.asarray([1, 4, 9]) # arbitrary rows w_ref, p_ref = epps_singleton_2samp(x, y, axis=-1) w_ref[i] = np.nan p_ref[i] = np.nan x[i[0], 0] = np.nan x[i[1], 1] = np.inf y[i[2], 2] = -np.inf x, y = xp.asarray(x), xp.asarray(y) w_res, p_res = epps_singleton_2samp(x, y, axis=-1) xp_assert_close(w_res, xp.asarray(w_ref)) xp_assert_close(p_res, xp.asarray(p_ref)) @make_xp_test_case(stats.cramervonmises)
TestEppsSingleton
python
davidhalter__jedi
jedi/inference/context.py
{ "start": 10326, "end": 10640 }
class ____(TreeContextMixin, ValueContext): def get_filters(self, until_position=None, origin_scope=None): yield ParserTreeFilter( self.inference_state, parent_context=self, until_position=until_position, origin_scope=origin_scope )
FunctionContext
python
django-extensions__django-extensions
django_extensions/management/jobs.py
{ "start": 456, "end": 519 }
class ____(BaseJob): when = "quarter_hourly"
QuarterHourlyJob
python
cherrypy__cherrypy
cherrypy/__init__.py
{ "start": 3646, "end": 5347 }
class ____(object): """Handle signals from other processes. Based on the configured platform handlers above. """ def __init__(self, bus): self.bus = bus def subscribe(self): """Add the handlers based on the platform.""" if hasattr(self.bus, 'signal_handler'): self.bus.signal_handler.subscribe() if hasattr(self.bus, 'console_control_handler'): self.bus.console_control_handler.subscribe() engine.signals = _HandleSignalsPlugin(engine) server = _cpserver.Server() server.subscribe() def quickstart(root=None, script_name='', config=None): """Mount the given root, start the builtin server (and engine), then block. root: an instance of a "controller class" (a collection of page handler methods) which represents the root of the application. script_name: a string containing the "mount point" of the application. This should start with a slash, and be the path portion of the URL at which to mount the given root. For example, if root.index() will handle requests to "http://www.example.com:8080/dept/app1/", then the script_name argument would be "/dept/app1". It MUST NOT end in a slash. If the script_name refers to the root of the URI, it MUST be an empty string (not "/"). config: a file or dict containing application config. If this contains a [global] section, those entries will be used in the global (site-wide) config. """ if config: _global_conf_alias.update(config) tree.mount(root, script_name, config) engine.signals.subscribe() engine.start() engine.block()
_HandleSignalsPlugin
python
fastai__fastai
fastai/collab.py
{ "start": 398, "end": 586 }
class ____(TabularPandas): "Instance of `TabularPandas` suitable for collaborative filtering (with no continuous variable)" with_cont=False # %% ../nbs/45_collab.ipynb 9
TabularCollab
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/dataplex.py
{ "start": 129095, "end": 133774 }
class ____(DataplexCatalogBaseOperator): """ Update an EntryType resource. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:DataplexCatalogUpdateEntryTypeOperator` :param project_id: Required. The ID of the Google Cloud project that the task belongs to. :param location: Required. The ID of the Google Cloud region that the task belongs to. :param update_mask: Optional. Names of fields whose values to overwrite on an entry group. If this parameter is absent or empty, all modifiable fields are overwritten. If such fields are non-required and omitted in the request body, their values are emptied. :param entry_type_id: Required. ID of the EntryType to update. :param entry_type_configuration: Required. The updated configuration body of the EntryType. For more details please see API documentation: https://cloud.google.com/dataplex/docs/reference/rest/v1/projects.locations.entryGroups#EntryGroup :param validate_only: Optional. The service validates the request without performing any mutations. :param retry: Optional. A retry object used to retry requests. If `None` is specified, requests will not be retried. :param timeout: Optional. The amount of time, in seconds, to wait for the request to complete. Note that if `retry` is specified, the timeout applies to each individual attempt. :param metadata: Optional. Additional metadata that is provided to the method. :param gcp_conn_id: Optional. The connection ID to use when fetching connection info. :param impersonation_chain: Optional. Service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). """ template_fields: Sequence[str] = tuple( {"entry_type_id", "entry_type_configuration", "update_mask"} | set(DataplexCatalogBaseOperator.template_fields) ) operator_extra_links = (DataplexCatalogEntryTypeLink(),) def __init__( self, entry_type_id: str, entry_type_configuration: dict | EntryType, update_mask: list[str] | FieldMask | None = None, validate_request: bool | None = False, *args, **kwargs, ) -> None: super().__init__(*args, **kwargs) self.entry_type_id = entry_type_id self.entry_type_configuration = entry_type_configuration self.update_mask = update_mask self.validate_request = validate_request @property def extra_links_params(self) -> dict[str, Any]: return { **super().extra_links_params, "entry_type_id": self.entry_type_id, } def execute(self, context: Context): DataplexCatalogEntryTypeLink.persist(context=context) if self.validate_request: self.log.info("Validating an Update Dataplex Catalog EntryType request.") else: self.log.info( "Updating Dataplex Catalog EntryType %s.", self.entry_type_id, ) try: operation = self.hook.update_entry_type( location=self.location, project_id=self.project_id, entry_type_id=self.entry_type_id, entry_type_configuration=self.entry_type_configuration, update_mask=self.update_mask, validate_only=self.validate_request, retry=self.retry, timeout=self.timeout, metadata=self.metadata, ) entry_type = self.hook.wait_for_operation(timeout=self.timeout, operation=operation) except NotFound as ex: self.log.info("Specified EntryType was not found.") raise AirflowException(ex) except Exception as exc: raise AirflowException(exc) else: result = EntryType.to_dict(entry_type) if not self.validate_request else None if not self.validate_request: self.log.info("EntryType %s was successfully updated.", self.entry_type_id) return result
DataplexCatalogUpdateEntryTypeOperator
python
django__django
django/core/serializers/json.py
{ "start": 450, "end": 1794 }
class ____(PythonSerializer): """Convert a queryset to JSON.""" internal_use_only = False def _init_options(self): self._current = None self.json_kwargs = self.options.copy() self.json_kwargs.pop("stream", None) self.json_kwargs.pop("fields", None) if self.options.get("indent"): # Prevent trailing spaces self.json_kwargs["separators"] = (",", ": ") self.json_kwargs.setdefault("cls", DjangoJSONEncoder) self.json_kwargs.setdefault("ensure_ascii", False) def start_serialization(self): self._init_options() self.stream.write("[") def end_serialization(self): if self.options.get("indent"): self.stream.write("\n") self.stream.write("]") self.stream.write("\n") def end_object(self, obj): # self._current has the field data indent = self.options.get("indent") if not self.first: self.stream.write(",") if not indent: self.stream.write(" ") if indent: self.stream.write("\n") json.dump(self.get_dump_object(obj), self.stream, **self.json_kwargs) self._current = None def getvalue(self): # Grandparent super return super(PythonSerializer, self).getvalue()
Serializer
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/inheritance.py
{ "start": 435, "end": 541 }
class ____(Base, AnotherBase): def inheritedmeth(self): # no docstring here pass
Derived
python
kamyu104__LeetCode-Solutions
Python/bricks-falling-when-hit.py
{ "start": 704, "end": 2254 }
class ____(object): def hitBricks(self, grid, hits): """ :type grid: List[List[int]] :type hits: List[List[int]] :rtype: List[int] """ def index(C, r, c): return r*C+c directions = [(0, -1), (0, 1), (-1, 0), (1, 0)] R, C = len(grid), len(grid[0]) hit_grid = [row[:] for row in grid] for i, j in hits: hit_grid[i][j] = 0 union_find = UnionFind(R*C) for r, row in enumerate(hit_grid): for c, val in enumerate(row): if not val: continue if r == 0: union_find.union_set(index(C, r, c), R*C) if r and hit_grid[r-1][c]: union_find.union_set(index(C, r, c), index(C, r-1, c)) if c and hit_grid[r][c-1]: union_find.union_set(index(C, r, c), index(C, r, c-1)) result = [] for r, c in reversed(hits): prev_roof = union_find.top() if grid[r][c] == 0: result.append(0) continue for d in directions: nr, nc = (r+d[0], c+d[1]) if 0 <= nr < R and 0 <= nc < C and hit_grid[nr][nc]: union_find.union_set(index(C, r, c), index(C, nr, nc)) if r == 0: union_find.union_set(index(C, r, c), R*C) hit_grid[r][c] = 1 result.append(max(0, union_find.top()-prev_roof-1)) return result[::-1]
Solution
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/transfers/imap_attachment_to_s3.py
{ "start": 1228, "end": 4584 }
class ____(BaseOperator): """ Transfers a mail attachment from a mail server into s3 bucket. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:ImapAttachmentToS3Operator` :param imap_attachment_name: The file name of the mail attachment that you want to transfer. :param s3_bucket: The targeted s3 bucket. This is the S3 bucket where the file will be downloaded. :param s3_key: The destination file name in the s3 bucket for the attachment. :param imap_check_regex: If set checks the `imap_attachment_name` for a regular expression. :param imap_mail_folder: The folder on the mail server to look for the attachment. :param imap_mail_filter: If set other than 'All' only specific mails will be checked. See :py:meth:`imaplib.IMAP4.search` for details. :param s3_overwrite: If set overwrites the s3 key if already exists. :param imap_conn_id: The reference to the connection details of the mail server. :param aws_conn_id: The Airflow connection used for AWS credentials. If this is None or empty then the default boto3 behaviour is used. If running Airflow in a distributed manner and aws_conn_id is None or empty, then default boto3 configuration would be used (and must be maintained on each worker node). """ template_fields: Sequence[str] = ("imap_attachment_name", "s3_key", "imap_mail_filter") def __init__( self, *, imap_attachment_name: str, s3_bucket: str, s3_key: str, imap_check_regex: bool = False, imap_mail_folder: str = "INBOX", imap_mail_filter: str = "All", s3_overwrite: bool = False, imap_conn_id: str = "imap_default", aws_conn_id: str | None = "aws_default", **kwargs, ) -> None: super().__init__(**kwargs) self.imap_attachment_name = imap_attachment_name self.s3_bucket = s3_bucket self.s3_key = s3_key self.imap_check_regex = imap_check_regex self.imap_mail_folder = imap_mail_folder self.imap_mail_filter = imap_mail_filter self.s3_overwrite = s3_overwrite self.imap_conn_id = imap_conn_id self.aws_conn_id = aws_conn_id def execute(self, context: Context) -> None: """ Execute the transfer from the email server (via imap) into s3. :param context: The context while executing. """ self.log.info( "Transferring mail attachment %s from mail server via imap to s3 key %s...", self.imap_attachment_name, self.s3_key, ) with ImapHook(imap_conn_id=self.imap_conn_id) as imap_hook: imap_mail_attachments = imap_hook.retrieve_mail_attachments( name=self.imap_attachment_name, check_regex=self.imap_check_regex, latest_only=True, mail_folder=self.imap_mail_folder, mail_filter=self.imap_mail_filter, ) s3_hook = S3Hook(aws_conn_id=self.aws_conn_id) s3_hook.load_bytes( bytes_data=imap_mail_attachments[0][1], bucket_name=self.s3_bucket, key=self.s3_key, replace=self.s3_overwrite, )
ImapAttachmentToS3Operator
python
pytest-dev__pytest
src/_pytest/outcomes.py
{ "start": 5015, "end": 10138 }
class ____: """Imperatively xfail an executing test or setup function with the given reason. This function should be called only during testing (setup, call or teardown). No other code is executed after using ``xfail()`` (it is implemented internally by raising an exception). :param reason: The message to show the user as reason for the xfail. .. note:: It is better to use the :ref:`pytest.mark.xfail ref` marker when possible to declare a test to be xfailed under certain conditions like known bugs or missing features. :raises pytest.xfail.Exception: The exception that is raised. """ Exception: ClassVar[type[XFailed]] = XFailed def __call__(self, reason: str = "") -> NoReturn: __tracebackhide__ = True raise XFailed(msg=reason) xfail: _XFail = _XFail() def importorskip( modname: str, minversion: str | None = None, reason: str | None = None, *, exc_type: type[ImportError] | None = None, ) -> Any: """Import and return the requested module ``modname``, or skip the current test if the module cannot be imported. :param modname: The name of the module to import. :param minversion: If given, the imported module's ``__version__`` attribute must be at least this minimal version, otherwise the test is still skipped. :param reason: If given, this reason is shown as the message when the module cannot be imported. :param exc_type: The exception that should be captured in order to skip modules. Must be :py:class:`ImportError` or a subclass. If the module can be imported but raises :class:`ImportError`, pytest will issue a warning to the user, as often users expect the module not to be found (which would raise :class:`ModuleNotFoundError` instead). This warning can be suppressed by passing ``exc_type=ImportError`` explicitly. See :ref:`import-or-skip-import-error` for details. :returns: The imported module. This should be assigned to its canonical name. :raises pytest.skip.Exception: If the module cannot be imported. Example:: docutils = pytest.importorskip("docutils") .. versionadded:: 8.2 The ``exc_type`` parameter. """ import warnings __tracebackhide__ = True compile(modname, "", "eval") # to catch syntaxerrors # Until pytest 9.1, we will warn the user if we catch ImportError (instead of ModuleNotFoundError), # as this might be hiding an installation/environment problem, which is not usually what is intended # when using importorskip() (#11523). # In 9.1, to keep the function signature compatible, we just change the code below to: # 1. Use `exc_type = ModuleNotFoundError` if `exc_type` is not given. # 2. Remove `warn_on_import` and the warning handling. if exc_type is None: exc_type = ImportError warn_on_import_error = True else: warn_on_import_error = False skipped: Skipped | None = None warning: Warning | None = None with warnings.catch_warnings(): # Make sure to ignore ImportWarnings that might happen because # of existing directories with the same name we're trying to # import but without a __init__.py file. warnings.simplefilter("ignore") try: importlib.import_module(modname) except exc_type as exc: # Do not raise or issue warnings inside the catch_warnings() block. if reason is None: reason = f"could not import {modname!r}: {exc}" skipped = Skipped(reason, allow_module_level=True) if warn_on_import_error and not isinstance(exc, ModuleNotFoundError): lines = [ "", f"Module '{modname}' was found, but when imported by pytest it raised:", f" {exc!r}", "In pytest 9.1 this warning will become an error by default.", "You can fix the underlying problem, or alternatively overwrite this behavior and silence this " "warning by passing exc_type=ImportError explicitly.", "See https://docs.pytest.org/en/stable/deprecations.html#pytest-importorskip-default-behavior-regarding-importerror", ] warning = PytestDeprecationWarning("\n".join(lines)) if warning: warnings.warn(warning, stacklevel=2) if skipped: raise skipped mod = sys.modules[modname] if minversion is None: return mod verattr = getattr(mod, "__version__", None) if minversion is not None: # Imported lazily to improve start-up time. from packaging.version import Version if verattr is None or Version(verattr) < Version(minversion): raise Skipped( f"module {modname!r} has __version__ {verattr!r}, required is: {minversion!r}", allow_module_level=True, ) return mod
_XFail
python
run-llama__llama_index
llama-index-instrumentation/tests/test_dispatcher.py
{ "start": 1137, "end": 1248 }
class ____(BaseEvent): @classmethod def class_name(cls): return "_TestStartEvent"
_TestStartEvent
python
django__django
tests/auth_tests/test_auth_backends.py
{ "start": 39007, "end": 40461 }
class ____(TestCase): """ Tests for changes in the settings.AUTHENTICATION_BACKENDS """ backend = "auth_tests.test_auth_backends.NewModelBackend" TEST_USERNAME = "test_user" TEST_PASSWORD = "test_password" TEST_EMAIL = "test@example.com" @classmethod def setUpTestData(cls): User.objects.create_user(cls.TEST_USERNAME, cls.TEST_EMAIL, cls.TEST_PASSWORD) @override_settings(AUTHENTICATION_BACKENDS=[backend]) def test_changed_backend_settings(self): """ Removing a backend configured in AUTHENTICATION_BACKENDS makes already logged-in users disconnect. """ # Get a session for the test user self.assertTrue( self.client.login( username=self.TEST_USERNAME, password=self.TEST_PASSWORD, ) ) # Prepare a request object request = HttpRequest() request.session = self.client.session # Remove NewModelBackend with self.settings( AUTHENTICATION_BACKENDS=["django.contrib.auth.backends.ModelBackend"] ): # Get the user from the request user = get_user(request) # Assert that the user retrieval is successful and the user is # anonymous as the backend is not longer available. self.assertIsNotNone(user) self.assertTrue(user.is_anonymous)
ChangedBackendSettingsTest
python
doocs__leetcode
solution/0400-0499/0464.Can I Win/Solution.py
{ "start": 0, "end": 516 }
class ____: def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool: @cache def dfs(mask: int, s: int) -> bool: for i in range(1, maxChoosableInteger + 1): if mask >> i & 1 ^ 1: if s + i >= desiredTotal or not dfs(mask | 1 << i, s + i): return True return False if (1 + maxChoosableInteger) * maxChoosableInteger // 2 < desiredTotal: return False return dfs(0, 0)
Solution
python
getsentry__sentry
src/sentry/integrations/slack/views/unlink_identity.py
{ "start": 997, "end": 1713 }
class ____(SlackIdentityLinkageView, UnlinkIdentityView): """ Django view for unlinking user from slack account. Deletes from Identity table. """ @property def command_response(self) -> SlackCommandResponse: return SlackCommandResponse("unlink", SUCCESS_UNLINKED_MESSAGE, "slack.unlink-identity") def get_success_template_and_context( self, params: Mapping[str, Any], integration: Integration | None ) -> tuple[str, dict[str, Any]]: if integration is None: raise ValueError context = {"channel_id": params["channel_id"], "team_id": integration.external_id} return "sentry/integrations/slack/unlinked.html", context
SlackUnlinkIdentityView
python
gevent__gevent
src/greentest/3.10/test_smtpd.py
{ "start": 33987, "end": 35548 }
class ____(unittest.TestCase): def setUp(self): smtpd.socket = asyncore.socket = mock_socket self.old_debugstream = smtpd.DEBUGSTREAM self.debug = smtpd.DEBUGSTREAM = io.StringIO() self.server = DummyServer((socket_helper.HOST, 0), ('b', 0)) conn, addr = self.server.accept() self.channel = smtpd.SMTPChannel(self.server, conn, addr) def tearDown(self): asyncore.close_all() asyncore.socket = smtpd.socket = socket smtpd.DEBUGSTREAM = self.old_debugstream def write_line(self, line): self.channel.socket.queue_recv(line) self.channel.handle_read() def test_ascii_data(self): self.write_line(b'HELO example') self.write_line(b'MAIL From:eggs@example') self.write_line(b'RCPT To:spam@example') self.write_line(b'DATA') self.write_line(b'plain ascii text') self.write_line(b'.') self.assertEqual(self.channel.received_data, b'plain ascii text') def test_utf8_data(self): self.write_line(b'HELO example') self.write_line(b'MAIL From:eggs@example') self.write_line(b'RCPT To:spam@example') self.write_line(b'DATA') self.write_line(b'utf8 enriched text: \xc5\xbc\xc5\xba\xc4\x87') self.write_line(b'and some plain ascii') self.write_line(b'.') self.assertEqual( self.channel.received_data, b'utf8 enriched text: \xc5\xbc\xc5\xba\xc4\x87\n' b'and some plain ascii')
SMTPDChannelWithDecodeDataFalse
python
optuna__optuna
optuna/pruners/_hyperband.py
{ "start": 345, "end": 14269 }
class ____(BasePruner): """Pruner using Hyperband. As SuccessiveHalving (SHA) requires the number of configurations :math:`n` as its hyperparameter. For a given finite budget :math:`B`, all the configurations have the resources of :math:`B \\over n` on average. As you can see, there will be a trade-off of :math:`B` and :math:`B \\over n`. `Hyperband <http://www.jmlr.org/papers/volume18/16-558/16-558.pdf>`__ attacks this trade-off by trying different :math:`n` values for a fixed budget. .. note:: * In the Hyperband paper, the counterpart of :class:`~optuna.samplers.RandomSampler` is used. * Optuna uses :class:`~optuna.samplers.TPESampler` by default. * `The benchmark result <https://github.com/optuna/optuna/pull/828#issuecomment-575457360>`__ shows that :class:`optuna.pruners.HyperbandPruner` supports both samplers. .. note:: If you use ``HyperbandPruner`` with :class:`~optuna.samplers.TPESampler`, it's recommended to consider setting larger ``n_trials`` or ``timeout`` to make full use of the characteristics of :class:`~optuna.samplers.TPESampler` because :class:`~optuna.samplers.TPESampler` uses some (by default, :math:`10`) :class:`~optuna.trial.Trial`\\ s for its startup. As Hyperband runs multiple :class:`~optuna.pruners.SuccessiveHalvingPruner` and collects trials based on the current :class:`~optuna.trial.Trial`\\ 's bracket ID, each bracket needs to observe more than :math:`10` :class:`~optuna.trial.Trial`\\ s for :class:`~optuna.samplers.TPESampler` to adapt its search space. Thus, for example, if ``HyperbandPruner`` has :math:`4` pruners in it, at least :math:`4 \\times 10` trials are consumed for startup. .. note:: Hyperband has several :class:`~optuna.pruners.SuccessiveHalvingPruner`\\ s. Each :class:`~optuna.pruners.SuccessiveHalvingPruner` is referred to as "bracket" in the original paper. The number of brackets is an important factor to control the early stopping behavior of Hyperband and is automatically determined by ``min_resource``, ``max_resource`` and ``reduction_factor`` as :math:`\\mathrm{The\\ number\\ of\\ brackets} = \\mathrm{floor}(\\log_{\\texttt{reduction}\\_\\texttt{factor}} (\\frac{\\texttt{max}\\_\\texttt{resource}}{\\texttt{min}\\_\\texttt{resource}})) + 1`. Please set ``reduction_factor`` so that the number of brackets is not too large (about 4 – 6 in most use cases). Please see Section 3.6 of the `original paper <http://www.jmlr.org/papers/volume18/16-558/16-558.pdf>`__ for the detail. .. note:: ``HyperbandPruner`` computes bracket ID for each trial with a function taking ``study_name`` of :class:`~optuna.study.Study` and :attr:`~optuna.trial.Trial.number`. Please specify ``study_name`` to make the pruning algorithm reproducible. Example: We minimize an objective function with Hyperband pruning algorithm. .. testcode:: import numpy as np from sklearn.datasets import load_iris from sklearn.linear_model import SGDClassifier from sklearn.model_selection import train_test_split import optuna X, y = load_iris(return_X_y=True) X_train, X_valid, y_train, y_valid = train_test_split(X, y) classes = np.unique(y) n_train_iter = 100 def objective(trial): alpha = trial.suggest_float("alpha", 0.0, 1.0) clf = SGDClassifier(alpha=alpha) for step in range(n_train_iter): clf.partial_fit(X_train, y_train, classes=classes) intermediate_value = clf.score(X_valid, y_valid) trial.report(intermediate_value, step) if trial.should_prune(): raise optuna.TrialPruned() return clf.score(X_valid, y_valid) study = optuna.create_study( direction="maximize", pruner=optuna.pruners.HyperbandPruner( min_resource=1, max_resource=n_train_iter, reduction_factor=3 ), ) study.optimize(objective, n_trials=20) Args: min_resource: A parameter for specifying the minimum resource allocated to a trial noted as :math:`r` in the paper. A smaller :math:`r` will give a result faster, but a larger :math:`r` will give a better guarantee of successful judging between configurations. See the details for :class:`~optuna.pruners.SuccessiveHalvingPruner`. max_resource: A parameter for specifying the maximum resource allocated to a trial. :math:`R` in the paper corresponds to ``max_resource / min_resource``. This value represents and should match the maximum iteration steps (e.g., the number of epochs for neural networks). When this argument is "auto", the maximum resource is estimated according to the completed trials. The default value of this argument is "auto". .. note:: With "auto", the maximum resource will be the largest step reported by :meth:`~optuna.trial.Trial.report` in the first, or one of the first if trained in parallel, completed trial. No trials will be pruned until the maximum resource is determined. .. note:: If the step of the last intermediate value may change with each trial, please manually specify the maximum possible step to ``max_resource``. reduction_factor: A parameter for specifying reduction factor of promotable trials noted as :math:`\\eta` in the paper. See the details for :class:`~optuna.pruners.SuccessiveHalvingPruner`. bootstrap_count: Parameter specifying the number of trials required in a rung before any trial can be promoted. Incompatible with ``max_resource`` is ``"auto"``. See the details for :class:`~optuna.pruners.SuccessiveHalvingPruner`. """ def __init__( self, min_resource: int = 1, max_resource: str | int = "auto", reduction_factor: int = 3, bootstrap_count: int = 0, ) -> None: self._min_resource = min_resource self._max_resource = max_resource self._reduction_factor = reduction_factor self._pruners: list[SuccessiveHalvingPruner] = [] self._bootstrap_count = bootstrap_count self._total_trial_allocation_budget = 0 self._trial_allocation_budgets: list[int] = [] self._n_brackets: int | None = None if not isinstance(self._max_resource, int) and self._max_resource != "auto": raise ValueError( "The 'max_resource' should be integer or 'auto'. But max_resource = {}".format( self._max_resource ) ) if self._bootstrap_count > 0 and self._max_resource == "auto": raise ValueError( "bootstrap_count > 0 and max_resource == 'auto' " "are mutually incompatible, bootstrap_count is {}".format(self._bootstrap_count) ) def prune(self, study: "optuna.study.Study", trial: "optuna.trial.FrozenTrial") -> bool: if len(self._pruners) == 0: self._try_initialization(study) if len(self._pruners) == 0: return False bracket_id = self._get_bracket_id(study, trial) _logger.debug("{}th bracket is selected".format(bracket_id)) bracket_study = self._create_bracket_study(study, bracket_id) return self._pruners[bracket_id].prune(bracket_study, trial) def _try_initialization(self, study: "optuna.study.Study") -> None: if self._max_resource == "auto": trials = study.get_trials(deepcopy=False, states=(TrialState.COMPLETE,)) n_steps = [t.last_step for t in trials if t.last_step is not None] if not n_steps: return self._max_resource = max(n_steps) + 1 assert isinstance(self._max_resource, int) if self._n_brackets is None: # In the original paper http://www.jmlr.org/papers/volume18/16-558/16-558.pdf, the # inputs of Hyperband are `R`: max resource and `\eta`: reduction factor. The # number of brackets (this is referred as `s_{max} + 1` in the paper) is calculated # by s_{max} + 1 = \floor{\log_{\eta} (R)} + 1 in Algorithm 1 of the original paper. # In this implementation, we combine this formula and that of ASHA paper # https://arxiv.org/abs/1502.07943 as # `n_brackets = floor(log_{reduction_factor}(max_resource / min_resource)) + 1` self._n_brackets = ( math.floor( math.log(self._max_resource / self._min_resource, self._reduction_factor) ) + 1 ) _logger.debug("Hyperband has {} brackets".format(self._n_brackets)) for bracket_id in range(self._n_brackets): trial_allocation_budget = self._calculate_trial_allocation_budget(bracket_id) self._total_trial_allocation_budget += trial_allocation_budget self._trial_allocation_budgets.append(trial_allocation_budget) pruner = SuccessiveHalvingPruner( min_resource=self._min_resource, reduction_factor=self._reduction_factor, min_early_stopping_rate=bracket_id, bootstrap_count=self._bootstrap_count, ) self._pruners.append(pruner) def _calculate_trial_allocation_budget(self, bracket_id: int) -> int: """Compute the trial allocated budget for a bracket of ``bracket_id``. In the `original paper <http://www.jmlr.org/papers/volume18/16-558/16-558.pdf>`, the number of trials per one bracket is referred as ``n`` in Algorithm 1. Since we do not know the total number of trials in the leaning scheme of Optuna, we calculate the ratio of the number of trials here instead. """ assert self._n_brackets is not None s = self._n_brackets - 1 - bracket_id return math.ceil(self._n_brackets * (self._reduction_factor**s) / (s + 1)) def _get_bracket_id( self, study: "optuna.study.Study", trial: "optuna.trial.FrozenTrial" ) -> int: """Compute the index of bracket for a trial of ``trial_number``. The index of a bracket is noted as :math:`s` in `Hyperband paper <http://www.jmlr.org/papers/volume18/16-558/16-558.pdf>`__. """ if len(self._pruners) == 0: return 0 assert self._n_brackets is not None n = ( binascii.crc32("{}_{}".format(study.study_name, trial.number).encode()) % self._total_trial_allocation_budget ) for bracket_id in range(self._n_brackets): n -= self._trial_allocation_budgets[bracket_id] if n < 0: return bracket_id assert False, "This line should be unreachable." def _create_bracket_study( self, study: "optuna.study.Study", bracket_id: int ) -> "optuna.study.Study": # This class is assumed to be passed to # `SuccessiveHalvingPruner.prune` in which `get_trials`, # `direction`, and `storage` are used. # But for safety, prohibit the other attributes explicitly. class _BracketStudy(optuna.study.Study): _VALID_ATTRS = ( "get_trials", "_get_trials", "directions", "direction", "_directions", "_storage", "_study_id", "pruner", "study_name", "_bracket_id", "sampler", "trials", "_is_multi_objective", "stop", "_study", "_thread_local", ) def __init__( self, study: "optuna.study.Study", pruner: HyperbandPruner, bracket_id: int ) -> None: super().__init__( study_name=study.study_name, storage=study._storage, sampler=study.sampler, pruner=pruner, ) self._study = study self._bracket_id = bracket_id def get_trials( self, deepcopy: bool = True, states: Container[TrialState] | None = None, ) -> list["optuna.trial.FrozenTrial"]: trials = super()._get_trials(deepcopy=deepcopy, states=states) pruner = self.pruner assert isinstance(pruner, HyperbandPruner) return [t for t in trials if pruner._get_bracket_id(self, t) == self._bracket_id] def stop(self) -> None: # `stop` should stop the original study's optimization loop instead of # `_BracketStudy`. self._study.stop() def __getattribute__(self, attr_name): # type: ignore if attr_name not in _BracketStudy._VALID_ATTRS: raise AttributeError( "_BracketStudy does not have attribute of '{}'".format(attr_name) ) else: return object.__getattribute__(self, attr_name) return _BracketStudy(study, self, bracket_id)
HyperbandPruner
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 89406, "end": 89892 }
class ____(sgqlc.types.Input): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("discussion_id", "body", "client_mutation_id") discussion_id = sgqlc.types.Field( sgqlc.types.non_null(ID), graphql_name="discussionId" ) body = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="body") client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
CreateTeamDiscussionCommentInput
python
dask__dask
dask/array/_array_expr/random.py
{ "start": 661, "end": 17219 }
class ____: """ Container for the BitGenerators. ``Generator`` exposes a number of methods for generating random numbers drawn from a variety of probability distributions and serves as a replacement for ``RandomState``. The main difference between the two is that ``Generator`` relies on an additional ``BitGenerator`` to manage state and generate the random bits, which are then transformed into random values from useful distributions. The default ``BitGenerator`` used by ``Generator`` is ``PCG64``. The ``BitGenerator`` can be changed by passing an instantiated ``BitGenerator`` to ``Generator``. The function :func:`dask.array.random.default_rng` is the recommended way to instantiate a ``Generator``. .. warning:: No Compatibility Guarantee. ``Generator`` does not provide a version compatibility guarantee. In particular, as better algorithms evolve the bit stream may change. Parameters ---------- bit_generator : BitGenerator BitGenerator to use as the core generator. Notes ----- In addition to the distribution-specific arguments, each ``Generator`` method takes a keyword argument `size` that defaults to ``None``. If `size` is ``None``, then a single value is generated and returned. If `size` is an integer, then a 1-D array filled with generated values is returned. If `size` is a tuple, then an array with that shape is filled and returned. The Python stdlib module `random` contains pseudo-random number generator with a number of methods that are similar to the ones available in ``Generator``. It uses Mersenne Twister, and this bit generator can be accessed using ``MT19937``. ``Generator``, besides being Dask-aware, has the advantage that it provides a much larger number of probability distributions to choose from. All ``Generator`` methods are identical to ``np.random.Generator`` except that they also take a `chunks=` keyword argument. ``Generator`` does not guarantee parity in the generated numbers with any third party library. In particular, numbers generated by `Dask` and `NumPy` will differ even if they use the same seed. Examples -------- >>> from numpy.random import PCG64 >>> from dask.array.random import Generator >>> rng = Generator(PCG64()) >>> rng.standard_normal().compute() # doctest: +SKIP array(0.44595957) # random See Also -------- default_rng : Recommended constructor for `Generator`. np.random.Generator """ def __init__(self, bit_generator): self._bit_generator = bit_generator def __str__(self): return f"{self.__class__.__name__}({self._bit_generator.__class__.__name__})" @property def _backend_name(self): # Assumes typename(self._RandomState) starts with an # array-library name (e.g. "numpy" or "cupy") return typename(self._bit_generator).split(".")[0] @property def _backend(self): # Assumes `self._backend_name` is an importable # array-library name (e.g. "numpy" or "cupy") return importlib.import_module(self._backend_name) @derived_from(np.random.Generator, skipblocks=1) def beta(self, a, b, size=None, chunks="auto", **kwargs): return _wrap_func(self, "beta", a, b, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def binomial(self, n, p, size=None, chunks="auto", **kwargs): return _wrap_func(self, "binomial", n, p, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def chisquare(self, df, size=None, chunks="auto", **kwargs): return _wrap_func(self, "chisquare", df, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def choice( self, a, size=None, replace=True, p=None, axis=0, shuffle=True, chunks="auto", ): ( a, size, replace, p, axis, chunks, meta, dependencies, ) = _choice_validate_params(self, a, size, replace, p, axis, chunks) return new_collection( RandomChoiceGenerator( a.expr, chunks, meta, self._bit_generator, replace, p, axis, shuffle ) ) @derived_from(np.random.Generator, skipblocks=1) def exponential(self, scale=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "exponential", scale, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def f(self, dfnum, dfden, size=None, chunks="auto", **kwargs): return _wrap_func(self, "f", dfnum, dfden, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def gamma(self, shape, scale=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "gamma", shape, scale, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def geometric(self, p, size=None, chunks="auto", **kwargs): return _wrap_func(self, "geometric", p, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def gumbel(self, loc=0.0, scale=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "gumbel", loc, scale, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def hypergeometric(self, ngood, nbad, nsample, size=None, chunks="auto", **kwargs): return _wrap_func( self, "hypergeometric", ngood, nbad, nsample, size=size, chunks=chunks, **kwargs, ) @derived_from(np.random.Generator, skipblocks=1) def integers( self, low, high=None, size=None, dtype=np.int64, endpoint=False, chunks="auto", **kwargs, ): return _wrap_func( self, "integers", low, high=high, size=size, dtype=dtype, endpoint=endpoint, chunks=chunks, **kwargs, ) @derived_from(np.random.Generator, skipblocks=1) def laplace(self, loc=0.0, scale=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "laplace", loc, scale, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def logistic(self, loc=0.0, scale=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "logistic", loc, scale, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def lognormal(self, mean=0.0, sigma=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "lognormal", mean, sigma, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def logseries(self, p, size=None, chunks="auto", **kwargs): return _wrap_func(self, "logseries", p, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def multinomial(self, n, pvals, size=None, chunks="auto", **kwargs): return _wrap_func( self, "multinomial", n, pvals, size=size, chunks=chunks, extra_chunks=((len(pvals),),), **kwargs, ) @derived_from(np.random.Generator, skipblocks=1) def multivariate_hypergeometric( self, colors, nsample, size=None, method="marginals", chunks="auto", **kwargs ): return _wrap_func( self, "multivariate_hypergeometric", colors, nsample, size=size, method=method, chunks=chunks, **kwargs, ) @derived_from(np.random.Generator, skipblocks=1) def negative_binomial(self, n, p, size=None, chunks="auto", **kwargs): return _wrap_func( self, "negative_binomial", n, p, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def noncentral_chisquare(self, df, nonc, size=None, chunks="auto", **kwargs): return _wrap_func( self, "noncentral_chisquare", df, nonc, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def noncentral_f(self, dfnum, dfden, nonc, size=None, chunks="auto", **kwargs): return _wrap_func( self, "noncentral_f", dfnum, dfden, nonc, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def normal(self, loc=0.0, scale=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "normal", loc, scale, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def pareto(self, a, size=None, chunks="auto", **kwargs): return _wrap_func(self, "pareto", a, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def permutation(self, x): from dask.array.slicing import shuffle_slice if self._backend_name == "cupy": raise NotImplementedError( "`Generator.permutation` not supported for cupy-backed " "Generator objects. Use the 'numpy' array backend to " "call `dask.array.random.default_rng`, or pass in " " `numpy.random.PCG64()`." ) if isinstance(x, numbers.Number): x = arange(x, chunks="auto") index = self._backend.arange(len(x)) _shuffle(self._bit_generator, index) return shuffle_slice(x, index) @derived_from(np.random.Generator, skipblocks=1) def poisson(self, lam=1.0, size=None, chunks="auto", **kwargs): return _wrap_func(self, "poisson", lam, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def power(self, a, size=None, chunks="auto", **kwargs): return _wrap_func(self, "power", a, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def random(self, size=None, dtype=np.float64, out=None, chunks="auto", **kwargs): return _wrap_func( self, "random", size=size, dtype=dtype, out=out, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def rayleigh(self, scale=1.0, size=None, chunks="auto", **kwargs): return _wrap_func(self, "rayleigh", scale, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def standard_cauchy(self, size=None, chunks="auto", **kwargs): return _wrap_func(self, "standard_cauchy", size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def standard_exponential(self, size=None, chunks="auto", **kwargs): return _wrap_func( self, "standard_exponential", size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def standard_gamma(self, shape, size=None, chunks="auto", **kwargs): return _wrap_func( self, "standard_gamma", shape, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def standard_normal(self, size=None, chunks="auto", **kwargs): return _wrap_func(self, "standard_normal", size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def standard_t(self, df, size=None, chunks="auto", **kwargs): return _wrap_func(self, "standard_t", df, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def triangular(self, left, mode, right, size=None, chunks="auto", **kwargs): return _wrap_func( self, "triangular", left, mode, right, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def uniform(self, low=0.0, high=1.0, size=None, chunks="auto", **kwargs): return _wrap_func( self, "uniform", low, high, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def vonmises(self, mu, kappa, size=None, chunks="auto", **kwargs): return _wrap_func( self, "vonmises", mu, kappa, size=size, chunks=chunks, **kwargs ) @derived_from(np.random.Generator, skipblocks=1) def wald(self, mean, scale, size=None, chunks="auto", **kwargs): return _wrap_func(self, "wald", mean, scale, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def weibull(self, a, size=None, chunks="auto", **kwargs): return _wrap_func(self, "weibull", a, size=size, chunks=chunks, **kwargs) @derived_from(np.random.Generator, skipblocks=1) def zipf(self, a, size=None, chunks="auto", **kwargs): return _wrap_func(self, "zipf", a, size=size, chunks=chunks, **kwargs) def default_rng(seed=None): """ Construct a new Generator with the default BitGenerator (PCG64). Parameters ---------- seed : {None, int, array_like[ints], SeedSequence, BitGenerator, Generator}, optional A seed to initialize the `BitGenerator`. If None, then fresh, unpredictable entropy will be pulled from the OS. If an ``int`` or ``array_like[ints]`` is passed, then it will be passed to `SeedSequence` to derive the initial `BitGenerator` state. One may also pass in a `SeedSequence` instance. Additionally, when passed a `BitGenerator`, it will be wrapped by `Generator`. If passed a `Generator`, it will be returned unaltered. Returns ------- Generator The initialized generator object. Notes ----- If ``seed`` is not a `BitGenerator` or a `Generator`, a new `BitGenerator` is instantiated. This function does not manage a default global instance. Examples -------- ``default_rng`` is the recommended constructor for the random number class ``Generator``. Here are several ways we can construct a random number generator using ``default_rng`` and the ``Generator`` class. Here we use ``default_rng`` to generate a random float: >>> import dask.array as da >>> rng = da.random.default_rng(12345) >>> print(rng) Generator(PCG64) >>> rfloat = rng.random().compute() >>> rfloat array(0.86999885) >>> type(rfloat) <class 'numpy.ndarray'> Here we use ``default_rng`` to generate 3 random integers between 0 (inclusive) and 10 (exclusive): >>> import dask.array as da >>> rng = da.random.default_rng(12345) >>> rints = rng.integers(low=0, high=10, size=3).compute() >>> rints array([2, 8, 7]) >>> type(rints[0]) <class 'numpy.int64'> Here we specify a seed so that we have reproducible results: >>> import dask.array as da >>> rng = da.random.default_rng(seed=42) >>> print(rng) Generator(PCG64) >>> arr1 = rng.random((3, 3)).compute() >>> arr1 array([[0.91674416, 0.91098667, 0.8765925 ], [0.30931841, 0.95465607, 0.17509458], [0.99662814, 0.75203348, 0.15038118]]) If we exit and restart our Python interpreter, we'll see that we generate the same random numbers again: >>> import dask.array as da >>> rng = da.random.default_rng(seed=42) >>> arr2 = rng.random((3, 3)).compute() >>> arr2 array([[0.91674416, 0.91098667, 0.8765925 ], [0.30931841, 0.95465607, 0.17509458], [0.99662814, 0.75203348, 0.15038118]]) See Also -------- np.random.default_rng """ if hasattr(seed, "capsule"): # We are passed a BitGenerator, so just wrap it return Generator(seed) elif isinstance(seed, Generator): # Pass through a Generator return seed elif hasattr(seed, "bit_generator"): # a Generator. Just not ours return Generator(seed.bit_generator) # Otherwise, use the backend-default BitGenerator return Generator(array_creation_dispatch.default_bit_generator(seed))
Generator
python
doocs__leetcode
solution/3200-3299/3226.Number of Bit Changes to Make Two Integers Equal/Solution.py
{ "start": 0, "end": 122 }
class ____: def minChanges(self, n: int, k: int) -> int: return -1 if n & k != k else (n ^ k).bit_count()
Solution
python
numba__numba
numba/tests/test_sort.py
{ "start": 18072, "end": 22584 }
class ____(BaseSortingTest): # NOTE these tests assume a non-argsort quicksort. def test_insertion_sort(self): n = 20 def check(l, n): res = self.array_factory([9999] + l + [-9999]) f(res, res, 1, n) self.assertEqual(res[0], 9999) self.assertEqual(res[-1], -9999) self.assertSorted(l, res[1:-1]) f = self.quicksort.insertion_sort l = self.sorted_list(n) check(l, n) l = self.revsorted_list(n) check(l, n) l = self.initially_sorted_list(n, n//2) check(l, n) l = self.revsorted_list(n) check(l, n) l = self.random_list(n) check(l, n) l = self.duprandom_list(n) check(l, n) def test_partition(self): n = 20 def check(l, n): res = self.array_factory([9999] + l + [-9999]) index = f(res, res, 1, n) self.assertEqual(res[0], 9999) self.assertEqual(res[-1], -9999) pivot = res[index] for i in range(1, index): self.assertLessEqual(res[i], pivot) for i in range(index + 1, n): self.assertGreaterEqual(res[i], pivot) f = self.quicksort.partition l = self.sorted_list(n) check(l, n) l = self.revsorted_list(n) check(l, n) l = self.initially_sorted_list(n, n//2) check(l, n) l = self.revsorted_list(n) check(l, n) l = self.random_list(n) check(l, n) l = self.duprandom_list(n) check(l, n) def test_partition3(self): # Test the unused partition3() function n = 20 def check(l, n): res = self.array_factory([9999] + l + [-9999]) lt, gt = f(res, 1, n) self.assertEqual(res[0], 9999) self.assertEqual(res[-1], -9999) pivot = res[lt] for i in range(1, lt): self.assertLessEqual(res[i], pivot) for i in range(lt, gt + 1): self.assertEqual(res[i], pivot) for i in range(gt + 1, n): self.assertGreater(res[i], pivot) f = self.quicksort.partition3 l = self.sorted_list(n) check(l, n) l = self.revsorted_list(n) check(l, n) l = self.initially_sorted_list(n, n//2) check(l, n) l = self.revsorted_list(n) check(l, n) l = self.random_list(n) check(l, n) l = self.duprandom_list(n) check(l, n) def test_run_quicksort(self): f = self.quicksort.run_quicksort for size_factor in (1, 5): # Make lists to be sorted from two chunks of different kinds. sizes = (15, 20) all_lists = [self.make_sample_lists(n * size_factor) for n in sizes] for chunks in itertools.product(*all_lists): orig_keys = sum(chunks, []) keys = self.array_factory(orig_keys) f(keys) # The list is now sorted self.assertSorted(orig_keys, keys) def test_run_quicksort_lt(self): def lt(a, b): return a > b f = self.make_quicksort(lt=lt).run_quicksort for size_factor in (1, 5): # Make lists to be sorted from two chunks of different kinds. sizes = (15, 20) all_lists = [self.make_sample_lists(n * size_factor) for n in sizes] for chunks in itertools.product(*all_lists): orig_keys = sum(chunks, []) keys = self.array_factory(orig_keys) f(keys) # The list is now rev-sorted self.assertSorted(orig_keys, keys[::-1]) # An imperfect comparison function, as LT(a, b) does not imply not LT(b, a). # The sort should handle it gracefully. def lt_floats(a, b): return math.isnan(b) or a < b f = self.make_quicksort(lt=lt_floats).run_quicksort np.random.seed(42) for size in (5, 20, 50, 500): orig = np.random.random(size=size) * 100 orig[np.random.random(size=size) < 0.1] = float('nan') orig_keys = list(orig) keys = self.array_factory(orig_keys) f(keys) non_nans = orig[~np.isnan(orig)] # Non-NaNs are sorted at the front self.assertSorted(non_nans, keys[:len(non_nans)])
BaseQuicksortTest
python
astropy__astropy
astropy/nddata/utils.py
{ "start": 866, "end": 975 }
class ____(ValueError): """Raised when determining the overlap of non-overlapping arrays."""
NoOverlapError
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 806040, "end": 806308 }
class ____( sgqlc.types.Type, Node, AuditEntry, EnterpriseAuditEntryData, OrganizationAuditEntryData, ): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ()
MembersCanDeleteReposClearAuditEntry
python
astropy__astropy
astropy/coordinates/tests/test_masked.py
{ "start": 13202, "end": 16397 }
class ____: @classmethod def setup_class(cls): cls.ra = [0.0, 3.0, 6.0, 12.0, 15.0, 18.0] << u.hourangle cls.dec = [-15.0, 30.0, 60.0, -60.0, 89.0, -80.0] << u.deg cls.dis = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0] << u.pc cls.mask_dis = np.array([False, True, False, True, False, True]) cls.pm_ra_cosdec = [1.0, 2.0, 3.0, -4.0, -5.0, -6.0] << (u.mas / u.yr) cls.mask_pm_ra_cosdec = np.array([False, False, True, False, False, True]) cls.pm_dec = [-9.0, -7.0, 5.0, 3.0, 1.0, 0.0] << (u.mas / u.yr) cls.mask_pm_dec = np.array([False, False, True, True, False, True]) cls.rv = [40.0, 50.0, 0.0, 0.0, -30.0, -10.0] << (u.km / u.s) cls.mask_rv = np.array([False, False, False, False, True, True]) cls.mdis = Masked(cls.dis, cls.mask_dis) cls.mpm_ra_cosdec = Masked(cls.pm_ra_cosdec, cls.mask_pm_ra_cosdec) cls.mpm_dec = Masked(cls.pm_dec, cls.mask_pm_dec) cls.mrv = Masked(cls.rv, cls.mask_rv) cls.sc = SkyCoord( ra=cls.ra, dec=cls.dec, distance=cls.mdis, pm_ra_cosdec=cls.mpm_ra_cosdec, pm_dec=cls.mpm_dec, radial_velocity=cls.mrv, ) cls.mask = cls.mask_dis | cls.mask_pm_ra_cosdec | cls.mask_pm_dec | cls.mask_rv def test_setup(self): assert self.sc.masked assert_array_equal(self.sc.ra.mask, False) assert_array_equal(self.sc.dec.mask, False) assert_array_equal(self.sc.distance.mask, self.mask_dis) assert_array_equal(self.sc.pm_ra_cosdec.mask, self.mask_pm_ra_cosdec) assert_array_equal(self.sc.pm_dec.mask, self.mask_pm_dec) assert_array_equal(self.sc.radial_velocity.mask, self.mask_rv) assert_array_equal(self.sc.mask, self.mask) def test_get_mask(self): assert_array_equal(self.sc.get_mask(), self.mask) assert_array_equal(self.sc.get_mask("ra", "dec"), False) def test_filled(self): unmasked = self.sc.unmasked filled = self.sc.filled(unmasked[1]) expected = unmasked.copy() expected[self.mask] = unmasked[1] assert skycoord_equal(filled, expected) def test_filled_with_masked_value(self): # Filled ignores the mask (this will be true as long as __setitem__ # ignores it; it may be a logical choice to actually use it). filled = self.sc.filled(self.sc[1]) expected = self.sc.unmasked.copy() expected[self.mask] = self.sc.unmasked[1] assert skycoord_equal(filled, expected) @pytest.mark.parametrize( "dt", [ 1 * u.yr, Masked([1, 2, 3] * u.yr, mask=[False, True, False])[:, np.newaxis], ], ) def test_apply_space_motion(self, dt): sc = self.sc.apply_space_motion(dt=dt) # All parts of the coordinate influence the final positions. expected_mask = self.sc.get_mask() | getattr(dt, "mask", False) assert_array_equal(sc.mask, expected_mask) expected_unmasked = self.sc.unmasked.apply_space_motion(dt=dt) assert skycoord_equal(sc.unmasked, expected_unmasked)
TestSkyCoordWithDifferentials
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 106966, "end": 108150 }
class ____(TestCase): def test_hashable(self): iterable = list('www.example.com') pred = lambda x: x in set('cmowz.') self.assertEqual(list(mi.lstrip(iterable, pred)), list('example.com')) self.assertEqual(list(mi.rstrip(iterable, pred)), list('www.example')) self.assertEqual(list(mi.strip(iterable, pred)), list('example')) def test_not_hashable(self): iterable = [ list('http://'), list('www'), list('.example'), list('.com'), ] pred = lambda x: x in [list('http://'), list('www'), list('.com')] self.assertEqual(list(mi.lstrip(iterable, pred)), iterable[2:]) self.assertEqual(list(mi.rstrip(iterable, pred)), iterable[:3]) self.assertEqual(list(mi.strip(iterable, pred)), iterable[2:3]) def test_math(self): iterable = [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2] pred = lambda x: x <= 2 self.assertEqual(list(mi.lstrip(iterable, pred)), iterable[3:]) self.assertEqual(list(mi.rstrip(iterable, pred)), iterable[:-3]) self.assertEqual(list(mi.strip(iterable, pred)), iterable[3:-3])
StripFunctionTests
python
walkccc__LeetCode
solutions/1560. Most Visited Sector in a Circular Track/1560.py
{ "start": 0, "end": 526 }
class ____: def mostVisited(self, n: int, rounds: list[int]) -> list[int]: # 1. if start <= end, [start, end] is the most visited. # # s --------- n # 1 -------------- n # 1 ------ e # # 2. if start > end, [1, end] and [start, n] are the most visited. # # s -- n # 1 -------------- n # 1 ------ e start = rounds[0] end = rounds[-1] if start <= end: return range(start, end + 1) return list(range(1, end + 1)) + list(range(start, n + 1))
Solution
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_data_validation02.py
{ "start": 315, "end": 1082 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("data_validation02.xlsx") def test_create_file(self): """Test the creation of a XlsxWriter file with data validation.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.data_validation( "C2", { "validate": "list", "value": ["Foo", "Bar", "Baz"], "input_title": "This is the input title", "input_message": "This is the input message", }, ) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
kubernetes-client__python
kubernetes/client/models/v1_for_node.py
{ "start": 383, "end": 3518 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ openapi_types = { 'name': 'str' } attribute_map = { 'name': 'name' } def __init__(self, name=None, local_vars_configuration=None): # noqa: E501 """V1ForNode - a model defined in OpenAPI""" # noqa: E501 if local_vars_configuration is None: local_vars_configuration = Configuration() self.local_vars_configuration = local_vars_configuration self._name = None self.discriminator = None self.name = name @property def name(self): """Gets the name of this V1ForNode. # noqa: E501 name represents the name of the node. # noqa: E501 :return: The name of this V1ForNode. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this V1ForNode. name represents the name of the node. # noqa: E501 :param name: The name of this V1ForNode. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and name is None: # noqa: E501 raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.openapi_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, V1ForNode): return False return self.to_dict() == other.to_dict() def __ne__(self, other): """Returns true if both objects are not equal""" if not isinstance(other, V1ForNode): return True return self.to_dict() != other.to_dict()
V1ForNode
python
spyder-ide__spyder
spyder/api/widgets/menus.py
{ "start": 1162, "end": 1826 }
class ____(QProxyStyle): """Style adjustments that can only be done with a proxy style.""" def pixelMetric(self, metric, option=None, widget=None): if metric == QStyle.PM_SmallIconSize: # Change icon size for menus. # Taken from https://stackoverflow.com/a/42145885/438386 delta = -1 if MAC else (0 if WIN else 1) return ( QProxyStyle.pixelMetric(self, metric, option, widget) + delta ) return QProxyStyle.pixelMetric(self, metric, option, widget) # ---- Widgets # -----------------------------------------------------------------------------
SpyderMenuProxyStyle
python
airbytehq__airbyte
airbyte-ci/connectors/connectors_qa/tests/unit_tests/test_checks/test_packaging.py
{ "start": 2206, "end": 3809 }
class ____: def test_pass_with_source_declarative_manifest(self, mocker, tmp_path): connector = mocker.MagicMock( code_directory=tmp_path, metadata={"connectorBuildOptions": {"baseImage": "docker.io/airbyte/source-declarative-manifest:4.3.0@SHA"}}, ) # Act result = packaging.CheckManifestOnlyConnectorBaseImage()._run(connector) # Assert assert result.status == CheckStatus.PASSED assert "Connector uses source-declarative-manifest base image" in result.message def test_fail_with_different_image(self, mocker, tmp_path): connector = mocker.MagicMock( code_directory=tmp_path, metadata={"connectorBuildOptions": {"baseImage": "docker.io/airbyte/connector-base-image:2.0.0@SHA"}}, ) # Act result = packaging.CheckManifestOnlyConnectorBaseImage()._run(connector) # Assert assert result.status == CheckStatus.FAILED assert "A manifest-only connector must use `source-declarative-manifest` base image" in result.message def test_fail_with_missing_image(self, mocker, tmp_path): connector = mocker.MagicMock( code_directory=tmp_path, metadata={"connectorBuildOptions": {}}, ) # Act result = packaging.CheckManifestOnlyConnectorBaseImage()._run(connector) # Assert assert result.status == CheckStatus.FAILED assert "A manifest-only connector must use `source-declarative-manifest` base image" in result.message
TestCheckManifestOnlyConnectorBaseImage
python
falconry__falcon
falcon/errors.py
{ "start": 69477, "end": 72063 }
class ____(HTTPError): """501 Not Implemented. The 501 (Not Implemented) status code indicates that the server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource. A 501 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls as described in RFC 7234, Section 4.2.2. (See also: RFC 7231, Section 6.6.2) All the arguments are defined as keyword-only. Keyword Args: title (str): Error title (default '500 Internal Server Error'). description (str): Human-friendly description of the error, along with a helpful suggestion or two. headers (dict or list): A ``dict`` of header names and values to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and *value* must be of type ``str`` or ``StringType``, and only character values 0x00 through 0xFF may be used on platforms that use wide characters. Note: The Content-Type header, if present, will be overridden. If you wish to return custom error messages, you can create your own HTTP error class, and install an error handler to convert it into an appropriate HTTP response for the client Note: Falcon can process a list of ``tuple`` slightly faster than a ``dict``. href (str): A URL someone can visit to find out more information (default ``None``). Unicode characters are percent-encoded. href_text (str): If href is given, use this as the friendly title/description for the link (default 'API documentation for this error'). code (int): An internal code that customers can reference in their support request or to help them when searching for knowledge base articles related to this error (default ``None``). """ def __init__( self, *, title: str | None = None, description: str | None = None, headers: HeaderArg | None = None, **kwargs: HTTPErrorKeywordArguments, ): super().__init__( status.HTTP_501, title=title, description=description, headers=headers, **kwargs, # type: ignore[arg-type] )
HTTPNotImplemented
python
huggingface__transformers
tests/models/doge/test_modeling_doge.py
{ "start": 1319, "end": 8878 }
class ____: def __init__( self, parent, batch_size=8, seq_length=16, is_training=True, use_input_mask=True, use_token_type_ids=False, use_labels=True, vocab_size=128, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=64, hidden_act="silu", max_position_embeddings=512, type_vocab_size=16, type_sequence_label_size=2, initializer_range=0.02, num_labels=3, pad_token_id=0, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_token_type_ids = use_token_type_ids self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.pad_token_id = pad_token_id self.scope = scope def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = None if self.use_input_mask: input_mask = torch.tril(torch.ones_like(input_ids).to(torch_device)) token_type_ids = None if self.use_token_type_ids: token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) sequence_labels = None token_labels = None if self.use_labels: sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) token_labels = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) config = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels def get_config(self): return DogeConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=False, initializer_range=self.initializer_range, pad_token_id=self.pad_token_id, ) def create_and_check_model(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels): model = DogeModel(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def create_and_check_model_as_decoder( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, encoder_hidden_states, encoder_attention_mask, ): config.add_cross_attention = True model = DogeModel(config) model.to(torch_device) model.eval() result = model( input_ids, attention_mask=input_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, ) result = model( input_ids, attention_mask=input_mask, encoder_hidden_states=encoder_hidden_states, ) result = model(input_ids, attention_mask=input_mask) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def create_and_check_for_causal_lm( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, encoder_hidden_states, encoder_attention_mask, ): model = DogeForCausalLM(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, labels=token_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def create_and_check_decoder_model_past_large_inputs( self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, encoder_hidden_states, encoder_attention_mask, ): config.is_decoder = True config.add_cross_attention = True model = DogeForCausalLM(config=config) model.to(torch_device) model.eval() # first forward pass outputs = model( input_ids, attention_mask=input_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, use_cache=True, ) past_key_values = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) # append to next input_ids and next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) output_from_no_past = model( next_input_ids, attention_mask=next_attention_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, output_hidden_states=True, )["hidden_states"][0] output_from_past = model( next_tokens, attention_mask=next_attention_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, past_key_values=past_key_values, output_hidden_states=True, )["hidden_states"][0] # select random slice random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach() output_from_past_slice = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, ) = config_and_inputs inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch
DogeModelTester
python
doocs__leetcode
solution/1700-1799/1797.Design Authentication Manager/Solution.py
{ "start": 0, "end": 782 }
class ____: def __init__(self, timeToLive: int): self.t = timeToLive self.d = defaultdict(int) def generate(self, tokenId: str, currentTime: int) -> None: self.d[tokenId] = currentTime + self.t def renew(self, tokenId: str, currentTime: int) -> None: if self.d[tokenId] <= currentTime: return self.d[tokenId] = currentTime + self.t def countUnexpiredTokens(self, currentTime: int) -> int: return sum(exp > currentTime for exp in self.d.values()) # Your AuthenticationManager object will be instantiated and called as such: # obj = AuthenticationManager(timeToLive) # obj.generate(tokenId,currentTime) # obj.renew(tokenId,currentTime) # param_3 = obj.countUnexpiredTokens(currentTime)
AuthenticationManager
python
docker__docker-py
docker/types/containers.py
{ "start": 354, "end": 571 }
class ____: _values = ( 'json-file', 'syslog', 'journald', 'gelf', 'fluentd', 'none' ) JSON, SYSLOG, JOURNALD, GELF, FLUENTD, NONE = _values
LogConfigTypesEnum
python
tensorflow__tensorflow
tensorflow/python/debug/cli/cli_config.py
{ "start": 951, "end": 5600 }
class ____(object): """Client-facing configurations for TFDBG command-line interfaces.""" _CONFIG_FILE_NAME = ".tfdbg_config" _DEFAULT_CONFIG = [ ("graph_recursion_depth", 20), ("mouse_mode", True), ] def __init__(self, config_file_path=None): self._config_file_path = (config_file_path or self._default_config_file_path()) self._config = collections.OrderedDict(self._DEFAULT_CONFIG) if gfile.Exists(self._config_file_path): config = self._load_from_file() for key, value in config.items(): self._config[key] = value self._save_to_file() self._set_callbacks = {} def get(self, property_name): if property_name not in self._config: raise KeyError("%s is not a valid property name." % property_name) return self._config[property_name] def set(self, property_name, property_val): """Set the value of a property. Supports limitd property value types: `bool`, `int` and `str`. Args: property_name: Name of the property. property_val: Value of the property. If the property has `bool` type and this argument has `str` type, the `str` value will be parsed as a `bool` Raises: ValueError: if a `str` property_value fails to be parsed as a `bool`. KeyError: if `property_name` is an invalid property name. """ if property_name not in self._config: raise KeyError("%s is not a valid property name." % property_name) orig_val = self._config[property_name] if isinstance(orig_val, bool): if isinstance(property_val, str): if property_val.lower() in ("1", "true", "t", "yes", "y", "on"): property_val = True elif property_val.lower() in ("0", "false", "f", "no", "n", "off"): property_val = False else: raise ValueError( "Invalid string value for bool type: %s" % property_val) else: property_val = bool(property_val) elif isinstance(orig_val, int): property_val = int(property_val) elif isinstance(orig_val, str): property_val = str(property_val) else: raise TypeError("Unsupported property type: %s" % type(orig_val)) self._config[property_name] = property_val self._save_to_file() # Invoke set-callback. if property_name in self._set_callbacks: self._set_callbacks[property_name](self._config) def set_callback(self, property_name, callback): """Set a set-callback for given property. Args: property_name: Name of the property. callback: The callback as a `callable` of signature: def cbk(config): where config is the config after it is set to the new value. The callback is invoked each time the set() method is called with the matching property_name. Raises: KeyError: If property_name does not exist. TypeError: If `callback` is not callable. """ if property_name not in self._config: raise KeyError("%s is not a valid property name." % property_name) if not callable(callback): raise TypeError("The callback object provided is not callable.") self._set_callbacks[property_name] = callback def _default_config_file_path(self): return os.path.join(os.path.expanduser("~"), self._CONFIG_FILE_NAME) def _save_to_file(self): try: with gfile.Open(self._config_file_path, "w") as config_file: json.dump(self._config, config_file) except IOError: pass def summarize(self, highlight=None): """Get a text summary of the config. Args: highlight: A property name to highlight in the output. Returns: A `RichTextLines` output. """ lines = [RL("Command-line configuration:", "bold"), RL("")] for name, val in self._config.items(): highlight_attr = "bold" if name == highlight else None line = RL(" ") line += RL(name, ["underline", highlight_attr]) line += RL(": ") line += RL(str(val), font_attr=highlight_attr) lines.append(line) return debugger_cli_common.rich_text_lines_from_rich_line_list(lines) def _load_from_file(self): try: with gfile.Open(self._config_file_path, "r") as config_file: config_dict = json.load(config_file) config = collections.OrderedDict() for key in sorted(config_dict.keys()): config[key] = config_dict[key] return config except (IOError, ValueError): # The reading of the config file may fail due to IO issues or file # corruption. We do not want tfdbg to error out just because of that. return dict()
CLIConfig
python
zarr-developers__zarr-python
src/zarr/errors.py
{ "start": 2442, "end": 2543 }
class ____(BaseZarrError): """ Raised when an unknown codec was used. """
UnknownCodecError
python
ray-project__ray
python/ray/train/v2/_internal/execution/worker_group/poll.py
{ "start": 1113, "end": 1269 }
class ____: running: bool error: Optional[Exception] = None training_report: Optional[_TrainingReport] = None @dataclass(frozen=True)
WorkerStatus
python
ray-project__ray
python/ray/serve/_private/handle_options.py
{ "start": 839, "end": 1407 }
class ____(InitHandleOptionsBase): @classmethod def create(cls, **kwargs) -> "InitHandleOptions": for k in list(kwargs.keys()): if kwargs[k] == DEFAULT.VALUE: # Use default value del kwargs[k] # Detect replica source for handles if ( "_source" not in kwargs and ray.serve.context._get_internal_replica_context() is not None ): kwargs["_source"] = DeploymentHandleSource.REPLICA return cls(**kwargs) @dataclass(frozen=True)
InitHandleOptions
python
tensorflow__tensorflow
tensorflow/python/distribute/cross_device_utils_test.py
{ "start": 1311, "end": 5268 }
class ____(test.TestCase, parameterized.TestCase): def _assert_values_equal(self, left, right): self.assertAllEqual( self.evaluate(ops.convert_to_tensor(left)), self.evaluate(ops.convert_to_tensor(right))) @test_util.run_in_graph_and_eager_modes def testAggregateTensors(self): t0 = constant_op.constant([[1., 2.], [0, 0], [3., 4.]]) t1 = constant_op.constant([[0., 0.], [5, 6], [7., 8.]]) total = constant_op.constant([[1., 2.], [5, 6], [10., 12.]]) result = cross_device_utils.aggregate_tensors_or_indexed_slices([t0, t1]) self._assert_values_equal(total, result) @test_util.run_in_graph_and_eager_modes def testAggregateIndexedSlices(self): t0 = math_ops._as_indexed_slices( constant_op.constant([[1., 2.], [0, 0], [3., 4.]])) t1 = math_ops._as_indexed_slices( constant_op.constant([[0., 0.], [5, 6], [7., 8.]])) total = constant_op.constant([[1., 2.], [5, 6], [10., 12.]]) result = cross_device_utils.aggregate_tensors_or_indexed_slices([t0, t1]) self.assertIsInstance(result, indexed_slices.IndexedSlices) self._assert_values_equal(total, result) @test_util.run_in_graph_and_eager_modes def testDivideTensor(self): t = constant_op.constant([[1., 2.], [0, 0], [3., 4.]]) n = 2 expected = constant_op.constant([[0.5, 1.], [0, 0], [1.5, 2.]]) result = cross_device_utils.divide_by_n_tensors_or_indexed_slices(t, n) self._assert_values_equal(expected, result) @test_util.run_in_graph_and_eager_modes def testDivideIndexedSlices(self): t = math_ops._as_indexed_slices( constant_op.constant([[1., 2.], [0, 0], [3., 4.]])) n = 2 expected = constant_op.constant([[0.5, 1.], [0, 0], [1.5, 2.]]) result = cross_device_utils.divide_by_n_tensors_or_indexed_slices(t, n) self.assertIsInstance(result, indexed_slices.IndexedSlices) self._assert_values_equal(expected, result) @test_util.run_in_graph_and_eager_modes def testIsIndexedSlices(self): t = math_ops._as_indexed_slices( constant_op.constant([[1., 2.], [0, 0], [3., 4.]])) self.assertTrue(cross_device_utils.is_indexed_slices(t)) @combinations.generate(combinations.combine( mode=["graph", "eager"], required_gpus=1)) def testCopyTensor(self): with ops.device("/cpu:0"): t = constant_op.constant([[1., 2.], [0, 0], [3., 4.]]) destination = "/gpu:0" result = cross_device_utils.copy_tensor_or_indexed_slices_to_device( t, destination) self._assert_values_equal(t, result) self.assertEqual(device_util.resolve(destination), device_util.resolve(result.device)) @combinations.generate(combinations.combine( mode=["graph", "eager"], required_gpus=1)) def testCopyIndexedSlices(self): with ops.device("/cpu:0"): t = math_ops._as_indexed_slices( constant_op.constant([[1., 2.], [0, 0], [3., 4.]])) destination = "/gpu:0" result = cross_device_utils.copy_tensor_or_indexed_slices_to_device( t, destination) self.assertIsInstance(result, indexed_slices.IndexedSlices) self._assert_values_equal(t, result) self.assertEqual( device_util.resolve(destination), device_util.resolve(result.device)) @combinations.generate( combinations.combine(mode=["graph", "eager"], required_gpus=1)) def testCopyIndexedSlicesNoDenseShape(self): with ops.device("/cpu:0"): t = indexed_slices.IndexedSlices( indices=array_ops.identity([0]), values=array_ops.identity([1.])) destination = "/gpu:0" result = cross_device_utils.copy_tensor_or_indexed_slices_to_device( t, destination) self.assertIsInstance(result, indexed_slices.IndexedSlices) self.assertAllEqual(t.indices, result.indices) self.assertAllEqual(t.values, result.values) self.assertEqual( device_util.resolve(destination), device_util.resolve(result.device))
IndexedSlicesUtilsTest
python
pypa__hatch
tests/backend/version/scheme/test_standard.py
{ "start": 3400, "end": 3780 }
class ____: def test_begin(self, isolation): scheme = StandardScheme(str(isolation), {}) assert scheme.update("dev", "9000.0.0-rc.3-7", {}) == "9000.0.0rc3.post7.dev0" def test_continue(self, isolation): scheme = StandardScheme(str(isolation), {}) assert scheme.update("dev", "9000.0.0-rc.3-7.dev5", {}) == "9000.0.0rc3.post7.dev6"
TestDev
python
walkccc__LeetCode
solutions/467. Unique Substrings in Wraparound String/467.py
{ "start": 0, "end": 479 }
class ____: def findSubstringInWraproundString(self, s: str) -> int: maxLength = 1 # count[i] := the number of substrings ending in ('a' + i) count = [0] * 26 for i in range(len(s)): if i > 0 and (ord(s[i]) - ord(s[i - 1]) == 1 or ord(s[i - 1]) - ord(s[i]) == 25): maxLength += 1 else: maxLength = 1 index = ord(s[i]) - ord('a') count[index] = max(count[index], maxLength) return sum(count)
Solution
python
sphinx-doc__sphinx
sphinx/util/cfamily.py
{ "start": 2929, "end": 3979 }
class ____: def __eq__(self, other: object) -> bool: if type(self) is not type(other): return NotImplemented try: return self.__dict__ == other.__dict__ except AttributeError: return False def __hash__(self) -> int: return hash(sorted(self.__dict__.items())) def clone(self) -> Any: return deepcopy(self) def _stringify(self, transform: StringifyTransform) -> str: raise NotImplementedError def __str__(self) -> str: return self._stringify(str) def get_display_string(self) -> str: return self._stringify(lambda ast: ast.get_display_string()) def __repr__(self) -> str: if repr_string := self._stringify(repr): return f'<{self.__class__.__name__}: {repr_string}>' return f'<{self.__class__.__name__}>' ################################################################################ # Attributes ################################################################################
ASTBaseBase
python
doocs__leetcode
solution/0700-0799/0709.To Lower Case/Solution.py
{ "start": 0, "end": 134 }
class ____: def toLowerCase(self, s: str) -> str: return "".join([chr(ord(c) | 32) if c.isupper() else c for c in s])
Solution
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_representation/handle.py
{ "start": 735, "end": 3163 }
class ____: repository_name: str code_location_origin: CodeLocationOrigin repository_python_origin: Optional[RepositoryPythonOrigin] display_metadata: Mapping[str, str] @classmethod def from_location(cls, repository_name: str, code_location: "CodeLocation"): from dagster._core.remote_representation.code_location import CodeLocation check.inst_param(code_location, "code_location", CodeLocation) return cls( repository_name=repository_name, code_location_origin=code_location.origin, repository_python_origin=code_location.get_repository_python_origin(repository_name), display_metadata=code_location.get_display_metadata(), ) @property def location_name(self) -> str: return self.code_location_origin.location_name def get_remote_origin(self) -> RemoteRepositoryOrigin: return RemoteRepositoryOrigin( code_location_origin=self.code_location_origin, repository_name=self.repository_name, ) def get_python_origin(self) -> RepositoryPythonOrigin: return check.not_none( self.repository_python_origin, "Repository does not have a RepositoryPythonOrigin" ) def to_selector(self) -> RepositorySelector: return RepositorySelector( location_name=self.location_name, repository_name=self.repository_name, ) def get_compound_id(self) -> "CompoundID": return CompoundID( remote_origin_id=self.get_remote_origin().get_id(), selector_id=self.to_selector().selector_id, ) @staticmethod def for_test( *, location_name: str = "fake_location", repository_name: str = "fake_repository", display_metadata: Optional[Mapping[str, str]] = None, ) -> "RepositoryHandle": return RepositoryHandle( repository_name=repository_name, code_location_origin=RegisteredCodeLocationOrigin(location_name=location_name), repository_python_origin=RepositoryPythonOrigin( executable_path=sys.executable, code_pointer=ModuleCodePointer( module="fake.module", fn_name="fake_fn", ), ), display_metadata=display_metadata or {}, ) @record(kw_only=False)
RepositoryHandle
python
apache__airflow
airflow-core/tests/unit/cli/commands/test_jobs_command.py
{ "start": 1189, "end": 6123 }
class ____: @classmethod def setup_class(cls): cls.parser = cli_parser.get_parser() def setup_method(self) -> None: clear_db_jobs() self.scheduler_job = None self.job_runner = None def teardown_method(self) -> None: clear_db_jobs() def test_should_report_success_for_one_working_scheduler(self, stdout_capture): with create_session() as session: self.scheduler_job = Job() self.job_runner = SchedulerJobRunner(job=self.scheduler_job) self.scheduler_job.state = State.RUNNING session.add(self.scheduler_job) session.commit() self.scheduler_job.heartbeat(heartbeat_callback=self.job_runner.heartbeat_callback) with stdout_capture as temp_stdout: jobs_command.check(self.parser.parse_args(["jobs", "check", "--job-type", "SchedulerJob"])) assert "Found one alive job." in temp_stdout.getvalue() def test_should_report_success_for_one_working_scheduler_with_hostname(self, stdout_capture): with create_session() as session: self.scheduler_job = Job() self.job_runner = SchedulerJobRunner(job=self.scheduler_job) self.scheduler_job.state = State.RUNNING self.scheduler_job.hostname = "HOSTNAME" session.add(self.scheduler_job) session.commit() self.scheduler_job.heartbeat(heartbeat_callback=self.job_runner.heartbeat_callback) with stdout_capture as temp_stdout: jobs_command.check( self.parser.parse_args( ["jobs", "check", "--job-type", "SchedulerJob", "--hostname", "HOSTNAME"] ) ) assert "Found one alive job." in temp_stdout.getvalue() def test_should_report_success_for_ha_schedulers(self, stdout_capture): scheduler_jobs = [] job_runners = [] with create_session() as session: for _ in range(3): scheduler_job = Job() job_runner = SchedulerJobRunner(job=scheduler_job) scheduler_job.state = State.RUNNING session.add(scheduler_job) scheduler_jobs.append(scheduler_job) job_runners.append(job_runner) session.commit() scheduler_job.heartbeat(heartbeat_callback=job_runner.heartbeat_callback) with stdout_capture as temp_stdout: jobs_command.check( self.parser.parse_args( ["jobs", "check", "--job-type", "SchedulerJob", "--limit", "100", "--allow-multiple"] ) ) assert "Found 3 alive jobs." in temp_stdout.getvalue() def test_should_ignore_not_running_jobs(self): scheduler_jobs = [] job_runners = [] with create_session() as session: for _ in range(3): scheduler_job = Job() job_runner = SchedulerJobRunner(job=scheduler_job) scheduler_job.state = JobState.FAILED session.add(scheduler_job) scheduler_jobs.append(scheduler_job) job_runners.append(job_runner) session.commit() # No alive jobs found. with pytest.raises(SystemExit, match=r"No alive jobs found."): jobs_command.check(self.parser.parse_args(["jobs", "check"])) def test_should_raise_exception_for_multiple_scheduler_on_one_host(self): scheduler_jobs = [] job_runners = [] with create_session() as session: for _ in range(3): scheduler_job = Job() job_runner = SchedulerJobRunner(job=scheduler_job) job_runner.job = scheduler_job scheduler_job.state = State.RUNNING scheduler_job.hostname = "HOSTNAME" session.add(scheduler_job) scheduler_jobs.append(scheduler_job) job_runners.append(job_runner) session.commit() scheduler_job.heartbeat(heartbeat_callback=job_runner.heartbeat_callback) with pytest.raises(SystemExit, match=r"Found 3 alive jobs. Expected only one."): jobs_command.check( self.parser.parse_args( [ "jobs", "check", "--job-type", "SchedulerJob", "--limit", "100", ] ) ) def test_should_raise_exception_for_allow_multiple_and_limit_1(self): with pytest.raises( SystemExit, match=r"To use option --allow-multiple, you must set the limit to a value greater than 1.", ): jobs_command.check(self.parser.parse_args(["jobs", "check", "--allow-multiple"]))
TestCliConfigList
python
spack__spack
lib/spack/spack/package_base.py
{ "start": 107443, "end": 107708 }
class ____(spack.error.SpackError): """Raised when the dependencies cannot be flattened as asked for.""" def __init__(self, conflict): super().__init__("%s conflicts with another file in the flattened directory." % (conflict))
DependencyConflictError
python
jd__tenacity
tests/test_tenacity.py
{ "start": 51899, "end": 53845 }
class ____(unittest.TestCase): def test_reraise_by_default(self): calls = [] @retry( wait=tenacity.wait_fixed(0.1), stop=tenacity.stop_after_attempt(2), reraise=True, ) def _reraised_by_default(): calls.append("x") raise KeyError("Bad key") self.assertRaises(KeyError, _reraised_by_default) self.assertEqual(2, len(calls)) def test_reraise_from_retry_error(self): calls = [] @retry(wait=tenacity.wait_fixed(0.1), stop=tenacity.stop_after_attempt(2)) def _raise_key_error(): calls.append("x") raise KeyError("Bad key") def _reraised_key_error(): try: _raise_key_error() except tenacity.RetryError as retry_err: retry_err.reraise() self.assertRaises(KeyError, _reraised_key_error) self.assertEqual(2, len(calls)) def test_reraise_timeout_from_retry_error(self): calls = [] @retry( wait=tenacity.wait_fixed(0.1), stop=tenacity.stop_after_attempt(2), retry=lambda retry_state: True, ) def _mock_fn(): calls.append("x") def _reraised_mock_fn(): try: _mock_fn() except tenacity.RetryError as retry_err: retry_err.reraise() self.assertRaises(tenacity.RetryError, _reraised_mock_fn) self.assertEqual(2, len(calls)) def test_reraise_no_exception(self): calls = [] @retry( wait=tenacity.wait_fixed(0.1), stop=tenacity.stop_after_attempt(2), retry=lambda retry_state: True, reraise=True, ) def _mock_fn(): calls.append("x") self.assertRaises(tenacity.RetryError, _mock_fn) self.assertEqual(2, len(calls))
TestReraiseExceptions
python
tensorflow__tensorflow
third_party/xla/xla/python/xla_client.py
{ "start": 3463, "end": 3728 }
class ____: """Python representation of a xla.ResultAccuracy protobuf.""" __slots__ = ('mode', 'atol', 'rtol', 'ulps') def __init__(self): self.mode = ops.ResultAccuracy_Mode.DEFAULT self.atol = 0.0 self.rtol = 0.0 self.ulps = 0
ResultAccuracy
python
django__django
tests/gis_tests/geo3d/models.py
{ "start": 885, "end": 959 }
class ____(NamedModel): poly = models.PolygonField(srid=32140)
Polygon2D
python
allegroai__clearml
clearml/backend_api/session/jsonmodels/builders.py
{ "start": 4831, "end": 5846 }
class ____(Builder): def __init__(self, *args: Any, **kwargs: Any) -> None: super(ListBuilder, self).__init__(*args, **kwargs) self.schemas = [] def add_type_schema(self, schema: Any) -> None: self.schemas.append(schema) def build(self) -> dict: schema = {"type": "array"} if self.nullable: self.add_type_schema({"type": "null"}) if self.has_default: schema["default"] = [self.to_struct(i) for i in self.default] schemas = [self.maybe_build(s) for s in self.schemas] if len(schemas) == 1: items = schemas[0] else: items = {"oneOf": schemas} schema["items"] = items return schema @property def is_definition(self) -> bool: return self.parent.is_definition @staticmethod def to_struct(item: Any) -> Any: from .models import Base if isinstance(item, Base): return item.to_struct() return item
ListBuilder
python
tensorflow__tensorflow
tensorflow/python/client/timeline.py
{ "start": 1229, "end": 1642 }
class ____( collections.namedtuple( 'AllocationMaximum', ('timestamp', 'num_bytes', 'tensors') ) ): """Stores the maximum allocation for a given allocator within the timelne. Parameters: timestamp: `tensorflow::Env::NowMicros()` when this maximum was reached. num_bytes: the total memory used at this time. tensors: the set of tensors allocated at this time. """
AllocationMaximum
python
getsentry__sentry
src/sentry/api/endpoints/organization_spans_fields.py
{ "start": 5478, "end": 7189 }
class ____(OrganizationSpansFieldsEndpointBase): def get(self, request: Request, organization: Organization, key: str) -> Response: performance_trace_explorer = features.has( "organizations:performance-trace-explorer", organization, actor=request.user ) visibility_explore_view = features.has( "organizations:visibility-explore-view", organization, actor=request.user ) if not performance_trace_explorer and not visibility_explore_view: return Response(status=404) try: snuba_params = self.get_snuba_params(request, organization) except NoProjects: return self.paginate( request=request, paginator=ChainPaginator([]), ) sentry_sdk.set_tag("query.tag_key", key) max_span_tag_values = options.get("performance.spans-tags-values.max") executor = EAPSpanFieldValuesAutocompletionExecutor( organization=organization, snuba_params=snuba_params, key=key, query=request.GET.get("query"), max_span_tag_values=max_span_tag_values, ) with handle_query_errors(): tag_values = executor.execute() tag_values.sort(key=lambda tag: tag.value or "") paginator = ChainPaginator([tag_values], max_limit=max_span_tag_values) return self.paginate( request=request, paginator=paginator, on_results=lambda results: serialize(results, request.user), default_per_page=max_span_tag_values, max_per_page=max_span_tag_values, )
OrganizationSpansFieldValuesEndpoint
python
doocs__leetcode
lcof2/剑指 Offer II 058. 日程表/Solution.py
{ "start": 0, "end": 445 }
class ____: def __init__(self): self.sd = SortedDict() def book(self, start: int, end: int) -> bool: idx = self.sd.bisect_right(start) if 0 <= idx < len(self.sd): if end > self.sd.values()[idx]: return False self.sd[end] = start return True # Your MyCalendar object will be instantiated and called as such: # obj = MyCalendar() # param_1 = obj.book(start,end)
MyCalendar
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_tab_color02.py
{ "start": 350, "end": 906 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("tab_color02.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with a tab color.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() worksheet.write("A1", "Foo") worksheet.set_tab_color(Color.theme(9, 4)) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
wandb__wandb
wandb/vendor/pygments/lexers/asm.py
{ "start": 5856, "end": 6281 }
class ____(DelegatingLexer): """ For the output of 'objdump -Sr on compiled C++ files' """ name = 'cpp-objdump' aliases = ['cpp-objdump', 'c++-objdumb', 'cxx-objdump'] filenames = ['*.cpp-objdump', '*.c++-objdump', '*.cxx-objdump'] mimetypes = ['text/x-cpp-objdump'] def __init__(self, **options): super(CppObjdumpLexer, self).__init__(CppLexer, ObjdumpLexer, **options)
CppObjdumpLexer
python
wandb__wandb
wandb/apis/public/registries/_members.py
{ "start": 1931, "end": 3350 }
class ____: kind: MemberKind index: int def encode(self) -> str: """Converts this parsed ID to a base64-encoded GraphQL ID.""" return b64encode_ascii(f"{self.kind.value}:{self.index}") @singledispatchmethod @classmethod def from_obj(cls, obj: MemberOrId, /) -> MemberId: """Parses `User` or `Team` ID from the argument.""" # Fallback for unexpected types raise TypeError( f"Member arg must be a {nameof(User)!r}, {nameof(Team)!r}, or a user/team ID. " f"Got: {nameof(type(obj))!r}" ) @from_obj.register(User) @from_obj.register(Team) @classmethod def _from_obj_with_id(cls, obj: User | Team, /) -> MemberId: # Use the object's string (base64-encoded) GraphQL ID return cls._from_id(obj.id) @from_obj.register(UserMember) @classmethod def _from_user_member(cls, member: UserMember, /) -> MemberId: return cls._from_id(member.user.id) @from_obj.register(TeamMember) @classmethod def _from_team_member(cls, member: TeamMember, /) -> MemberId: return cls._from_id(member.team.id) @from_obj.register(str) @classmethod def _from_id(cls, id_: str, /) -> MemberId: # Parse the ID to figure out if it's a team or user ID kind, index = b64decode_ascii(id_).split(":", maxsplit=1) return cls(kind=kind, index=index)
MemberId
python
tensorflow__tensorflow
third_party/xla/xla/python/xla_compiler_test.py
{ "start": 1284, "end": 2873 }
class ____(parameterized.TestCase): def test_create_literal_from_ndarray_rank_1(self, dtype): input_array = create_random_array([10], dtype) shape = xla_extension.Shape.array_shape( input_array.dtype, input_array.shape ) literal = xla_extension.Literal(shape) # use `np.asarray` to ensure that the array is a view into the literal. array = np.asarray(literal) np.copyto(array, input_array) # Intentionally check against `np.array(literal)` instead of `array` # to ensure that the underlying literal is actually updated and not some # rebinding to a new object. (This also exersises the copy functionality) np.testing.assert_array_equal(np.array(literal), input_array) def test_create_literal_from_ndarray_rank_2(self, dtype): input_array = create_random_array([20, 5], dtype) shape = xla_extension.Shape.array_shape( input_array.dtype, input_array.shape, [1, 0] ) literal = xla_extension.Literal(shape) array = np.asarray(literal) np.copyto(array, input_array) np.testing.assert_array_equal(np.array(literal), input_array) def test_create_literal_from_ndarray_rank_2_reverse_layout(self, dtype): input_array = create_random_array([25, 4], dtype) shape = xla_extension.Shape.array_shape( input_array.dtype, input_array.shape, [0, 1] ) literal = xla_extension.Literal(shape) array = np.asarray(literal) np.copyto(array, input_array) np.testing.assert_array_equal(np.array(literal), input_array) if __name__ == "__main__": absltest.main()
ConstructLiteralTest
python
plotly__plotly.py
plotly/basewidget.py
{ "start": 352, "end": 34931 }
class ____(BaseFigure, anywidget.AnyWidget): """ Base class for FigureWidget. The FigureWidget class is code-generated as a subclass """ _esm = pathlib.Path(__file__).parent / "package_data" / "widgetbundle.js" # ### _data and _layout ### # These properties store the current state of the traces and # layout as JSON-style dicts. These dicts do not store any subclasses of # `BasePlotlyType` # # Note: These are only automatically synced with the frontend on full # assignment, not on mutation. We use this fact to only directly sync # them to the front-end on FigureWidget construction. All other updates # are made using mutation, and they are manually synced to the frontend # using the relayout/restyle/update/etc. messages. _widget_layout = Dict().tag(sync=True, **custom_serializers) _widget_data = List().tag(sync=True, **custom_serializers) _config = Dict().tag(sync=True, **custom_serializers) # ### Python -> JS message properties ### # These properties are used to send messages from Python to the # frontend. Messages are sent by assigning the message contents to the # appropriate _py2js_* property and then immediatly assigning None to the # property. # # See JSDoc comments in the FigureModel class in js/src/Figure.js for # detailed descriptions of the messages. _py2js_addTraces = Dict(allow_none=True).tag(sync=True, **custom_serializers) _py2js_restyle = Dict(allow_none=True).tag(sync=True, **custom_serializers) _py2js_relayout = Dict(allow_none=True).tag(sync=True, **custom_serializers) _py2js_update = Dict(allow_none=True).tag(sync=True, **custom_serializers) _py2js_animate = Dict(allow_none=True).tag(sync=True, **custom_serializers) _py2js_deleteTraces = Dict(allow_none=True).tag(sync=True, **custom_serializers) _py2js_moveTraces = Dict(allow_none=True).tag(sync=True, **custom_serializers) _py2js_removeLayoutProps = Dict(allow_none=True).tag( sync=True, **custom_serializers ) _py2js_removeTraceProps = Dict(allow_none=True).tag(sync=True, **custom_serializers) # ### JS -> Python message properties ### # These properties are used to receive messages from the frontend. # Messages are received by defining methods that observe changes to these # properties. Receive methods are named `_handler_js2py_*` where '*' is # the name of the corresponding message property. Receive methods are # responsible for setting the message property to None after retreiving # the message data. # # See JSDoc comments in the FigureModel class in js/src/Figure.js for # detailed descriptions of the messages. _js2py_traceDeltas = Dict(allow_none=True).tag(sync=True, **custom_serializers) _js2py_layoutDelta = Dict(allow_none=True).tag(sync=True, **custom_serializers) _js2py_restyle = Dict(allow_none=True).tag(sync=True, **custom_serializers) _js2py_relayout = Dict(allow_none=True).tag(sync=True, **custom_serializers) _js2py_update = Dict(allow_none=True).tag(sync=True, **custom_serializers) _js2py_pointsCallback = Dict(allow_none=True).tag(sync=True, **custom_serializers) # ### Message tracking properties ### # The _last_layout_edit_id and _last_trace_edit_id properties are used # to keep track of the edit id of the message that most recently # requested an update to the Figures layout or traces respectively. # # We track this information because we don't want to update the Figure's # default layout/trace properties (_layout_defaults, _data_defaults) # while edits are in process. This can lead to inconsistent property # states. _last_layout_edit_id = Integer(0).tag(sync=True) _last_trace_edit_id = Integer(0).tag(sync=True) _set_trace_uid = True _allow_disable_validation = False # Constructor # ----------- def __init__( self, data=None, layout=None, frames=None, skip_invalid=False, **kwargs ): # Call superclass constructors # ---------------------------- # Note: We rename layout to layout_plotly because to deconflict it # with the `layout` constructor parameter of the `widgets.DOMWidget` # ipywidgets class super(BaseFigureWidget, self).__init__( data=data, layout_plotly=layout, frames=frames, skip_invalid=skip_invalid, **kwargs, ) # Validate Frames # --------------- # Frames are not supported by figure widget if self._frame_objs: BaseFigureWidget._display_frames_error() # Message States # -------------- # ### Layout ### # _last_layout_edit_id is described above self._last_layout_edit_id = 0 # _layout_edit_in_process is set to True if there are layout edit # operations that have been sent to the frontend that haven't # completed yet. self._layout_edit_in_process = False # _waiting_edit_callbacks is a list of callback functions that # should be executed as soon as all pending edit operations are # completed self._waiting_edit_callbacks = [] # ### Trace ### # _last_trace_edit_id: described above self._last_trace_edit_id = 0 # _trace_edit_in_process is set to True if there are trace edit # operations that have been sent to the frontend that haven't # completed yet. self._trace_edit_in_process = False # View count # ---------- # ipywidget property that stores the number of active frontend # views of this widget self._view_count = 0 # Initialize widget layout and data for third-party widget integration # -------------------------------------------------------------------- self._widget_layout = deepcopy(self._layout_obj._props) self._widget_data = deepcopy(self._data) def show(self, *args, **kwargs): return self # Python -> JavaScript Messages # ----------------------------- def _send_relayout_msg(self, layout_data, source_view_id=None): """ Send Plotly.relayout message to the frontend Parameters ---------- layout_data : dict Plotly.relayout layout data source_view_id : str UID of view that triggered this relayout operation (e.g. By the user clicking 'zoom' in the toolbar). None if the operation was not triggered by a frontend view """ # Increment layout edit messages IDs # ---------------------------------- layout_edit_id = self._last_layout_edit_id + 1 self._last_layout_edit_id = layout_edit_id self._layout_edit_in_process = True # Build message # ------------- msg_data = { "relayout_data": layout_data, "layout_edit_id": layout_edit_id, "source_view_id": source_view_id, } # Send message # ------------ self._py2js_relayout = msg_data self._py2js_relayout = None def _send_restyle_msg(self, restyle_data, trace_indexes=None, source_view_id=None): """ Send Plotly.restyle message to the frontend Parameters ---------- restyle_data : dict Plotly.restyle restyle data trace_indexes : list[int] List of trace indexes that the restyle operation applies to source_view_id : str UID of view that triggered this restyle operation (e.g. By the user clicking the legend to hide a trace). None if the operation was not triggered by a frontend view """ # Validate / normalize inputs # --------------------------- trace_indexes = self._normalize_trace_indexes(trace_indexes) # Increment layout/trace edit message IDs # --------------------------------------- layout_edit_id = self._last_layout_edit_id + 1 self._last_layout_edit_id = layout_edit_id self._layout_edit_in_process = True trace_edit_id = self._last_trace_edit_id + 1 self._last_trace_edit_id = trace_edit_id self._trace_edit_in_process = True # Build message # ------------- restyle_msg = { "restyle_data": restyle_data, "restyle_traces": trace_indexes, "trace_edit_id": trace_edit_id, "layout_edit_id": layout_edit_id, "source_view_id": source_view_id, } # Send message # ------------ self._py2js_restyle = restyle_msg self._py2js_restyle = None def _send_addTraces_msg(self, new_traces_data): """ Send Plotly.addTraces message to the frontend Parameters ---------- new_traces_data : list[dict] List of trace data for new traces as accepted by Plotly.addTraces """ # Increment layout/trace edit message IDs # --------------------------------------- layout_edit_id = self._last_layout_edit_id + 1 self._last_layout_edit_id = layout_edit_id self._layout_edit_in_process = True trace_edit_id = self._last_trace_edit_id + 1 self._last_trace_edit_id = trace_edit_id self._trace_edit_in_process = True # Build message # ------------- add_traces_msg = { "trace_data": new_traces_data, "trace_edit_id": trace_edit_id, "layout_edit_id": layout_edit_id, } # Send message # ------------ self._py2js_addTraces = add_traces_msg self._py2js_addTraces = None def _send_moveTraces_msg(self, current_inds, new_inds): """ Send Plotly.moveTraces message to the frontend Parameters ---------- current_inds : list[int] List of current trace indexes new_inds : list[int] List of new trace indexes """ # Build message # ------------- move_msg = {"current_trace_inds": current_inds, "new_trace_inds": new_inds} # Send message # ------------ self._py2js_moveTraces = move_msg self._py2js_moveTraces = None def _send_update_msg( self, restyle_data, relayout_data, trace_indexes=None, source_view_id=None ): """ Send Plotly.update message to the frontend Parameters ---------- restyle_data : dict Plotly.update restyle data relayout_data : dict Plotly.update relayout data trace_indexes : list[int] List of trace indexes that the update operation applies to source_view_id : str UID of view that triggered this update operation (e.g. By the user clicking a button). None if the operation was not triggered by a frontend view """ # Validate / normalize inputs # --------------------------- trace_indexes = self._normalize_trace_indexes(trace_indexes) # Increment layout/trace edit message IDs # --------------------------------------- trace_edit_id = self._last_trace_edit_id + 1 self._last_trace_edit_id = trace_edit_id self._trace_edit_in_process = True layout_edit_id = self._last_layout_edit_id + 1 self._last_layout_edit_id = layout_edit_id self._layout_edit_in_process = True # Build message # ------------- update_msg = { "style_data": restyle_data, "layout_data": relayout_data, "style_traces": trace_indexes, "trace_edit_id": trace_edit_id, "layout_edit_id": layout_edit_id, "source_view_id": source_view_id, } # Send message # ------------ self._py2js_update = update_msg self._py2js_update = None def _send_animate_msg( self, styles_data, relayout_data, trace_indexes, animation_opts ): """ Send Plotly.update message to the frontend Note: there is no source_view_id parameter because animations triggered by the fontend are not currently supported Parameters ---------- styles_data : list[dict] Plotly.animate styles data relayout_data : dict Plotly.animate relayout data trace_indexes : list[int] List of trace indexes that the animate operation applies to """ # Validate / normalize inputs # --------------------------- trace_indexes = self._normalize_trace_indexes(trace_indexes) # Increment layout/trace edit message IDs # --------------------------------------- trace_edit_id = self._last_trace_edit_id + 1 self._last_trace_edit_id = trace_edit_id self._trace_edit_in_process = True layout_edit_id = self._last_layout_edit_id + 1 self._last_layout_edit_id = layout_edit_id self._layout_edit_in_process = True # Build message # ------------- animate_msg = { "style_data": styles_data, "layout_data": relayout_data, "style_traces": trace_indexes, "animation_opts": animation_opts, "trace_edit_id": trace_edit_id, "layout_edit_id": layout_edit_id, "source_view_id": None, } # Send message # ------------ self._py2js_animate = animate_msg self._py2js_animate = None def _send_deleteTraces_msg(self, delete_inds): """ Send Plotly.deleteTraces message to the frontend Parameters ---------- delete_inds : list[int] List of trace indexes of traces to delete """ # Increment layout/trace edit message IDs # --------------------------------------- trace_edit_id = self._last_trace_edit_id + 1 self._last_trace_edit_id = trace_edit_id self._trace_edit_in_process = True layout_edit_id = self._last_layout_edit_id + 1 self._last_layout_edit_id = layout_edit_id self._layout_edit_in_process = True # Build message # ------------- delete_msg = { "delete_inds": delete_inds, "layout_edit_id": layout_edit_id, "trace_edit_id": trace_edit_id, } # Send message # ------------ self._py2js_deleteTraces = delete_msg self._py2js_deleteTraces = None # JavaScript -> Python Messages # ----------------------------- @observe("_js2py_traceDeltas") def _handler_js2py_traceDeltas(self, change): """ Process trace deltas message from the frontend """ # Receive message # --------------- msg_data = change["new"] if not msg_data: self._js2py_traceDeltas = None return trace_deltas = msg_data["trace_deltas"] trace_edit_id = msg_data["trace_edit_id"] # Apply deltas # ------------ # We only apply the deltas if this message corresponds to the most # recent trace edit operation if trace_edit_id == self._last_trace_edit_id: # ### Loop over deltas ### for delta in trace_deltas: # #### Find existing trace for uid ### trace_uid = delta["uid"] trace_uids = [trace.uid for trace in self.data] trace_index = trace_uids.index(trace_uid) uid_trace = self.data[trace_index] # #### Transform defaults to delta #### delta_transform = BaseFigureWidget._transform_data( uid_trace._prop_defaults, delta ) # #### Remove overlapping properties #### # If a property is present in both _props and _prop_defaults # then we remove the copy from _props remove_props = self._remove_overlapping_props( uid_trace._props, uid_trace._prop_defaults ) # #### Notify frontend model of property removal #### if remove_props: remove_trace_props_msg = { "remove_trace": trace_index, "remove_props": remove_props, } self._py2js_removeTraceProps = remove_trace_props_msg self._py2js_removeTraceProps = None # #### Dispatch change callbacks #### self._dispatch_trace_change_callbacks(delta_transform, [trace_index]) # ### Trace edits no longer in process ### self._trace_edit_in_process = False # ### Call any waiting trace edit callbacks ### if not self._layout_edit_in_process: while self._waiting_edit_callbacks: self._waiting_edit_callbacks.pop()() self._js2py_traceDeltas = None @observe("_js2py_layoutDelta") def _handler_js2py_layoutDelta(self, change): """ Process layout delta message from the frontend """ # Receive message # --------------- msg_data = change["new"] if not msg_data: self._js2py_layoutDelta = None return layout_delta = msg_data["layout_delta"] layout_edit_id = msg_data["layout_edit_id"] # Apply delta # ----------- # We only apply the delta if this message corresponds to the most # recent layout edit operation if layout_edit_id == self._last_layout_edit_id: # ### Transform defaults to delta ### delta_transform = BaseFigureWidget._transform_data( self._layout_defaults, layout_delta ) # ### Remove overlapping properties ### # If a property is present in both _layout and _layout_defaults # then we remove the copy from _layout removed_props = self._remove_overlapping_props( self._widget_layout, self._layout_defaults ) # ### Notify frontend model of property removal ### if removed_props: remove_props_msg = {"remove_props": removed_props} self._py2js_removeLayoutProps = remove_props_msg self._py2js_removeLayoutProps = None # ### Create axis objects ### # For example, when a SPLOM trace is created the layout defaults # may include axes that weren't explicitly defined by the user. for proppath in delta_transform: prop = proppath[0] match = self.layout._subplot_re_match(prop) if match and prop not in self.layout: # We need to create a subplotid object self.layout[prop] = {} # ### Dispatch change callbacks ### self._dispatch_layout_change_callbacks(delta_transform) # ### Layout edits no longer in process ### self._layout_edit_in_process = False # ### Call any waiting layout edit callbacks ### if not self._trace_edit_in_process: while self._waiting_edit_callbacks: self._waiting_edit_callbacks.pop()() self._js2py_layoutDelta = None @observe("_js2py_restyle") def _handler_js2py_restyle(self, change): """ Process Plotly.restyle message from the frontend """ # Receive message # --------------- restyle_msg = change["new"] if not restyle_msg: self._js2py_restyle = None return style_data = restyle_msg["style_data"] style_traces = restyle_msg["style_traces"] source_view_id = restyle_msg["source_view_id"] # Perform restyle # --------------- self.plotly_restyle( restyle_data=style_data, trace_indexes=style_traces, source_view_id=source_view_id, ) self._js2py_restyle = None @observe("_js2py_update") def _handler_js2py_update(self, change): """ Process Plotly.update message from the frontend """ # Receive message # --------------- update_msg = change["new"] if not update_msg: self._js2py_update = None return style = update_msg["style_data"] trace_indexes = update_msg["style_traces"] layout = update_msg["layout_data"] source_view_id = update_msg["source_view_id"] # Perform update # -------------- self.plotly_update( restyle_data=style, relayout_data=layout, trace_indexes=trace_indexes, source_view_id=source_view_id, ) self._js2py_update = None @observe("_js2py_relayout") def _handler_js2py_relayout(self, change): """ Process Plotly.relayout message from the frontend """ # Receive message # --------------- relayout_msg = change["new"] if not relayout_msg: self._js2py_relayout = None return relayout_data = relayout_msg["relayout_data"] source_view_id = relayout_msg["source_view_id"] if "lastInputTime" in relayout_data: # Remove 'lastInputTime'. Seems to be an internal plotly # property that is introduced for some plot types, but it is not # actually a property in the schema relayout_data.pop("lastInputTime") # Perform relayout # ---------------- self.plotly_relayout(relayout_data=relayout_data, source_view_id=source_view_id) self._js2py_relayout = None @observe("_js2py_pointsCallback") def _handler_js2py_pointsCallback(self, change): """ Process points callback message from the frontend """ # Receive message # --------------- callback_data = change["new"] if not callback_data: self._js2py_pointsCallback = None return # Get event type # -------------- event_type = callback_data["event_type"] # Build Selector Object # --------------------- if callback_data.get("selector", None): selector_data = callback_data["selector"] selector_type = selector_data["type"] selector_state = selector_data["selector_state"] if selector_type == "box": selector = BoxSelector(**selector_state) elif selector_type == "lasso": selector = LassoSelector(**selector_state) else: raise ValueError("Unsupported selector type: %s" % selector_type) else: selector = None # Build Input Device State Object # ------------------------------- if callback_data.get("device_state", None): device_state_data = callback_data["device_state"] state = InputDeviceState(**device_state_data) else: state = None # Build Trace Points Dictionary # ----------------------------- points_data = callback_data["points"] trace_points = { trace_ind: { "point_inds": [], "xs": [], "ys": [], "trace_name": self._data_objs[trace_ind].name, "trace_index": trace_ind, } for trace_ind in range(len(self._data_objs)) } for x, y, point_ind, trace_ind in zip( points_data["xs"], points_data["ys"], points_data["point_indexes"], points_data["trace_indexes"], ): trace_dict = trace_points[trace_ind] trace_dict["xs"].append(x) trace_dict["ys"].append(y) trace_dict["point_inds"].append(point_ind) # Dispatch callbacks # ------------------ for trace_ind, trace_points_data in trace_points.items(): points = Points(**trace_points_data) trace = self.data[trace_ind] if event_type == "plotly_click": trace._dispatch_on_click(points, state) elif event_type == "plotly_hover": trace._dispatch_on_hover(points, state) elif event_type == "plotly_unhover": trace._dispatch_on_unhover(points, state) elif event_type == "plotly_selected": trace._dispatch_on_selection(points, selector) elif event_type == "plotly_deselect": trace._dispatch_on_deselect(points) self._js2py_pointsCallback = None # Display # ------- def _repr_html_(self): """ Customize html representation """ raise NotImplementedError # Prefer _repr_mimebundle_ def _repr_mimebundle_(self, include=None, exclude=None, validate=True, **kwargs): """ Return mimebundle corresponding to default renderer. """ display_jupyter_version_warnings() # Widget layout and data need to be set here in case there are # changes made to the figure after the widget is created but before # the cell is run. self._widget_layout = deepcopy(self._layout_obj._props) self._widget_data = deepcopy(self._data) return { "application/vnd.jupyter.widget-view+json": { "version_major": 2, "version_minor": 0, "model_id": self._model_id, }, } def _ipython_display_(self): """ Handle rich display of figures in ipython contexts """ raise NotImplementedError # Prefer _repr_mimebundle_ # Callbacks # --------- def on_edits_completed(self, fn): """ Register a function to be called after all pending trace and layout edit operations have completed If there are no pending edit operations then function is called immediately Parameters ---------- fn : callable Function of zero arguments to be called when all pending edit operations have completed """ if self._layout_edit_in_process or self._trace_edit_in_process: self._waiting_edit_callbacks.append(fn) else: fn() # Validate No Frames # ------------------ @property def frames(self): # Note: This property getter is identical to that of the superclass, # but it must be included here because we're overriding the setter # below. return self._frame_objs @frames.setter def frames(self, new_frames): if new_frames: BaseFigureWidget._display_frames_error() @staticmethod def _display_frames_error(): """ Display an informative error when user attempts to set frames on a FigureWidget Raises ------ ValueError always """ msg = """ Frames are not supported by the plotly.graph_objs.FigureWidget class. Note: Frames are supported by the plotly.graph_objs.Figure class""" raise ValueError(msg) # Static Helpers # -------------- @staticmethod def _remove_overlapping_props(input_data, delta_data, prop_path=()): """ Remove properties in input_data that are also in delta_data, and do so recursively. Exception: Never remove 'uid' from input_data, this property is used to align traces Parameters ---------- input_data : dict|list delta_data : dict|list Returns ------- list[tuple[str|int]] List of removed property path tuples """ # Initialize removed # ------------------ # This is the list of path tuples to the properties that were # removed from input_data removed = [] # Handle dict # ----------- if isinstance(input_data, dict): assert isinstance(delta_data, dict) for p, delta_val in delta_data.items(): if isinstance(delta_val, dict) or BaseFigure._is_dict_list(delta_val): if p in input_data: # ### Recurse ### input_val = input_data[p] recur_prop_path = prop_path + (p,) recur_removed = BaseFigureWidget._remove_overlapping_props( input_val, delta_val, recur_prop_path ) removed.extend(recur_removed) # Check whether the last property in input_val # has been removed. If so, remove it entirely if not input_val: input_data.pop(p) removed.append(recur_prop_path) elif p in input_data and p != "uid": # ### Remove property ### input_data.pop(p) removed.append(prop_path + (p,)) # Handle list # ----------- elif isinstance(input_data, list): assert isinstance(delta_data, list) for i, delta_val in enumerate(delta_data): if i >= len(input_data): break input_val = input_data[i] if ( input_val is not None and isinstance(delta_val, dict) or BaseFigure._is_dict_list(delta_val) ): # ### Recurse ### recur_prop_path = prop_path + (i,) recur_removed = BaseFigureWidget._remove_overlapping_props( input_val, delta_val, recur_prop_path ) removed.extend(recur_removed) return removed @staticmethod def _transform_data(to_data, from_data, should_remove=True, relayout_path=()): """ Transform to_data into from_data and return relayout-style description of the transformation Parameters ---------- to_data : dict|list from_data : dict|list Returns ------- dict relayout-style description of the transformation """ # Initialize relayout data # ------------------------ relayout_data = {} # Handle dict # ----------- if isinstance(to_data, dict): # ### Validate from_data ### if not isinstance(from_data, dict): raise ValueError( "Mismatched data types: {to_dict} {from_data}".format( to_dict=to_data, from_data=from_data ) ) # ### Add/modify properties ### # Loop over props/vals for from_prop, from_val in from_data.items(): # #### Handle compound vals recursively #### if isinstance(from_val, dict) or BaseFigure._is_dict_list(from_val): # ##### Init property value if needed ##### if from_prop not in to_data: to_data[from_prop] = {} if isinstance(from_val, dict) else [] # ##### Transform property val recursively ##### input_val = to_data[from_prop] relayout_data.update( BaseFigureWidget._transform_data( input_val, from_val, should_remove=should_remove, relayout_path=relayout_path + (from_prop,), ) ) # #### Handle simple vals directly #### else: if from_prop not in to_data or not BasePlotlyType._vals_equal( to_data[from_prop], from_val ): to_data[from_prop] = from_val relayout_path_prop = relayout_path + (from_prop,) relayout_data[relayout_path_prop] = from_val # ### Remove properties ### if should_remove: for remove_prop in set(to_data.keys()).difference( set(from_data.keys()) ): to_data.pop(remove_prop) # Handle list # ----------- elif isinstance(to_data, list): # ### Validate from_data ### if not isinstance(from_data, list): raise ValueError( "Mismatched data types: to_data: {to_data} {from_data}".format( to_data=to_data, from_data=from_data ) ) # ### Add/modify properties ### # Loop over indexes / elements for i, from_val in enumerate(from_data): # #### Initialize element if needed #### if i >= len(to_data): to_data.append(None) input_val = to_data[i] # #### Handle compound element recursively #### if input_val is not None and ( isinstance(from_val, dict) or BaseFigure._is_dict_list(from_val) ): relayout_data.update( BaseFigureWidget._transform_data( input_val, from_val, should_remove=should_remove, relayout_path=relayout_path + (i,), ) ) # #### Handle simple elements directly #### else: if not BasePlotlyType._vals_equal(to_data[i], from_val): to_data[i] = from_val relayout_data[relayout_path + (i,)] = from_val return relayout_data
BaseFigureWidget
python
astropy__astropy
astropy/nddata/tests/test_nddata.py
{ "start": 13292, "end": 17400 }
class ____(MetaBaseTest): test_class = NDData args = np.array([[1.0]]) # Representation tests def test_nddata_str(): arr1d = NDData(np.array([1, 2, 3])) assert str(arr1d) == "[1 2 3]" arr2d = NDData(np.array([[1, 2], [3, 4]])) assert str(arr2d) == textwrap.dedent( """ [[1 2] [3 4]]"""[1:] ) arr3d = NDData(np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])) assert str(arr3d) == textwrap.dedent( """ [[[1 2] [3 4]] [[5 6] [7 8]]]"""[1:] ) # let's add units! arr = NDData(np.array([1, 2, 3]), unit="km") assert str(arr) == "[1 2 3] km" # what if it had these units? arr = NDData(np.array([1, 2, 3]), unit="erg cm^-2 s^-1 A^-1") assert str(arr) == "[1 2 3] erg / (A s cm2)" def test_nddata_repr(): # The big test is eval(repr()) should be equal to the original! # but this must be modified slightly since adopting the # repr machinery from astropy.utils.masked arr1d = NDData(np.array([1, 2, 3])) s = repr(arr1d) assert s == "NDData([1, 2, 3])" got = eval(s) assert np.all(got.data == arr1d.data) assert got.unit == arr1d.unit arr2d = NDData(np.array([[1, 2], [3, 4]])) s = repr(arr2d) assert s == ("NDData([[1, 2],\n [3, 4]])") got = eval(s) assert np.all(got.data == arr2d.data) assert got.unit == arr2d.unit arr3d = NDData(np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])) s = repr(arr3d) assert s == ( "NDData([[[1, 2],\n [3, 4]],\n\n [[5, 6],\n [7, 8]]])" ) got = eval(s) assert np.all(got.data == arr3d.data) assert got.unit == arr3d.unit # let's add units! arr = NDData(np.array([1, 2, 3]), unit="km") s = repr(arr) assert s == "NDData([1, 2, 3], unit='km')" got = eval(s) assert np.all(got.data == arr.data) assert got.unit == arr.unit @pytest.mark.skipif(not HAS_DASK, reason="requires dask to be available") def test_nddata_repr_dask(): import dask.array as da arr = NDData(da.arange(3), unit="km") s = repr(arr) # just check repr equality for dask arrays, not round-tripping: assert s in ( 'NDData(\n data=dask.array<arange, shape=(3,), dtype=int64, chunksize=(3,), chunktype=numpy.ndarray>,\n unit=Unit("km")\n)', 'NDData(\n data=dask.array<arange, shape=(3,), dtype=int32, chunksize=(3,), chunktype=numpy.ndarray>,\n unit=Unit("km")\n)', ) # Not supported features def test_slicing_not_supported(): ndd = NDData(np.ones((5, 5))) with pytest.raises(TypeError): ndd[0] def test_arithmetic_not_supported(): ndd = NDData(np.ones((5, 5))) with pytest.raises(TypeError): ndd + ndd def test_nddata_wcs_setter_error_cases(): ndd = NDData(np.ones((5, 5))) # Setting with a non-WCS should raise an error with pytest.raises(TypeError): ndd.wcs = "I am not a WCS" naxis = 2 # This should succeed since the WCS is currently None ndd.wcs = nd_testing._create_wcs_simple( naxis=naxis, ctype=["deg"] * naxis, crpix=[0] * naxis, crval=[10] * naxis, cdelt=[1] * naxis, ) with pytest.raises(ValueError): # This should fail since the WCS is not None ndd.wcs = nd_testing._create_wcs_simple( naxis=naxis, ctype=["deg"] * naxis, crpix=[0] * naxis, crval=[10] * naxis, cdelt=[1] * naxis, ) def test_nddata_wcs_setter_with_low_level_wcs(): ndd = NDData(np.ones((5, 5))) wcs = WCS() # If the wcs property is set with a low level WCS it should get # wrapped to high level. low_level = SlicedLowLevelWCS(wcs, 5) assert not isinstance(low_level, BaseHighLevelWCS) ndd.wcs = low_level assert isinstance(ndd.wcs, BaseHighLevelWCS) def test_nddata_init_with_low_level_wcs(): wcs = WCS() low_level = SlicedLowLevelWCS(wcs, 5) ndd = NDData(np.ones((5, 5)), wcs=low_level) assert isinstance(ndd.wcs, BaseHighLevelWCS)
TestMetaNDData
python
getsentry__sentry
src/sentry/integrations/discord/views/unlink_identity.py
{ "start": 854, "end": 1525 }
class ____(DiscordIdentityLinkageView, UnlinkIdentityView): def get_success_template_and_context( self, params: Mapping[str, Any], integration: Integration | None ) -> tuple[str, dict[str, Any]]: return "sentry/integrations/discord/unlinked.html", {} def get_analytics_event( self, provider: str, actor_id: int, actor_type: str ) -> analytics.Event | None: from sentry.integrations.discord.analytics import DiscordIntegrationIdentityUnlinked return DiscordIntegrationIdentityUnlinked( provider=provider, actor_id=actor_id, actor_type=actor_type, )
DiscordUnlinkIdentityView
python
getsentry__sentry
tests/sentry/api/helpers/test_group_index.py
{ "start": 22008, "end": 23325 }
class ____(TestCase): def setUp(self) -> None: self.group = self.create_group() self.group_list = [self.group] self.group_ids = [self.group] self.project_lookup = {self.group.project_id: self.group.project} def test_is_bookmarked(self) -> None: handle_is_bookmarked(True, self.group_list, self.project_lookup, self.user) assert GroupBookmark.objects.filter(group=self.group, user_id=self.user.id).exists() assert GroupSubscription.objects.filter( group=self.group, user_id=self.user.id, reason=GroupSubscriptionReason.bookmark ).exists() def test_not_is_bookmarked(self) -> None: GroupBookmark.objects.create( group=self.group, user_id=self.user.id, project_id=self.group.project_id ) GroupSubscription.objects.create( project=self.group.project, group=self.group, user_id=self.user.id, reason=GroupSubscriptionReason.bookmark, ) handle_is_bookmarked(False, self.group_list, self.project_lookup, self.user) assert not GroupBookmark.objects.filter(group=self.group, user_id=self.user.id).exists() assert not GroupSubscription.objects.filter(group=self.group, user_id=self.user.id).exists()
TestHandleIsBookmarked
python
pytorch__pytorch
test/jit/fixtures_srcs/fixtures_src.py
{ "start": 961, "end": 1202 }
class ____(torch.nn.Module): def forward( self, a: Union[int, float, complex], b: Union[int, float, complex], out: torch.Tensor, ): return torch.logspace(a, b, out=out)
TestVersionedLogspaceOutV8
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/view_resolve_conflict_top/package.py
{ "start": 228, "end": 933 }
class ____(Package): """Package for testing edge cases for views, such as spec ordering and clashing files referring to the same file on disk. See test_env_view_resolves_identical_file_conflicts.""" has_code = False version("0.1.0") depends_on("view-file") depends_on("view-resolve-conflict-middle") def install(self, spec, prefix): middle = spec["view-resolve-conflict-middle"].prefix bottom = spec["view-file"].prefix os.mkdir(os.path.join(prefix, "bin")) os.symlink(os.path.join(bottom, "bin", "x"), os.path.join(prefix, "bin", "x")) os.symlink(os.path.join(middle, "bin", "y"), os.path.join(prefix, "bin", "y"))
ViewResolveConflictTop
python
huggingface__transformers
src/transformers/models/vilt/modeling_vilt.py
{ "start": 17613, "end": 18269 }
class ____(nn.Module): def __init__(self, config: ViltConfig): super().__init__() self.dense = nn.Linear(config.hidden_size, config.intermediate_size) if isinstance(config.hidden_act, str): self.intermediate_act_fn = ACT2FN[config.hidden_act] else: self.intermediate_act_fn = config.hidden_act def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: hidden_states = self.dense(hidden_states) hidden_states = self.intermediate_act_fn(hidden_states) return hidden_states # Copied from transformers.models.vit.modeling_vit.ViTOutput with ViT->Vilt
ViltIntermediate
python
doocs__leetcode
solution/3600-3699/3662.Filter Characters by Frequency/Solution.py
{ "start": 0, "end": 218 }
class ____: def filterCharacters(self, s: str, k: int) -> str: cnt = Counter(s) ans = [] for c in s: if cnt[c] < k: ans.append(c) return "".join(ans)
Solution
python
pytorch__pytorch
tools/experimental/torchfuzz/operators/item.py
{ "start": 150, "end": 1475 }
class ____(Operator): """Operator for converting 0-d tensor to scalar.""" def __init__(self): super().__init__("item") @property def torch_op_name(self) -> str | None: """Item is a tensor method, not a direct torch operation.""" return None def can_produce(self, output_spec: Spec) -> bool: """Item produces scalars from 0-d tensors.""" return isinstance(output_spec, ScalarSpec) def fuzz_inputs_specs(self, output_spec: Spec, num_inputs: int = 1) -> list[Spec]: """Decompose scalar into a single-element tensor for item operation.""" if not isinstance(output_spec, ScalarSpec): raise ValueError("ItemOperator can only produce ScalarSpec outputs") # Create a tensor spec that can produce a scalar via .item() # Use a 0-D tensor (scalar tensor) to ensure .item() works reliably tensor_spec = TensorSpec(size=(), stride=(), dtype=output_spec.dtype) return [tensor_spec] def codegen( self, output_name: str, input_names: list[str], output_spec: Spec ) -> str: """Generate code for item operation.""" if len(input_names) != 1: raise ValueError("ItemOperator requires exactly one input") return f"{output_name} = {input_names[0]}.item()"
ItemOperator
python
scikit-learn__scikit-learn
asv_benchmarks/benchmarks/linear_model.py
{ "start": 2815, "end": 3592 }
class ____(Predictor, Estimator, Benchmark): """ Benchmarks for Linear Regression. """ param_names = ["representation"] params = (["dense", "sparse"],) def setup_cache(self): super().setup_cache() def make_data(self, params): (representation,) = params if representation == "dense": data = _synth_regression_dataset(n_samples=1000000, n_features=100) else: data = _synth_regression_sparse_dataset( n_samples=10000, n_features=100000, density=0.01 ) return data def make_estimator(self, params): estimator = LinearRegression() return estimator def make_scorers(self): make_gen_reg_scorers(self)
LinearRegressionBenchmark
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance6.py
{ "start": 293, "end": 328 }
class ____(Generic[_T1]): ...
ParentA
python
pypa__pip
src/pip/_vendor/rich/errors.py
{ "start": 344, "end": 422 }
class ____(ConsoleError): """Object is not renderable."""
NotRenderableError
python
huggingface__transformers
src/transformers/models/deberta/modeling_deberta.py
{ "start": 5512, "end": 14884 }
class ____(nn.Module): """ Disentangled self-attention module Parameters: config (`str`): A model config class instance with the configuration to build a new model. The schema is similar to *BertConfig*, for more details, please refer [`DebertaConfig`] """ def __init__(self, config): super().__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " f"heads ({config.num_attention_heads})" ) self.num_attention_heads = config.num_attention_heads self.attention_head_size = int(config.hidden_size / config.num_attention_heads) self.all_head_size = self.num_attention_heads * self.attention_head_size self.in_proj = nn.Linear(config.hidden_size, self.all_head_size * 3, bias=False) self.q_bias = nn.Parameter(torch.zeros((self.all_head_size), dtype=torch.float)) self.v_bias = nn.Parameter(torch.zeros((self.all_head_size), dtype=torch.float)) self.pos_att_type = config.pos_att_type if config.pos_att_type is not None else [] self.relative_attention = getattr(config, "relative_attention", False) self.talking_head = getattr(config, "talking_head", False) if self.talking_head: self.head_logits_proj = nn.Linear(config.num_attention_heads, config.num_attention_heads, bias=False) self.head_weights_proj = nn.Linear(config.num_attention_heads, config.num_attention_heads, bias=False) else: self.head_logits_proj = None self.head_weights_proj = None if self.relative_attention: self.max_relative_positions = getattr(config, "max_relative_positions", -1) if self.max_relative_positions < 1: self.max_relative_positions = config.max_position_embeddings self.pos_dropout = nn.Dropout(config.hidden_dropout_prob) if "c2p" in self.pos_att_type: self.pos_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=False) if "p2c" in self.pos_att_type: self.pos_q_proj = nn.Linear(config.hidden_size, self.all_head_size) self.dropout = nn.Dropout(config.attention_probs_dropout_prob) def transpose_for_scores(self, x): new_x_shape = x.size()[:-1] + (self.num_attention_heads, -1) x = x.view(new_x_shape) return x.permute(0, 2, 1, 3) def forward( self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: bool = False, query_states: Optional[torch.Tensor] = None, relative_pos: Optional[torch.Tensor] = None, rel_embeddings: Optional[torch.Tensor] = None, ) -> tuple[torch.Tensor, Optional[torch.Tensor]]: """ Call the module Args: hidden_states (`torch.FloatTensor`): Input states to the module usually the output from previous layer, it will be the Q,K and V in *Attention(Q,K,V)* attention_mask (`torch.BoolTensor`): An attention mask matrix of shape [*B*, *N*, *N*] where *B* is the batch size, *N* is the maximum sequence length in which element [i,j] = *1* means the *i* th token in the input can attend to the *j* th token. output_attentions (`bool`, *optional*): Whether return the attention matrix. query_states (`torch.FloatTensor`, *optional*): The *Q* state in *Attention(Q,K,V)*. relative_pos (`torch.LongTensor`): The relative position encoding between the tokens in the sequence. It's of shape [*B*, *N*, *N*] with values ranging in [*-max_relative_positions*, *max_relative_positions*]. rel_embeddings (`torch.FloatTensor`): The embedding of relative distances. It's a tensor of shape [\\(2 \\times \\text{max_relative_positions}\\), *hidden_size*]. """ if query_states is None: qp = self.in_proj(hidden_states) # .split(self.all_head_size, dim=-1) query_layer, key_layer, value_layer = self.transpose_for_scores(qp).chunk(3, dim=-1) else: ws = self.in_proj.weight.chunk(self.num_attention_heads * 3, dim=0) qkvw = [torch.cat([ws[i * 3 + k] for i in range(self.num_attention_heads)], dim=0) for k in range(3)] q = torch.matmul(qkvw[0], query_states.t().to(dtype=qkvw[0].dtype)) k = torch.matmul(qkvw[1], hidden_states.t().to(dtype=qkvw[1].dtype)) v = torch.matmul(qkvw[2], hidden_states.t().to(dtype=qkvw[2].dtype)) query_layer, key_layer, value_layer = [self.transpose_for_scores(x) for x in [q, k, v]] query_layer = query_layer + self.transpose_for_scores(self.q_bias[None, None, :]) value_layer = value_layer + self.transpose_for_scores(self.v_bias[None, None, :]) rel_att: int = 0 # Take the dot product between "query" and "key" to get the raw attention scores. scale_factor = 1 + len(self.pos_att_type) scale = scaled_size_sqrt(query_layer, scale_factor) query_layer = query_layer / scale.to(dtype=query_layer.dtype) attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) if self.relative_attention and rel_embeddings is not None and relative_pos is not None: rel_embeddings = self.pos_dropout(rel_embeddings) rel_att = self.disentangled_att_bias(query_layer, key_layer, relative_pos, rel_embeddings, scale_factor) if rel_att is not None: attention_scores = attention_scores + rel_att # bxhxlxd if self.head_logits_proj is not None: attention_scores = self.head_logits_proj(attention_scores.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) attention_mask = attention_mask.bool() attention_scores = attention_scores.masked_fill(~(attention_mask), torch.finfo(query_layer.dtype).min) # bsz x height x length x dimension attention_probs = nn.functional.softmax(attention_scores, dim=-1) attention_probs = self.dropout(attention_probs) if self.head_weights_proj is not None: attention_probs = self.head_weights_proj(attention_probs.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) context_layer = torch.matmul(attention_probs, value_layer) context_layer = context_layer.permute(0, 2, 1, 3).contiguous() new_context_layer_shape = context_layer.size()[:-2] + (-1,) context_layer = context_layer.view(new_context_layer_shape) if not output_attentions: return (context_layer, None) return (context_layer, attention_probs) def disentangled_att_bias( self, query_layer: torch.Tensor, key_layer: torch.Tensor, relative_pos: torch.Tensor, rel_embeddings: torch.Tensor, scale_factor: int, ): if relative_pos is None: relative_pos = build_relative_position(query_layer, key_layer, query_layer.device) if relative_pos.dim() == 2: relative_pos = relative_pos.unsqueeze(0).unsqueeze(0) elif relative_pos.dim() == 3: relative_pos = relative_pos.unsqueeze(1) # bxhxqxk elif relative_pos.dim() != 4: raise ValueError(f"Relative position ids must be of dim 2 or 3 or 4. {relative_pos.dim()}") att_span = compute_attention_span(query_layer, key_layer, self.max_relative_positions) relative_pos = relative_pos.long() rel_embeddings = rel_embeddings[ self.max_relative_positions - att_span : self.max_relative_positions + att_span, : ].unsqueeze(0) score = 0 # content->position if "c2p" in self.pos_att_type: pos_key_layer = self.pos_proj(rel_embeddings) pos_key_layer = self.transpose_for_scores(pos_key_layer) c2p_att = torch.matmul(query_layer, pos_key_layer.transpose(-1, -2)) c2p_pos = torch.clamp(relative_pos + att_span, 0, att_span * 2 - 1) c2p_att = torch.gather(c2p_att, dim=-1, index=c2p_dynamic_expand(c2p_pos, query_layer, relative_pos)) score += c2p_att # position->content if "p2c" in self.pos_att_type: pos_query_layer = self.pos_q_proj(rel_embeddings) pos_query_layer = self.transpose_for_scores(pos_query_layer) pos_query_layer /= scaled_size_sqrt(pos_query_layer, scale_factor) r_pos = build_rpos( query_layer, key_layer, relative_pos, ) p2c_pos = torch.clamp(-r_pos + att_span, 0, att_span * 2 - 1) p2c_att = torch.matmul(key_layer, pos_query_layer.transpose(-1, -2).to(dtype=key_layer.dtype)) p2c_att = torch.gather( p2c_att, dim=-1, index=p2c_dynamic_expand(p2c_pos, query_layer, key_layer) ).transpose(-1, -2) p2c_att = uneven_size_corrected(p2c_att, query_layer, key_layer, relative_pos) score += p2c_att return score
DisentangledSelfAttention
python
huggingface__transformers
examples/modular-transformers/modular_roberta.py
{ "start": 401, "end": 527 }
class ____(BertModel): def __init__(self, config, add_pooling_layer=True): super().__init__(self, config)
RobertaModel
python
jupyterlab__jupyterlab
packages/services/examples/typescript-browser-with-output/main.py
{ "start": 1517, "end": 2448 }
class ____(LabServerApp): extension_url = "/example" app_url = "/example" default_url = "/example" name = __name__ # In jupyter-server v2 terminals are an extension load_other_extensions = True app_name = "JupyterLab Example Service" static_dir = os.path.join(HERE, "build") templates_dir = os.path.join(HERE, "templates") app_version = version app_settings_dir = os.path.join(HERE, "build", "application_settings") schemas_dir = os.path.join(HERE, "build", "schemas") themes_dir = os.path.join(HERE, "build", "themes") user_settings_dir = os.path.join(HERE, "build", "user_settings") workspaces_dir = os.path.join(HERE, "build", "workspaces") def initialize_handlers(self): """Add example handler to Lab Server's handler list.""" self.handlers.append(("/example", ExampleHandler)) if __name__ == "__main__": ExampleApp.launch_instance()
ExampleApp
python
readthedocs__readthedocs.org
readthedocs/projects/models.py
{ "start": 65923, "end": 67358 }
class ____(TimeStampedModel, models.Model): """ Define a HTTP header for a user Domain. All the HTTPHeader(s) associated with the domain are added in the response from El Proxito. NOTE: the available headers are hardcoded in the NGINX configuration for now (see ``dockerfile/nginx/proxito.conf``) until we figure it out a way to expose them all without hardcoding them. """ HEADERS_CHOICES = ( ("access_control_allow_origin", "Access-Control-Allow-Origin"), ("access_control_allow_headers", "Access-Control-Allow-Headers"), ("access_control_expose_headers", "Access-Control-Expose-Headers"), ("content_security_policy", "Content-Security-Policy"), ("feature_policy", "Feature-Policy"), ("permissions_policy", "Permissions-Policy"), ("referrer_policy", "Referrer-Policy"), ("x_frame_options", "X-Frame-Options"), ("x_content_type_options", "X-Content-Type-Options"), ) domain = models.ForeignKey( Domain, related_name="http_headers", on_delete=models.CASCADE, ) name = models.CharField( max_length=128, choices=HEADERS_CHOICES, ) value = models.CharField(max_length=4096) only_if_secure_request = models.BooleanField( help_text="Only set this header if the request is secure (HTTPS)", ) def __str__(self): return self.name
HTTPHeader
python
allegroai__clearml
clearml/utilities/pyhocon/exceptions.py
{ "start": 0, "end": 163 }
class ____(Exception): def __init__(self, message, ex=None): super(ConfigException, self).__init__(message) self._exception = ex
ConfigException
python
plotly__plotly.py
plotly/graph_objs/parcoords/_unselected.py
{ "start": 233, "end": 2420 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "parcoords" _path_str = "parcoords.unselected" _valid_props = {"line"} @property def line(self): """ The 'line' property is an instance of Line that may be specified as: - An instance of :class:`plotly.graph_objs.parcoords.unselected.Line` - A dict of string/value properties that will be passed to the Line constructor Returns ------- plotly.graph_objs.parcoords.unselected.Line """ return self["line"] @line.setter def line(self, val): self["line"] = val @property def _prop_descriptions(self): return """\ line :class:`plotly.graph_objects.parcoords.unselected.Line` instance or dict with compatible properties """ def __init__(self, arg=None, line=None, **kwargs): """ Construct a new Unselected object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.parcoords.Unselected` line :class:`plotly.graph_objects.parcoords.unselected.Line` instance or dict with compatible properties Returns ------- Unselected """ super().__init__("unselected") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.parcoords.Unselected constructor must be a dict or an instance of :class:`plotly.graph_objs.parcoords.Unselected`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("line", arg, line) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Unselected
python
huggingface__transformers
tests/models/sam2/test_image_processing_sam2.py
{ "start": 3516, "end": 9873 }
class ____(ImageProcessingTestMixin, unittest.TestCase): fast_image_processing_class = Sam2ImageProcessorFast if is_torchvision_available() else None test_slow_image_processor = False def setUp(self): super().setUp() self.image_processor_tester = Sam2ImageProcessingTester(self) @property def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() def test_image_processor_properties(self): for image_processing_class in self.image_processor_list: image_processing = image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(image_processing, "image_mean")) self.assertTrue(hasattr(image_processing, "image_std")) self.assertTrue(hasattr(image_processing, "do_normalize")) self.assertTrue(hasattr(image_processing, "do_resize")) self.assertTrue(hasattr(image_processing, "size")) self.assertTrue(hasattr(image_processing, "do_rescale")) self.assertTrue(hasattr(image_processing, "rescale_factor")) self.assertTrue(hasattr(image_processing, "mask_size")) def test_image_processor_from_dict_with_kwargs(self): for image_processing_class in self.image_processor_list: image_processing_class = image_processing_class(**self.image_processor_dict) image_processor = image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size, {"height": 20, "width": 20}) image_processor = image_processing_class.from_dict(self.image_processor_dict, size=42) self.assertEqual(image_processor.size, {"height": 42, "width": 42}) def test_call_segmentation_maps(self): for image_processing_class in self.image_processor_list: # Initialize image_processor image_processor = image_processing_class(**self.image_processor_dict) # create random PyTorch tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) maps = [] for image in image_inputs: self.assertIsInstance(image, torch.Tensor) maps.append(torch.zeros(image.shape[-2:]).long()) # Test not batched input encoding = image_processor(image_inputs[0], maps[0], return_tensors="pt") self.assertEqual( encoding["pixel_values"].shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ), ) self.assertEqual( encoding["labels"].shape, ( 1, self.image_processor_tester.mask_size["height"], self.image_processor_tester.mask_size["width"], ), ) self.assertEqual(encoding["labels"].dtype, torch.long) self.assertTrue(encoding["labels"].min().item() >= 0) self.assertTrue(encoding["labels"].max().item() <= 255) # Test batched encoding = image_processor(image_inputs, maps, return_tensors="pt") self.assertEqual( encoding["pixel_values"].shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ), ) self.assertEqual( encoding["labels"].shape, ( self.image_processor_tester.batch_size, self.image_processor_tester.mask_size["height"], self.image_processor_tester.mask_size["width"], ), ) self.assertEqual(encoding["labels"].dtype, torch.long) self.assertTrue(encoding["labels"].min().item() >= 0) self.assertTrue(encoding["labels"].max().item() <= 255) # Test not batched input (PIL images) image, segmentation_map = prepare_semantic_single_inputs() encoding = image_processor(image, segmentation_map, return_tensors="pt") self.assertEqual( encoding["pixel_values"].shape, ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ), ) self.assertEqual( encoding["labels"].shape, ( 1, self.image_processor_tester.mask_size["height"], self.image_processor_tester.mask_size["width"], ), ) self.assertEqual(encoding["labels"].dtype, torch.long) self.assertTrue(encoding["labels"].min().item() >= 0) self.assertTrue(encoding["labels"].max().item() <= 255) # Test batched input (PIL images) images, segmentation_maps = prepare_semantic_batch_inputs() encoding = image_processor(images, segmentation_maps, return_tensors="pt") self.assertEqual( encoding["pixel_values"].shape, ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ), ) self.assertEqual( encoding["labels"].shape, ( 2, self.image_processor_tester.mask_size["height"], self.image_processor_tester.mask_size["width"], ), ) self.assertEqual(encoding["labels"].dtype, torch.long) self.assertTrue(encoding["labels"].min().item() >= 0) self.assertTrue(encoding["labels"].max().item() <= 255)
SamImageProcessingTest
python
kamyu104__LeetCode-Solutions
Python/rotated-digits.py
{ "start": 1629, "end": 2051 }
class ____(object): def rotatedDigits(self, N): """ :type N: int :rtype: int """ invalid, diff = set(['3', '4', '7']), set(['2', '5', '6', '9']) result = 0 for i in xrange(N+1): lookup = set(list(str(i))) if invalid & lookup: continue if diff & lookup: result += 1 return result
Solution3