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
microsoft__pyright
packages/pyright-internal/src/tests/samples/paramSpec25.py
{ "start": 226, "end": 305 }
class ____: ... CommandHandler = Callable[Concatenate[Context, P], Any]
Context
python
Unity-Technologies__ml-agents
ml-agents/mlagents/trainers/tests/simple_test_envs.py
{ "start": 22695, "end": 22957 }
class ____(SimpleEnvironment): def __init__(self, brain_names, use_discrete, to_raise): super().__init__(brain_names, use_discrete) self.to_raise = to_raise def step(self) -> None: raise self.to_raise()
UnexpectedExceptionEnvironment
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 149400, "end": 149950 }
class ____(BaseModel, extra="forbid"): hnsw_config: Optional["HnswConfigDiff"] = Field( default=None, description="Update params for HNSW index. If empty object - it will be unset." ) quantization_config: Optional["QuantizationConfigDiff"] = Field( default=None, description="Update params for quantization. If none - it is left unchanged." ) on_disk: Optional[bool] = Field( default=None, description="If true, vectors are served from disk, improving RAM usage at the cost of latency" )
VectorParamsDiff
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 18143, "end": 18371 }
class ____(BaseModel): vectors: int = Field(..., description="") optimizers_status: "OptimizersStatus" = Field(..., description="") params: "CollectionParams" = Field(..., description="")
CollectionsAggregatedTelemetry
python
pypa__pip
src/pip/_vendor/tomli_w/_writer.py
{ "start": 892, "end": 6961 }
class ____: def __init__(self, allow_multiline: bool, indent: int): if indent < 0: raise ValueError("Indent width must be non-negative") self.allow_multiline: Final = allow_multiline # cache rendered inline tables (mapping from object id to rendered inline table) self.inline_table_cache: Final[dict[int, str]] = {} self.indent_str: Final = " " * indent def dump( obj: Mapping[str, Any], fp: IO[bytes], /, *, multiline_strings: bool = False, indent: int = 4, ) -> None: ctx = Context(multiline_strings, indent) for chunk in gen_table_chunks(obj, ctx, name=""): fp.write(chunk.encode()) def dumps( obj: Mapping[str, Any], /, *, multiline_strings: bool = False, indent: int = 4 ) -> str: ctx = Context(multiline_strings, indent) return "".join(gen_table_chunks(obj, ctx, name="")) def gen_table_chunks( table: Mapping[str, Any], ctx: Context, *, name: str, inside_aot: bool = False, ) -> Generator[str, None, None]: yielded = False literals = [] tables: list[tuple[str, Any, bool]] = [] # => [(key, value, inside_aot)] for k, v in table.items(): if isinstance(v, Mapping): tables.append((k, v, False)) elif is_aot(v) and not all(is_suitable_inline_table(t, ctx) for t in v): tables.extend((k, t, True) for t in v) else: literals.append((k, v)) if inside_aot or name and (literals or not tables): yielded = True yield f"[[{name}]]\n" if inside_aot else f"[{name}]\n" if literals: yielded = True for k, v in literals: yield f"{format_key_part(k)} = {format_literal(v, ctx)}\n" for k, v, in_aot in tables: if yielded: yield "\n" else: yielded = True key_part = format_key_part(k) display_name = f"{name}.{key_part}" if name else key_part yield from gen_table_chunks(v, ctx, name=display_name, inside_aot=in_aot) def format_literal(obj: object, ctx: Context, *, nest_level: int = 0) -> str: if isinstance(obj, bool): return "true" if obj else "false" if isinstance(obj, (int, float, date, datetime)): return str(obj) if isinstance(obj, time): if obj.tzinfo: raise ValueError("TOML does not support offset times") return str(obj) if isinstance(obj, str): return format_string(obj, allow_multiline=ctx.allow_multiline) if isinstance(obj, ARRAY_TYPES): return format_inline_array(obj, ctx, nest_level) if isinstance(obj, Mapping): return format_inline_table(obj, ctx) # Lazy import to improve module import time from decimal import Decimal if isinstance(obj, Decimal): return format_decimal(obj) raise TypeError( f"Object of type '{type(obj).__qualname__}' is not TOML serializable" ) def format_decimal(obj: Decimal) -> str: if obj.is_nan(): return "nan" if obj.is_infinite(): return "-inf" if obj.is_signed() else "inf" dec_str = str(obj).lower() return dec_str if "." in dec_str or "e" in dec_str else dec_str + ".0" def format_inline_table(obj: Mapping, ctx: Context) -> str: # check cache first obj_id = id(obj) if obj_id in ctx.inline_table_cache: return ctx.inline_table_cache[obj_id] if not obj: rendered = "{}" else: rendered = ( "{ " + ", ".join( f"{format_key_part(k)} = {format_literal(v, ctx)}" for k, v in obj.items() ) + " }" ) ctx.inline_table_cache[obj_id] = rendered return rendered def format_inline_array(obj: tuple | list, ctx: Context, nest_level: int) -> str: if not obj: return "[]" item_indent = ctx.indent_str * (1 + nest_level) closing_bracket_indent = ctx.indent_str * nest_level return ( "[\n" + ",\n".join( item_indent + format_literal(item, ctx, nest_level=nest_level + 1) for item in obj ) + f",\n{closing_bracket_indent}]" ) def format_key_part(part: str) -> str: try: only_bare_key_chars = BARE_KEY_CHARS.issuperset(part) except TypeError: raise TypeError( f"Invalid mapping key '{part}' of type '{type(part).__qualname__}'." " A string is required." ) from None if part and only_bare_key_chars: return part return format_string(part, allow_multiline=False) def format_string(s: str, *, allow_multiline: bool) -> str: do_multiline = allow_multiline and "\n" in s if do_multiline: result = '"""\n' s = s.replace("\r\n", "\n") else: result = '"' pos = seq_start = 0 while True: try: char = s[pos] except IndexError: result += s[seq_start:pos] if do_multiline: return result + '"""' return result + '"' if char in ILLEGAL_BASIC_STR_CHARS: result += s[seq_start:pos] if char in COMPACT_ESCAPES: if do_multiline and char == "\n": result += "\n" else: result += COMPACT_ESCAPES[char] else: result += "\\u" + hex(ord(char))[2:].rjust(4, "0") seq_start = pos + 1 pos += 1 def is_aot(obj: Any) -> bool: """Decides if an object behaves as an array of tables (i.e. a nonempty list of dicts).""" return bool( isinstance(obj, ARRAY_TYPES) and obj and all(isinstance(v, Mapping) for v in obj) ) def is_suitable_inline_table(obj: Mapping, ctx: Context) -> bool: """Use heuristics to decide if the inline-style representation is a good choice for a given table.""" rendered_inline = f"{ctx.indent_str}{format_inline_table(obj, ctx)}," return len(rendered_inline) <= MAX_LINE_LENGTH and "\n" not in rendered_inline
Context
python
python-openxml__python-docx
src/docx/image/tiff.py
{ "start": 9187, "end": 9706 }
class ____(_IfdEntry): """IFD entry expressed as a long (4-byte) integer.""" @classmethod def _parse_value(cls, stream_rdr, offset, value_count, value_offset): """Return the long int value contained in the `value_offset` field of this entry. Only supports single values at present. """ if value_count == 1: return stream_rdr.read_long(offset, 8) else: # pragma: no cover return "Multi-value long integer NOT IMPLEMENTED"
_LongIfdEntry
python
sqlalchemy__sqlalchemy
test/sql/test_roles.py
{ "start": 1766, "end": 11261 }
class ____(fixtures.TestBase): # TODO: the individual role tests here are incomplete. The functionality # of each role is covered by other tests in the sql testing suite however # ideally they'd all have direct tests here as well. def _test_role_neg_comparisons(self, role): impl = coercions._impl_lookup[role] role_name = impl.name assert_raises_message( exc.ArgumentError, r"%s expected, got .*NotAThing1" % role_name, expect, role, not_a_thing1, ) assert_raises_message( exc.ArgumentError, r"%s expected, got .*NotAThing2" % role_name, expect, role, not_a_thing2, ) assert_raises_message( exc.ArgumentError, r"%s expected, got .*NotAThing3" % role_name, expect, role, not_a_thing3, ) assert_raises_message( exc.ArgumentError, r"%s expected for argument 'foo'; got .*NotAThing3" % role_name, expect, role, not_a_thing3, argname="foo", ) def test_const_expr_role(self): t = true() is_(expect(roles.ConstExprRole, t), t) f = false() is_(expect(roles.ConstExprRole, f), f) is_instance_of(expect(roles.ConstExprRole, True), True_) is_instance_of(expect(roles.ConstExprRole, False), False_) is_instance_of(expect(roles.ConstExprRole, None), Null) def test_truncated_label_role(self): is_instance_of( expect(roles.TruncatedLabelRole, "foobar"), _truncated_label ) def test_labeled_column_expr_role(self): c = column("q") is_true(expect(roles.LabeledColumnExprRole, c).compare(c)) is_true( expect(roles.LabeledColumnExprRole, c.label("foo")).compare( c.label("foo") ) ) is_true( expect( roles.LabeledColumnExprRole, select(column("q")).scalar_subquery(), ).compare(select(column("q")).label(None)) ) is_true( expect(roles.LabeledColumnExprRole, not_a_thing1).compare( literal(not_a_thing1).label(None) ) ) def test_untyped_scalar_subquery(self): """test for :ticket:`6181`""" c = column("q") subq = select(c).scalar_subquery() assert isinstance( subq._with_binary_element_type(Integer()), ScalarSelect ) expr = column("a", Integer) == subq assert isinstance(expr.right, ScalarSelect) def test_no_clauseelement_in_bind(self): with testing.expect_raises_message( exc.ArgumentError, r"Literal Python value expected, got BindParameter", ): literal(bindparam("x")) with testing.expect_raises_message( exc.ArgumentError, r"Literal Python value expected, got .*ColumnClause", ): literal(column("q")) def test_scalar_select_no_coercion(self): with testing.expect_warnings( "implicitly coercing SELECT object to scalar subquery" ): expect( roles.LabeledColumnExprRole, select(column("q")), ) with testing.expect_warnings( "implicitly coercing SELECT object to scalar subquery" ): expect( roles.LabeledColumnExprRole, select(column("q")).alias(), ) def test_values_advice(self): value_expr = values( column("id", Integer), column("name", String), name="my_values" ).data([(1, "name1"), (2, "name2"), (3, "name3")]) assert_raises_message( exc.ArgumentError, r"SQL expression element expected, got <.*Values.*my_values>. To " r"create a " r"column expression from a VALUES clause, " r"use the .scalar_values\(\) method.", expect, roles.ExpressionElementRole, value_expr, ) def test_table_valued_advice(self): msg = ( r"SQL expression element expected, got %s. To create a " r"column expression from a FROM clause row as a whole, " r"use the .table_valued\(\) method." ) assert_raises_message( exc.ArgumentError, msg % ("Table.*",), expect, roles.ExpressionElementRole, t, ) # no table_valued() message here right now, it goes to scalar subquery with testing.expect_warnings( "implicitly coercing SELECT object to scalar subquery" ): expect(roles.ExpressionElementRole, t.select().alias()) def test_raise_on_regular_python_obj_for_expr(self): """test #6350""" def some_function(): pass class Thing: def __clause_element__(self): return some_function with testing.expect_raises_message( exc.ArgumentError, r"SQL expression element expected, got " "<function .*some_function .* resolved from <.*Thing object .*", ): expect(roles.ExpressionElementRole, Thing()) def test_no_statement_text_coercion(self): with testing.expect_raises_message( exc.ArgumentError, r"Textual SQL expression 'select \* from table' should be " "explicitly declared", ): expect(roles.StatementRole, "select * from table") def test_select_statement_no_text_coercion(self): assert_raises_message( exc.ArgumentError, r"Textual SQL expression 'select \* from table' should be " r"explicitly declared", expect, roles.SelectStatementRole, "select * from table", ) def test_select_is_coerced_into_fromclause_w_deprecation(self): with testing.expect_raises_message( exc.ArgumentError, r"FROM expression, such as a Table or alias\(\) object expected", ): expect(roles.FromClauseRole, SelectStatementGrouping(select(t))) def test_offset_or_limit_role_only_ints_or_clauseelement(self): assert_raises(ValueError, select(t).limit, "some limit") assert_raises(ValueError, select(t).offset, "some offset") def test_offset_or_limit_role_clauseelement(self): bind = bindparam("x") stmt = select(t).limit(bind) is_(stmt._limit_clause, bind) stmt = select(t).offset(bind) is_(stmt._offset_clause, bind) def test_from_clause_is_not_a_select(self): assert_raises_message( exc.ArgumentError, r"SELECT construct or equivalent text\(\) construct expected,", expect, roles.SelectStatementRole, FromGrouping(t), ) def test_text_as_from_select_statement(self): is_true( expect( roles.SelectStatementRole, text("select * from table").columns(t.c.q), ).compare(text("select * from table").columns(t.c.q)) ) def test_statement_coercion_select(self): is_true(expect(roles.StatementRole, select(t)).compare(select(t))) def test_statement_coercion_ddl(self): d1 = DDL("hi") is_(expect(roles.StatementRole, d1), d1) def test_from_clause_role(self): stmt = select(t).subquery() is_true( expect(roles.FromClauseRole, stmt).compare(select(t).subquery()) ) def test_from_clause_role_disallow_select(self): stmt = select(t) assert_raises_message( exc.ArgumentError, r"FROM expression, such as a Table or alias\(\) " "object expected, got .*Select", expect, roles.FromClauseRole, stmt, ) def test_anonymized_from_clause_role(self): is_true(expect(roles.AnonymizedFromClauseRole, t).compare(t.alias())) # note the compare for subquery().alias(), even if it is two # plain Alias objects (which it won't be once we introduce the # Subquery class), still compares based on alias() being present # twice, that is, alias().alias() builds an alias of an alias, rather # than just replacing the outer alias. is_true( expect( roles.AnonymizedFromClauseRole, select(t).subquery() ).compare(select(t).subquery().alias()) ) def test_statement_coercion_sequence(self): s1 = Sequence("hi") is_(expect(roles.StatementRole, s1), s1) def test_columns_clause_role(self): is_(expect(roles.ColumnsClauseRole, t.c.q), t.c.q) def test_truncated_label_role_neg(self): self._test_role_neg_comparisons(roles.TruncatedLabelRole) def test_where_having_role_neg(self): self._test_role_neg_comparisons(roles.WhereHavingRole) def test_by_of_role_neg(self): self._test_role_neg_comparisons(roles.ByOfRole) def test_const_expr_role_neg(self): self._test_role_neg_comparisons(roles.ConstExprRole) def test_columns_clause_role_neg(self): self._test_role_neg_comparisons(roles.ColumnsClauseRole)
RoleTest
python
pallets__werkzeug
src/werkzeug/datastructures/cache_control.py
{ "start": 7250, "end": 9711 }
class ____(_CacheControl): """A cache control for responses. Unlike :class:`RequestCacheControl` this is mutable and gives access to response-relevant cache control headers. To get a header of the :class:`ResponseCacheControl` object again you can convert the object into a string or call the :meth:`to_header` method. If you plan to subclass it and add your own items have a look at the sourcecode for that class. .. versionchanged:: 3.1 Dict values are always ``str | None``. Setting properties will convert the value to a string. Setting a non-bool property to ``False`` is equivalent to setting it to ``None``. Getting typed properties will return ``None`` if conversion raises ``ValueError``, rather than the string. .. versionchanged:: 3.1 ``no_cache`` is ``True`` if present without a value, rather than ``"*"``. .. versionchanged:: 3.1 ``private`` is ``True`` if present without a value, rather than ``"*"``. .. versionchanged:: 3.1 ``no_transform`` is a boolean. Previously it was mistakenly always ``None``. .. versionchanged:: 3.1 Added the ``must_understand``, ``stale_while_revalidate``, and ``stale_if_error`` properties. .. versionchanged:: 2.1.1 ``s_maxage`` converts the value to an int. .. versionchanged:: 2.1 Setting int properties such as ``max_age`` will convert the value to an int. .. versionadded:: 0.5 Request-only properties are not present on this response class. """ no_cache: str | t.Literal[True] | None = cache_control_property( "no-cache", True, None ) public: bool = cache_control_property("public", None, bool) private: str | t.Literal[True] | None = cache_control_property( "private", True, None ) must_revalidate: bool = cache_control_property("must-revalidate", None, bool) proxy_revalidate: bool = cache_control_property("proxy-revalidate", None, bool) s_maxage: int | None = cache_control_property("s-maxage", None, int) immutable: bool = cache_control_property("immutable", None, bool) must_understand: bool = cache_control_property("must-understand", None, bool) stale_while_revalidate: int | None = cache_control_property( "stale-while-revalidate", None, int ) # circular dependencies from .. import http # noqa: E402
ResponseCacheControl
python
doocs__leetcode
solution/0300-0399/0343.Integer Break/Solution.py
{ "start": 0, "end": 233 }
class ____: def integerBreak(self, n: int) -> int: f = [1] * (n + 1) for i in range(2, n + 1): for j in range(1, i): f[i] = max(f[i], f[i - j] * j, (i - j) * j) return f[n]
Solution
python
pytorch__pytorch
benchmarks/gpt_fast/mixtral_moe_model.py
{ "start": 313, "end": 1716 }
class ____: block_size: int = 2048 vocab_size: int = 32000 n_layer: int = 32 n_head: int = 32 dim: int = 4096 intermediate_size: int = None n_local_heads: int = -1 head_dim: int = 64 rope_base: float = 10000 norm_eps: float = 1e-5 num_experts: int = 8 num_activated_experts: int = 2 def __post_init__(self): if self.n_local_heads == -1: self.n_local_heads = self.n_head if self.intermediate_size is None: hidden_dim = 4 * self.dim n_hidden = int(2 * hidden_dim / 3) self.intermediate_size = find_multiple(n_hidden, 256) self.head_dim = self.dim // self.n_head @classmethod def from_name(cls, name: str): if name in transformer_configs: return cls(**transformer_configs[name]) # fuzzy search config = [ config for config in transformer_configs if config in str(name).upper() or config in str(name) ] assert len(config) == 1, name return cls(**transformer_configs[config[0]]) transformer_configs = { "Mixtral-8x7B-v0.1": dict( block_size=32768, n_layer=16, n_head=32, n_local_heads=8, dim=4096, intermediate_size=14336, rope_base=1000000.0, num_experts=8, num_activated_experts=2, ), }
ModelArgs
python
apache__airflow
providers/pagerduty/src/airflow/providers/pagerduty/hooks/pagerduty_events.py
{ "start": 2730, "end": 9262 }
class ____(BaseHook): """ This class can be used to interact with the Pagerduty Events API. It takes both an Events API token and a PagerDuty connection with the Events API token (i.e. Integration key) as the password/Pagerduty API token. If both supplied, the token will be used. :param integration_key: PagerDuty Events API token :param pagerduty_events_conn_id: connection that has PagerDuty integration key in the Pagerduty API token field """ conn_name_attr = "pagerduty_events_conn_id" default_conn_name = "pagerduty_events_default" conn_type = "pagerduty_events" hook_name = "Pagerduty Events" @classmethod def get_ui_field_behaviour(cls) -> dict[str, Any]: """Return custom field behaviour.""" return { "hidden_fields": ["port", "login", "schema", "host", "extra"], "relabeling": { "password": "Pagerduty Integration key", }, } def __init__( self, integration_key: str | None = None, pagerduty_events_conn_id: str | None = None ) -> None: super().__init__() self.integration_key = "" self._client = None if pagerduty_events_conn_id is not None: conn = self.get_connection(pagerduty_events_conn_id) password = conn.password if password is not None: self.integration_key = password if integration_key is not None: # token takes higher priority self.integration_key = integration_key if self.integration_key == "": raise AirflowException( "Cannot get token: No valid integration key nor pagerduty_events_conn_id supplied." ) def send_event( self, summary: str, severity: str, source: str = "airflow", action: str = "trigger", dedup_key: str | None = None, custom_details: Any | None = None, group: str | None = None, component: str | None = None, class_type: str | None = None, images: list[Any] | None = None, links: list[Any] | None = None, ) -> str: """ Create event for service integration. :param summary: Summary for the event :param severity: Severity for the event, needs to be one of: info, warning, error, critical :param source: Specific human-readable unique identifier, such as a hostname, for the system having the problem. :param action: Event action, needs to be one of: trigger, acknowledge, resolve. Default to trigger if not specified. :param dedup_key: A string which identifies the alert triggered for the given event. Required for the actions acknowledge and resolve. :param custom_details: Free-form details from the event. Can be a dictionary or a string. If a dictionary is passed it will show up in PagerDuty as a table. :param group: A cluster or grouping of sources. For example, sources "prod-datapipe-02" and "prod-datapipe-03" might both be part of "prod-datapipe" :param component: The part or component of the affected system that is broken. :param class_type: The class/type of the event. :param images: List of images to include. Each dictionary in the list accepts the following keys: `src`: The source (URL) of the image being attached to the incident. This image must be served via HTTPS. `href`: [Optional] URL to make the image a clickable link. `alt`: [Optional] Alternative text for the image. :param links: List of links to include. Each dictionary in the list accepts the following keys: `href`: URL of the link to be attached. `text`: [Optional] Plain text that describes the purpose of the link, and can be used as the link's text. :return: PagerDuty Events API v2 response. """ data = prepare_event_data( summary=summary, severity=severity, source=source, custom_details=custom_details, component=component, group=group, class_type=class_type, action=action, dedup_key=dedup_key, images=images, links=links, ) client = pagerduty.EventsApiV2Client(self.integration_key) return client.send_event(**data) def create_change_event( self, summary: str, source: str = "airflow", custom_details: Any | None = None, timestamp: datetime | None = None, links: list[Any] | None = None, ) -> str: """ Create change event for service integration. :param summary: Summary for the event :param source: Specific human-readable unique identifier, such as a hostname, for the system having the problem. :param custom_details: Free-form details from the event. Can be a dictionary or a string. If a dictionary is passed it will show up in PagerDuty as a table. :param timestamp: The time at which the emitting tool detected or generated the event. :param links: List of links to include. Each dictionary in the list accepts the following keys: `href`: URL of the link to be attached. `text`: [Optional] Plain text that describes the purpose of the link, and can be used as the link's text. :return: PagerDuty Change Events API v2 response. """ payload = { "summary": summary, } if custom_details is not None: payload["custom_details"] = custom_details if timestamp is not None: payload["timestamp"] = timestamp.isoformat() if source is not None: payload["source"] = source data: dict[str, Any] = {"payload": payload} if links is not None: data["links"] = links client = pagerduty.EventsApiV2Client(self.integration_key) return client.send_change_event(payload=payload, links=links) def test_connection(self): try: client = pagerduty.EventsApiV2Client(self.integration_key) client.resolve("some_dedup_key_that_dont_exist") except Exception: return False, "connection test failed, invalid routing key" return True, "connection tested successfully"
PagerdutyEventsHook
python
joke2k__faker
tests/providers/test_job.py
{ "start": 2458, "end": 2647 }
class ____: """Test el_GR job provider""" def test_job(self, faker, num_samples): for _ in range(num_samples): assert faker.job() in ElGrJobProvider.jobs
TestElGr
python
conda__conda
conda/cli/install.py
{ "start": 5892, "end": 7997 }
class ____: def __init__( self, notify_success, repodata, last_repodata, index_args, allowed_errors ): self.notify_success = notify_success self.repodata = repodata self.last_repodata = last_repodata self.index_args = index_args self.allowed_errors = allowed_errors def __enter__(self): return self.repodata def __exit__(self, exc_type, exc_value, traceback): if not exc_value: self.notify_success() # Swallow the error to allow for the next repodata to be tried if: # 1. the error is in the 'allowed_errors' type # 2. there are more repodatas to try AND # 3. the error says it's okay to retry # # TODO: Regarding (3) This is a temporary workaround to allow downstream libraries # to inject this attribute set to False and skip the retry logic # Other solvers might implement their own internal retry logic without # depending --freeze-install implicitly like conda classic does. Example # retry loop in conda-libmamba-solver: # https://github.com/conda-incubator/conda-libmamba-solver/blob/da5b1ba/conda_libmamba_solver/solver.py#L254-L299 # If we end up raising UnsatisfiableError, we annotate it with `allow_retry` # so we don't have go through all the repodatas and freeze-installed logic # unnecessarily (see https://github.com/conda/conda/issues/11294). see also: # https://github.com/conda-incubator/conda-libmamba-solver/blob/7c698209/conda_libmamba_solver/solver.py#L617 if ( isinstance(exc_value, self.allowed_errors) and (self.repodata != self.last_repodata) and getattr(exc_value, "allow_retry", True) ): return True elif isinstance(exc_value, ResolvePackageNotFound): # convert the ResolvePackageNotFound into PackagesNotFoundError raise PackagesNotFoundError( exc_value._formatted_chains, all_channel_urls(context.channels), )
TryRepodata
python
allegroai__clearml
clearml/backend_api/services/v2_20/workers.py
{ "start": 86280, "end": 86857 }
class ____(Response): """ Response of workers.unregister endpoint. """ _service = "workers" _action = "unregister" _version = "2.20" _schema = {"definitions": {}, "properties": {}, "type": "object"} response_mapping = { GetAllRequest: GetAllResponse, RegisterRequest: RegisterResponse, UnregisterRequest: UnregisterResponse, StatusReportRequest: StatusReportResponse, GetMetricKeysRequest: GetMetricKeysResponse, GetStatsRequest: GetStatsResponse, GetActivityReportRequest: GetActivityReportResponse, }
UnregisterResponse
python
python-openxml__python-docx
tests/oxml/unitdata/styles.py
{ "start": 250, "end": 449 }
class ____(BaseBuilder): __tag__ = "w:styles" __nspfxs__ = ("w",) __attrs__ = () def a_style(): return CT_StyleBuilder() def a_styles(): return CT_StylesBuilder()
CT_StylesBuilder
python
pytorch__pytorch
test/package/package_a/test_module.py
{ "start": 744, "end": 1071 }
class ____(torch.nn.Module): def __init__(self, tensor, sub_mod_0, sub_mod_1): super().__init__() self.tensor = tensor self.sub_mod_0 = sub_mod_0 self.sub_mod_1 = sub_mod_1 def forward(self, x): return self.sub_mod_0(x) + self.sub_mod_1(x) + self.tensor
ModWithTwoSubmodsAndTensor
python
huggingface__transformers
src/transformers/models/instructblip/modeling_instructblip.py
{ "start": 24028, "end": 27398 }
class ____(GradientCheckpointingLayer): def __init__(self, config, layer_idx): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = InstructBlipQFormerAttention(config) self.layer_idx = layer_idx if layer_idx % config.cross_attention_frequency == 0: self.crossattention = InstructBlipQFormerAttention(config, is_cross_attention=True) self.has_cross_attention = True else: self.has_cross_attention = False self.intermediate = InstructBlipQFormerIntermediate(config) self.output = InstructBlipQFormerOutput(config) self.intermediate_query = InstructBlipQFormerIntermediate(config) self.output_query = InstructBlipQFormerOutput(config) def forward( self, hidden_states, attention_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, query_length=0, **kwargs: Unpack[TransformersKwargs], ): attention_output = self.attention( hidden_states, attention_mask=attention_mask, **kwargs, ) if query_length > 0: query_attention_output = attention_output[:, :query_length, :] if self.has_cross_attention: if encoder_hidden_states is None: raise ValueError("encoder_hidden_states must be given for cross-attention layers") query_attention_output = self.crossattention( query_attention_output, attention_mask=attention_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, **kwargs, ) layer_output = apply_chunking_to_forward( self.feed_forward_chunk_query, self.chunk_size_feed_forward, self.seq_len_dim, query_attention_output, ) if attention_output.shape[1] > query_length: layer_output_text = apply_chunking_to_forward( self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output[:, query_length:, :], ).to(layer_output.device) layer_output = torch.cat([layer_output, layer_output_text], dim=1) else: layer_output = apply_chunking_to_forward( self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output, ) return layer_output def feed_forward_chunk(self, attention_output): intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) return layer_output def feed_forward_chunk_query(self, attention_output): intermediate_output = self.intermediate_query(attention_output) layer_output = self.output_query(intermediate_output, attention_output) return layer_output # Copied from transformers.models.blip_2.modeling_blip_2.Blip2QFormerEncoder with Blip2->InstructBlip
InstructBlipQFormerLayer
python
pytorch__pytorch
test/test_futures.py
{ "start": 344, "end": 10515 }
class ____(TestCase): def test_set_exception(self) -> None: # This test is to ensure errors can propagate across futures. error_msg = "Intentional Value Error" value_error = ValueError(error_msg) f = Future[T]() # type: ignore[valid-type] # Set exception f.set_exception(value_error) # Exception should throw on wait with self.assertRaisesRegex(ValueError, "Intentional"): f.wait() # Exception should also throw on value f = Future[T]() # type: ignore[valid-type] f.set_exception(value_error) with self.assertRaisesRegex(ValueError, "Intentional"): f.value() def cb(fut): fut.value() f = Future[T]() # type: ignore[valid-type] f.set_exception(value_error) with self.assertRaisesRegex(RuntimeError, "Got the following error"): cb_fut = f.then(cb) cb_fut.wait() def test_set_exception_multithreading(self) -> None: # Ensure errors can propagate when one thread waits on future result # and the other sets it with an error. error_msg = "Intentional Value Error" value_error = ValueError(error_msg) def wait_future(f): with self.assertRaisesRegex(ValueError, "Intentional"): f.wait() f = Future[T]() # type: ignore[valid-type] t = threading.Thread(target=wait_future, args=(f, )) t.start() f.set_exception(value_error) t.join() def cb(fut): fut.value() def then_future(f): fut = f.then(cb) with self.assertRaisesRegex(RuntimeError, "Got the following error"): fut.wait() f = Future[T]() # type: ignore[valid-type] t = threading.Thread(target=then_future, args=(f, )) t.start() f.set_exception(value_error) t.join() def test_done(self) -> None: f = Future[torch.Tensor]() self.assertFalse(f.done()) f.set_result(torch.ones(2, 2)) self.assertTrue(f.done()) def test_done_exception(self) -> None: err_msg = "Intentional Value Error" def raise_exception(unused_future): raise RuntimeError(err_msg) f1 = Future[torch.Tensor]() self.assertFalse(f1.done()) f1.set_result(torch.ones(2, 2)) self.assertTrue(f1.done()) f2 = f1.then(raise_exception) self.assertTrue(f2.done()) with self.assertRaisesRegex(RuntimeError, err_msg): f2.wait() def test_wait(self) -> None: f = Future[torch.Tensor]() f.set_result(torch.ones(2, 2)) self.assertEqual(f.wait(), torch.ones(2, 2)) def test_wait_multi_thread(self) -> None: def slow_set_future(fut, value): time.sleep(0.5) fut.set_result(value) f = Future[torch.Tensor]() t = threading.Thread(target=slow_set_future, args=(f, torch.ones(2, 2))) t.start() self.assertEqual(f.wait(), torch.ones(2, 2)) t.join() def test_mark_future_twice(self) -> None: fut = Future[int]() fut.set_result(1) with self.assertRaisesRegex( RuntimeError, "Future can only be marked completed once" ): fut.set_result(1) def test_pickle_future(self): fut = Future[int]() errMsg = "Can not pickle torch.futures.Future" with TemporaryFileName() as fname: with self.assertRaisesRegex(RuntimeError, errMsg): torch.save(fut, fname) def test_then(self): fut = Future[torch.Tensor]() then_fut = fut.then(lambda x: x.wait() + 1) fut.set_result(torch.ones(2, 2)) self.assertEqual(fut.wait(), torch.ones(2, 2)) self.assertEqual(then_fut.wait(), torch.ones(2, 2) + 1) def test_chained_then(self): fut = Future[torch.Tensor]() futs = [] last_fut = fut for _ in range(20): last_fut = last_fut.then(add_one) futs.append(last_fut) fut.set_result(torch.ones(2, 2)) for i in range(len(futs)): self.assertEqual(futs[i].wait(), torch.ones(2, 2) + i + 1) def _test_then_error(self, cb, errMsg): fut = Future[int]() then_fut = fut.then(cb) fut.set_result(5) self.assertEqual(5, fut.wait()) with self.assertRaisesRegex(RuntimeError, errMsg): then_fut.wait() def test_then_wrong_arg(self): def wrong_arg(tensor): return tensor + 1 self._test_then_error(wrong_arg, "unsupported operand type.*Future.*int") def test_then_no_arg(self): def no_arg(): return True self._test_then_error(no_arg, "takes 0 positional arguments but 1 was given") def test_then_raise(self): def raise_value_error(fut): raise ValueError("Expected error") self._test_then_error(raise_value_error, "Expected error") def test_add_done_callback_simple(self): callback_result = False def callback(fut): nonlocal callback_result fut.wait() callback_result = True fut = Future[torch.Tensor]() fut.add_done_callback(callback) self.assertFalse(callback_result) fut.set_result(torch.ones(2, 2)) self.assertEqual(fut.wait(), torch.ones(2, 2)) self.assertTrue(callback_result) def test_add_done_callback_maintains_callback_order(self): callback_result = 0 def callback_set1(fut): nonlocal callback_result fut.wait() callback_result = 1 def callback_set2(fut): nonlocal callback_result fut.wait() callback_result = 2 fut = Future[torch.Tensor]() fut.add_done_callback(callback_set1) fut.add_done_callback(callback_set2) fut.set_result(torch.ones(2, 2)) self.assertEqual(fut.wait(), torch.ones(2, 2)) # set2 called last, callback_result = 2 self.assertEqual(callback_result, 2) def _test_add_done_callback_error_ignored(self, cb): fut = Future[int]() fut.add_done_callback(cb) fut.set_result(5) # error msg logged to stdout self.assertEqual(5, fut.wait()) def test_add_done_callback_error_is_ignored(self): def raise_value_error(fut): raise ValueError("Expected error") self._test_add_done_callback_error_ignored(raise_value_error) def test_add_done_callback_no_arg_error_is_ignored(self): def no_arg(): return True # Adding another level of function indirection here on purpose. # Otherwise mypy will pick up on no_arg having an incompatible type and fail CI self._test_add_done_callback_error_ignored(no_arg) def test_interleaving_then_and_add_done_callback_maintains_callback_order(self): callback_result = 0 def callback_set1(fut): nonlocal callback_result fut.wait() callback_result = 1 def callback_set2(fut): nonlocal callback_result fut.wait() callback_result = 2 def callback_then(fut): nonlocal callback_result return fut.wait() + callback_result fut = Future[torch.Tensor]() fut.add_done_callback(callback_set1) then_fut = fut.then(callback_then) fut.add_done_callback(callback_set2) fut.set_result(torch.ones(2, 2)) self.assertEqual(fut.wait(), torch.ones(2, 2)) # then_fut's callback is called with callback_result = 1 self.assertEqual(then_fut.wait(), torch.ones(2, 2) + 1) # set2 called last, callback_result = 2 self.assertEqual(callback_result, 2) def test_interleaving_then_and_add_done_callback_propagates_error(self): def raise_value_error(fut): raise ValueError("Expected error") fut = Future[torch.Tensor]() then_fut = fut.then(raise_value_error) fut.add_done_callback(raise_value_error) fut.set_result(torch.ones(2, 2)) # error from add_done_callback's callback is swallowed # error from then's callback is not self.assertEqual(fut.wait(), torch.ones(2, 2)) with self.assertRaisesRegex(RuntimeError, "Expected error"): then_fut.wait() def test_collect_all(self): fut1 = Future[int]() fut2 = Future[int]() fut_all = torch.futures.collect_all([fut1, fut2]) def slow_in_thread(fut, value): time.sleep(0.1) fut.set_result(value) t = threading.Thread(target=slow_in_thread, args=(fut1, 1)) fut2.set_result(2) t.start() res = fut_all.wait() self.assertEqual(res[0].wait(), 1) self.assertEqual(res[1].wait(), 2) t.join() @unittest.skipIf(IS_WINDOWS, "TODO: need to fix this testcase for Windows") def test_wait_all(self): fut1 = Future[int]() fut2 = Future[int]() # No error version fut1.set_result(1) fut2.set_result(2) res = torch.futures.wait_all([fut1, fut2]) print(res) self.assertEqual(res, [1, 2]) # Version with an exception def raise_in_fut(fut): raise ValueError("Expected error") fut3 = fut1.then(raise_in_fut) with self.assertRaisesRegex(RuntimeError, "Expected error"): torch.futures.wait_all([fut3, fut2]) def test_wait_none(self): fut1 = Future[int]() with self.assertRaisesRegex(RuntimeError, "Future can't be None"): torch.jit.wait(None) with self.assertRaisesRegex(RuntimeError, "Future can't be None"): torch.futures.wait_all((None,)) # type: ignore[arg-type] with self.assertRaisesRegex(RuntimeError, "Future can't be None"): torch.futures.collect_all((fut1, None,)) # type: ignore[arg-type] if __name__ == '__main__': run_tests()
TestFuture
python
scrapy__scrapy
tests/CrawlerRunner/multi_seq.py
{ "start": 257, "end": 631 }
class ____(Spider): name = "no_request" async def start(self): return yield @inlineCallbacks def main(reactor): configure_logging() runner = CrawlerRunner() yield runner.crawl(NoRequestsSpider) yield runner.crawl(NoRequestsSpider) install_reactor("twisted.internet.asyncioreactor.AsyncioSelectorReactor") react(main)
NoRequestsSpider
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-mlx/llama_index/llms/mlx/tokenizer_utils.py
{ "start": 3100, "end": 4649 }
class ____(StreamingDetokenizer): """ A streaming detokenizer for SPM models. It adds tokens to the text if the next token starts with the special SPM underscore which results in linear complexity. """ def __init__(self, tokenizer, trim_space=True) -> None: self.trim_space = trim_space # Extract the tokens in a list from id to text self.tokenmap = [None] * len(tokenizer.vocab) for value, tokenid in tokenizer.vocab.items(): self.tokenmap[tokenid] = value # Replace bytes with their value for i in range(len(self.tokenmap)): if self.tokenmap[i].startswith("<0x"): self.tokenmap[i] = chr(int(self.tokenmap[i][3:5], 16)) self.reset() def reset(self): self.offset = 0 self._unflushed = "" self.text = "" self.tokens = [] def add_token(self, token): v = self.tokenmap[token] if v[0] == "\u2581": if self.text or not self.trim_space: self.text += self._unflushed.replace("\u2581", " ") else: self.text = _remove_space(self._unflushed.replace("\u2581", " ")) self._unflushed = v else: self._unflushed += v def finalize(self): if self.text or not self.trim_space: self.text += self._unflushed.replace("\u2581", " ") else: self.text = _remove_space(self._unflushed.replace("\u2581", " ")) self._unflushed = ""
SPMStreamingDetokenizer
python
kubernetes-client__python
kubernetes/client/models/v1_service_account.py
{ "start": 383, "end": 11448 }
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 = { 'api_version': 'str', 'automount_service_account_token': 'bool', 'image_pull_secrets': 'list[V1LocalObjectReference]', 'kind': 'str', 'metadata': 'V1ObjectMeta', 'secrets': 'list[V1ObjectReference]' } attribute_map = { 'api_version': 'apiVersion', 'automount_service_account_token': 'automountServiceAccountToken', 'image_pull_secrets': 'imagePullSecrets', 'kind': 'kind', 'metadata': 'metadata', 'secrets': 'secrets' } def __init__(self, api_version=None, automount_service_account_token=None, image_pull_secrets=None, kind=None, metadata=None, secrets=None, local_vars_configuration=None): # noqa: E501 """V1ServiceAccount - 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._api_version = None self._automount_service_account_token = None self._image_pull_secrets = None self._kind = None self._metadata = None self._secrets = None self.discriminator = None if api_version is not None: self.api_version = api_version if automount_service_account_token is not None: self.automount_service_account_token = automount_service_account_token if image_pull_secrets is not None: self.image_pull_secrets = image_pull_secrets if kind is not None: self.kind = kind if metadata is not None: self.metadata = metadata if secrets is not None: self.secrets = secrets @property def api_version(self): """Gets the api_version of this V1ServiceAccount. # noqa: E501 APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :return: The api_version of this V1ServiceAccount. # noqa: E501 :rtype: str """ return self._api_version @api_version.setter def api_version(self, api_version): """Sets the api_version of this V1ServiceAccount. APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 :param api_version: The api_version of this V1ServiceAccount. # noqa: E501 :type: str """ self._api_version = api_version @property def automount_service_account_token(self): """Gets the automount_service_account_token of this V1ServiceAccount. # noqa: E501 AutomountServiceAccountToken indicates whether pods running as this service account should have an API token automatically mounted. Can be overridden at the pod level. # noqa: E501 :return: The automount_service_account_token of this V1ServiceAccount. # noqa: E501 :rtype: bool """ return self._automount_service_account_token @automount_service_account_token.setter def automount_service_account_token(self, automount_service_account_token): """Sets the automount_service_account_token of this V1ServiceAccount. AutomountServiceAccountToken indicates whether pods running as this service account should have an API token automatically mounted. Can be overridden at the pod level. # noqa: E501 :param automount_service_account_token: The automount_service_account_token of this V1ServiceAccount. # noqa: E501 :type: bool """ self._automount_service_account_token = automount_service_account_token @property def image_pull_secrets(self): """Gets the image_pull_secrets of this V1ServiceAccount. # noqa: E501 ImagePullSecrets is a list of references to secrets in the same namespace to use for pulling any images in pods that reference this ServiceAccount. ImagePullSecrets are distinct from Secrets because Secrets can be mounted in the pod, but ImagePullSecrets are only accessed by the kubelet. More info: https://kubernetes.io/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod # noqa: E501 :return: The image_pull_secrets of this V1ServiceAccount. # noqa: E501 :rtype: list[V1LocalObjectReference] """ return self._image_pull_secrets @image_pull_secrets.setter def image_pull_secrets(self, image_pull_secrets): """Sets the image_pull_secrets of this V1ServiceAccount. ImagePullSecrets is a list of references to secrets in the same namespace to use for pulling any images in pods that reference this ServiceAccount. ImagePullSecrets are distinct from Secrets because Secrets can be mounted in the pod, but ImagePullSecrets are only accessed by the kubelet. More info: https://kubernetes.io/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod # noqa: E501 :param image_pull_secrets: The image_pull_secrets of this V1ServiceAccount. # noqa: E501 :type: list[V1LocalObjectReference] """ self._image_pull_secrets = image_pull_secrets @property def kind(self): """Gets the kind of this V1ServiceAccount. # noqa: E501 Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :return: The kind of this V1ServiceAccount. # noqa: E501 :rtype: str """ return self._kind @kind.setter def kind(self, kind): """Sets the kind of this V1ServiceAccount. Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 :param kind: The kind of this V1ServiceAccount. # noqa: E501 :type: str """ self._kind = kind @property def metadata(self): """Gets the metadata of this V1ServiceAccount. # noqa: E501 :return: The metadata of this V1ServiceAccount. # noqa: E501 :rtype: V1ObjectMeta """ return self._metadata @metadata.setter def metadata(self, metadata): """Sets the metadata of this V1ServiceAccount. :param metadata: The metadata of this V1ServiceAccount. # noqa: E501 :type: V1ObjectMeta """ self._metadata = metadata @property def secrets(self): """Gets the secrets of this V1ServiceAccount. # noqa: E501 Secrets is a list of the secrets in the same namespace that pods running using this ServiceAccount are allowed to use. Pods are only limited to this list if this service account has a \"kubernetes.io/enforce-mountable-secrets\" annotation set to \"true\". The \"kubernetes.io/enforce-mountable-secrets\" annotation is deprecated since v1.32. Prefer separate namespaces to isolate access to mounted secrets. This field should not be used to find auto-generated service account token secrets for use outside of pods. Instead, tokens can be requested directly using the TokenRequest API, or service account token secrets can be manually created. More info: https://kubernetes.io/docs/concepts/configuration/secret # noqa: E501 :return: The secrets of this V1ServiceAccount. # noqa: E501 :rtype: list[V1ObjectReference] """ return self._secrets @secrets.setter def secrets(self, secrets): """Sets the secrets of this V1ServiceAccount. Secrets is a list of the secrets in the same namespace that pods running using this ServiceAccount are allowed to use. Pods are only limited to this list if this service account has a \"kubernetes.io/enforce-mountable-secrets\" annotation set to \"true\". The \"kubernetes.io/enforce-mountable-secrets\" annotation is deprecated since v1.32. Prefer separate namespaces to isolate access to mounted secrets. This field should not be used to find auto-generated service account token secrets for use outside of pods. Instead, tokens can be requested directly using the TokenRequest API, or service account token secrets can be manually created. More info: https://kubernetes.io/docs/concepts/configuration/secret # noqa: E501 :param secrets: The secrets of this V1ServiceAccount. # noqa: E501 :type: list[V1ObjectReference] """ self._secrets = secrets 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, V1ServiceAccount): 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, V1ServiceAccount): return True return self.to_dict() != other.to_dict()
V1ServiceAccount
python
gevent__gevent
src/greentest/3.12/test_socket.py
{ "start": 17545, "end": 18223 }
class ____(unittest.TestCase): """A base class for socket tests. Subclasses must provide methods newSocket() to return a new socket and bindSock(sock) to bind it to an unused address. Creates a socket self.serv and sets self.serv_addr to its address. """ def setUp(self): self.serv = self.newSocket() self.addCleanup(self.close_server) self.bindServer() def close_server(self): self.serv.close() self.serv = None def bindServer(self): """Bind server socket and set self.serv_addr to its address.""" self.bindSock(self.serv) self.serv_addr = self.serv.getsockname()
SocketTestBase
python
django__django
django/contrib/auth/models.py
{ "start": 15585, "end": 17855 }
class ____(AbstractBaseUser, PermissionsMixin): """ An abstract base class implementing a fully featured User model with admin-compliant permissions. Username and password are required. Other fields are optional. """ username_validator = UnicodeUsernameValidator() username = models.CharField( _("username"), max_length=150, unique=True, help_text=_( "Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only." ), validators=[username_validator], error_messages={ "unique": _("A user with that username already exists."), }, ) first_name = models.CharField(_("first name"), max_length=150, blank=True) last_name = models.CharField(_("last name"), max_length=150, blank=True) email = models.EmailField(_("email address"), blank=True) is_staff = models.BooleanField( _("staff status"), default=False, help_text=_("Designates whether the user can log into this admin site."), ) is_active = models.BooleanField( _("active"), default=True, help_text=_( "Designates whether this user should be treated as active. " "Unselect this instead of deleting accounts." ), ) date_joined = models.DateTimeField(_("date joined"), default=timezone.now) objects = UserManager() EMAIL_FIELD = "email" USERNAME_FIELD = "username" REQUIRED_FIELDS = ["email"] class Meta: verbose_name = _("user") verbose_name_plural = _("users") abstract = True def clean(self): super().clean() self.email = self.__class__.objects.normalize_email(self.email) def get_full_name(self): """ Return the first_name plus the last_name, with a space in between. """ full_name = "%s %s" % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): """Return the short name for the user.""" return self.first_name def email_user(self, subject, message, from_email=None, **kwargs): """Send an email to this user.""" send_mail(subject, message, from_email, [self.email], **kwargs)
AbstractUser
python
walkccc__LeetCode
solutions/978. Longest Turbulent Subarray/978.py
{ "start": 0, "end": 458 }
class ____: def maxTurbulenceSize(self, arr: list[int]) -> int: ans = 1 increasing = 1 decreasing = 1 for i in range(1, len(arr)): if arr[i] > arr[i - 1]: increasing = decreasing + 1 decreasing = 1 elif arr[i] < arr[i - 1]: decreasing = increasing + 1 increasing = 1 else: increasing = 1 decreasing = 1 ans = max(ans, max(increasing, decreasing)) return ans
Solution
python
arrow-py__arrow
tests/test_locales.py
{ "start": 55022, "end": 59284 }
class ____: def test_singles_mk(self): assert self.locale._format_timeframe("second", 1) == "bir saniyə" assert self.locale._format_timeframe("minute", 1) == "bir dəqiqə" assert self.locale._format_timeframe("hour", 1) == "bir saat" assert self.locale._format_timeframe("day", 1) == "bir gün" assert self.locale._format_timeframe("week", 1) == "bir həftə" assert self.locale._format_timeframe("month", 1) == "bir ay" assert self.locale._format_timeframe("year", 1) == "bir il" def test_describe_mk(self): assert self.locale.describe("second", only_distance=True) == "bir saniyə" assert self.locale.describe("second", only_distance=False) == "bir saniyə sonra" assert self.locale.describe("minute", only_distance=True) == "bir dəqiqə" assert self.locale.describe("minute", only_distance=False) == "bir dəqiqə sonra" assert self.locale.describe("hour", only_distance=True) == "bir saat" assert self.locale.describe("hour", only_distance=False) == "bir saat sonra" assert self.locale.describe("day", only_distance=True) == "bir gün" assert self.locale.describe("day", only_distance=False) == "bir gün sonra" assert self.locale.describe("week", only_distance=True) == "bir həftə" assert self.locale.describe("week", only_distance=False) == "bir həftə sonra" assert self.locale.describe("month", only_distance=True) == "bir ay" assert self.locale.describe("month", only_distance=False) == "bir ay sonra" assert self.locale.describe("year", only_distance=True) == "bir il" assert self.locale.describe("year", only_distance=False) == "bir il sonra" def test_relative_mk(self): assert self.locale._format_relative("indi", "now", 0) == "indi" assert ( self.locale._format_relative("1 saniyə", "seconds", 1) == "1 saniyə sonra" ) assert ( self.locale._format_relative("1 saniyə", "seconds", -1) == "1 saniyə əvvəl" ) assert ( self.locale._format_relative("1 dəqiqə", "minutes", 1) == "1 dəqiqə sonra" ) assert ( self.locale._format_relative("1 dəqiqə", "minutes", -1) == "1 dəqiqə əvvəl" ) assert self.locale._format_relative("1 saat", "hours", 1) == "1 saat sonra" assert self.locale._format_relative("1 saat", "hours", -1) == "1 saat əvvəl" assert self.locale._format_relative("1 gün", "days", 1) == "1 gün sonra" assert self.locale._format_relative("1 gün", "days", -1) == "1 gün əvvəl" assert self.locale._format_relative("1 hafta", "weeks", 1) == "1 hafta sonra" assert self.locale._format_relative("1 hafta", "weeks", -1) == "1 hafta əvvəl" assert self.locale._format_relative("1 ay", "months", 1) == "1 ay sonra" assert self.locale._format_relative("1 ay", "months", -1) == "1 ay əvvəl" assert self.locale._format_relative("1 il", "years", 1) == "1 il sonra" assert self.locale._format_relative("1 il", "years", -1) == "1 il əvvəl" def test_plurals_mk(self): assert self.locale._format_timeframe("now", 0) == "indi" assert self.locale._format_timeframe("second", 1) == "bir saniyə" assert self.locale._format_timeframe("seconds", 30) == "30 saniyə" assert self.locale._format_timeframe("minute", 1) == "bir dəqiqə" assert self.locale._format_timeframe("minutes", 40) == "40 dəqiqə" assert self.locale._format_timeframe("hour", 1) == "bir saat" assert self.locale._format_timeframe("hours", 23) == "23 saat" assert self.locale._format_timeframe("day", 1) == "bir gün" assert self.locale._format_timeframe("days", 12) == "12 gün" assert self.locale._format_timeframe("week", 1) == "bir həftə" assert self.locale._format_timeframe("weeks", 38) == "38 həftə" assert self.locale._format_timeframe("month", 1) == "bir ay" assert self.locale._format_timeframe("months", 11) == "11 ay" assert self.locale._format_timeframe("year", 1) == "bir il" assert self.locale._format_timeframe("years", 12) == "12 il" @pytest.mark.usefixtures("lang_locale")
TestAzerbaijaniLocale
python
dagster-io__dagster
python_modules/dagster/dagster_tests/declarative_automation_tests/automation_condition_tests/builtins/test_freshness_result_condition.py
{ "start": 393, "end": 7259 }
class ____: instance: DagsterInstance __state_cache: dict[AssetKey, FreshnessState] @pytest.fixture(autouse=True) def setup_method(self): self.instance = DagsterInstance.ephemeral() self.__state_cache = {} yield self.instance = None # pyright: ignore[reportAttributeAccessIssue] self.__state_cache = {} def report_freshness_state(self, key: AssetKey, state: FreshnessState) -> None: self.instance.report_runless_asset_event( asset_event=FreshnessStateChange( key=key, previous_state=self.__state_cache.get(key, FreshnessState.UNKNOWN), new_state=state, state_change_timestamp=get_current_timestamp(), ) ) self.__state_cache[key] = state @pytest.mark.parametrize( ["automation_condition", "synth_events", "expected_requested"], [ pytest.param( automation_condition, synth_events, expected_requested, id=f"{automation_condition.name}-{[e.value for e in synth_events]}-{expected_requested}", ) for automation_condition, synth_events, expected_requested in [ (AutomationCondition.freshness_passed(), [FreshnessState.PASS], 1), (AutomationCondition.freshness_passed(), [FreshnessState.WARN], 0), (AutomationCondition.freshness_passed(), [FreshnessState.FAIL], 0), (AutomationCondition.freshness_passed(), [FreshnessState.UNKNOWN], 0), (AutomationCondition.freshness_passed(), [FreshnessState.NOT_APPLICABLE], 0), ( AutomationCondition.freshness_passed(), [FreshnessState.NOT_APPLICABLE, FreshnessState.UNKNOWN, FreshnessState.PASS], 1, ), ( AutomationCondition.freshness_passed(), [FreshnessState.PASS, FreshnessState.FAIL, FreshnessState.PASS], 1, ), ( AutomationCondition.freshness_passed(), [FreshnessState.PASS, FreshnessState.WARN, FreshnessState.FAIL], 0, ), (AutomationCondition.freshness_passed(), [FreshnessState.NOT_APPLICABLE], 0), (AutomationCondition.freshness_warned(), [FreshnessState.PASS], 0), (AutomationCondition.freshness_warned(), [FreshnessState.WARN], 1), (AutomationCondition.freshness_warned(), [FreshnessState.FAIL], 0), (AutomationCondition.freshness_warned(), [FreshnessState.UNKNOWN], 0), (AutomationCondition.freshness_warned(), [FreshnessState.NOT_APPLICABLE], 0), ( AutomationCondition.freshness_warned(), [FreshnessState.NOT_APPLICABLE, FreshnessState.UNKNOWN, FreshnessState.WARN], 1, ), ( AutomationCondition.freshness_warned(), [FreshnessState.PASS, FreshnessState.FAIL, FreshnessState.WARN], 1, ), ( AutomationCondition.freshness_warned(), [FreshnessState.PASS, FreshnessState.WARN, FreshnessState.FAIL], 0, ), (AutomationCondition.freshness_failed(), [FreshnessState.PASS], 0), (AutomationCondition.freshness_failed(), [FreshnessState.WARN], 0), (AutomationCondition.freshness_failed(), [FreshnessState.FAIL], 1), (AutomationCondition.freshness_failed(), [FreshnessState.UNKNOWN], 0), (AutomationCondition.freshness_failed(), [FreshnessState.NOT_APPLICABLE], 0), ( AutomationCondition.freshness_failed(), [FreshnessState.NOT_APPLICABLE, FreshnessState.UNKNOWN, FreshnessState.FAIL], 1, ), ( AutomationCondition.freshness_failed(), [FreshnessState.FAIL, FreshnessState.WARN, FreshnessState.FAIL], 1, ), ( AutomationCondition.freshness_failed(), [FreshnessState.WARN, FreshnessState.FAIL, FreshnessState.PASS], 0, ), ] ], ) def test_freshness_status_condition( self, automation_condition: AutomationCondition, synth_events: Sequence[FreshnessState], expected_requested: int, ) -> None: @dg.asset( freshness_policy=FreshnessPolicy.time_window( fail_window=timedelta(seconds=1, minutes=2, hours=3) ), automation_condition=automation_condition, ) def _asset() -> None: ... # no change events - should not request result = dg.evaluate_automation_conditions(defs=[_asset], instance=self.instance) assert result.total_requested == 0 for state in synth_events: self.report_freshness_state(_asset.key, state) # should request based on the last event result = dg.evaluate_automation_conditions(defs=[_asset], instance=self.instance) assert result.total_requested == expected_requested # should not change if we re-evaluate result = dg.evaluate_automation_conditions(defs=[_asset], instance=self.instance) assert result.total_requested == expected_requested @pytest.mark.parametrize( "automation_condition", [ AutomationCondition.freshness_passed(), AutomationCondition.freshness_warned(), AutomationCondition.freshness_failed(), ], ids=["freshness_passed", "freshness_warned", "freshness_failed"], ) def test_freshness_result_condition_no_freshness_policy( self, automation_condition: AutomationCondition ) -> None: @dg.asset( freshness_policy=None, automation_condition=automation_condition, ) def _asset() -> None: ... # no freshness policy - should not request result = dg.evaluate_automation_conditions(defs=[_asset], instance=self.instance) assert result.total_requested == 0 def test_freshness_result_condition_invalid_state_param(self) -> None: with pytest.raises(ParameterCheckError): from dagster._core.definitions.declarative_automation.operands import ( FreshnessResultCondition, ) FreshnessResultCondition(state="Fresh") # pyright: ignore[reportArgumentType]
TestFreshnessResultCondition
python
tiangolo__fastapi
docs_src/request_form_models/tutorial002_pv1_an.py
{ "start": 124, "end": 322 }
class ____(BaseModel): username: str password: str class Config: extra = "forbid" @app.post("/login/") async def login(data: Annotated[FormData, Form()]): return data
FormData
python
scipy__scipy
scipy/stats/_multivariate.py
{ "start": 165020, "end": 181438 }
class ____(multi_rv_generic): r"""A multivariate t-distributed random variable. The `loc` parameter specifies the location. The `shape` parameter specifies the positive semidefinite shape matrix. The `df` parameter specifies the degrees of freedom. In addition to calling the methods below, the object itself may be called as a function to fix the location, shape matrix, and degrees of freedom parameters, returning a "frozen" multivariate t-distribution random. Methods ------- pdf(x, loc=None, shape=1, df=1, allow_singular=False) Probability density function. logpdf(x, loc=None, shape=1, df=1, allow_singular=False) Log of the probability density function. cdf(x, loc=None, shape=1, df=1, allow_singular=False, *, maxpts=None, lower_limit=None, random_state=None) Cumulative distribution function. rvs(loc=None, shape=1, df=1, size=1, random_state=None) Draw random samples from a multivariate t-distribution. entropy(loc=None, shape=1, df=1) Differential entropy of a multivariate t-distribution. Parameters ---------- %(_mvt_doc_default_callparams)s %(_doc_random_state)s Notes ----- %(_mvt_doc_callparams_note)s The matrix `shape` must be a (symmetric) positive semidefinite matrix. The determinant and inverse of `shape` are computed as the pseudo-determinant and pseudo-inverse, respectively, so that `shape` does not need to have full rank. The probability density function for `multivariate_t` is .. math:: f(x) = \frac{\Gamma((\nu + p)/2)}{\Gamma(\nu/2)\nu^{p/2}\pi^{p/2}|\Sigma|^{1/2}} \left[1 + \frac{1}{\nu} (\mathbf{x} - \boldsymbol{\mu})^{\top} \boldsymbol{\Sigma}^{-1} (\mathbf{x} - \boldsymbol{\mu}) \right]^{-(\nu + p)/2}, where :math:`p` is the dimension of :math:`\mathbf{x}`, :math:`\boldsymbol{\mu}` is the :math:`p`-dimensional location, :math:`\boldsymbol{\Sigma}` the :math:`p \times p`-dimensional shape matrix, and :math:`\nu` is the degrees of freedom. .. versionadded:: 1.6.0 References ---------- .. [1] Arellano-Valle et al. "Shannon Entropy and Mutual Information for Multivariate Skew-Elliptical Distributions". Scandinavian Journal of Statistics. Vol. 40, issue 1. Examples -------- The object may be called (as a function) to fix the `loc`, `shape`, `df`, and `allow_singular` parameters, returning a "frozen" multivariate_t random variable: >>> import numpy as np >>> from scipy.stats import multivariate_t >>> rv = multivariate_t([1.0, -0.5], [[2.1, 0.3], [0.3, 1.5]], df=2) >>> # Frozen object with the same methods but holding the given location, >>> # scale, and degrees of freedom fixed. Create a contour plot of the PDF. >>> import matplotlib.pyplot as plt >>> x, y = np.mgrid[-1:3:.01, -2:1.5:.01] >>> pos = np.dstack((x, y)) >>> fig, ax = plt.subplots(1, 1) >>> ax.set_aspect('equal') >>> plt.contourf(x, y, rv.pdf(pos)) """ def __init__(self, seed=None): """Initialize a multivariate t-distributed random variable. Parameters ---------- seed : Random state. """ super().__init__(seed) self.__doc__ = doccer.docformat(self.__doc__, mvt_docdict_params) self._random_state = check_random_state(seed) def __call__(self, loc=None, shape=1, df=1, allow_singular=False, seed=None): """Create a frozen multivariate t-distribution. See `multivariate_t_frozen` for parameters. """ if df == np.inf: return multivariate_normal_frozen(mean=loc, cov=shape, allow_singular=allow_singular, seed=seed) return multivariate_t_frozen(loc=loc, shape=shape, df=df, allow_singular=allow_singular, seed=seed) def pdf(self, x, loc=None, shape=1, df=1, allow_singular=False): """Multivariate t-distribution probability density function. Parameters ---------- x : array_like Points at which to evaluate the probability density function. %(_mvt_doc_default_callparams)s Returns ------- pdf : Probability density function evaluated at `x`. Examples -------- >>> from scipy.stats import multivariate_t >>> x = [0.4, 5] >>> loc = [0, 1] >>> shape = [[1, 0.1], [0.1, 1]] >>> df = 7 >>> multivariate_t.pdf(x, loc, shape, df) 0.00075713 """ dim, loc, shape, df = self._process_parameters(loc, shape, df) x = self._process_quantiles(x, dim) shape_info = _PSD(shape, allow_singular=allow_singular) logpdf = self._logpdf(x, loc, shape_info.U, shape_info.log_pdet, df, dim, shape_info.rank) return np.exp(logpdf) def logpdf(self, x, loc=None, shape=1, df=1): """Log of the multivariate t-distribution probability density function. Parameters ---------- x : array_like Points at which to evaluate the log of the probability density function. %(_mvt_doc_default_callparams)s Returns ------- logpdf : Log of the probability density function evaluated at `x`. Examples -------- >>> from scipy.stats import multivariate_t >>> x = [0.4, 5] >>> loc = [0, 1] >>> shape = [[1, 0.1], [0.1, 1]] >>> df = 7 >>> multivariate_t.logpdf(x, loc, shape, df) -7.1859802 See Also -------- pdf : Probability density function. """ dim, loc, shape, df = self._process_parameters(loc, shape, df) x = self._process_quantiles(x, dim) shape_info = _PSD(shape) cov_object = _covariance.CovViaPSD(shape_info) return self._logpdf(x, loc, shape_info.U, shape_info.log_pdet, df, dim, shape_info.rank, cov_object) def _logpdf(self, x, loc, prec_U, log_pdet, df, dim, rank, cov_object=None): """Utility method `pdf`, `logpdf` for parameters. Parameters ---------- x : ndarray Points at which to evaluate the log of the probability density function. loc : ndarray Location of the distribution. prec_U : ndarray A decomposition such that `np.dot(prec_U, prec_U.T)` is the inverse of the shape matrix. log_pdet : float Logarithm of the determinant of the shape matrix. df : float Degrees of freedom of the distribution. dim : int Dimension of the quantiles x. rank : int Rank of the shape matrix. Notes ----- As this function does no argument checking, it should not be called directly; use 'logpdf' instead. """ if df == np.inf: return multivariate_normal._logpdf(x, loc, cov_object) dev = x - loc maha = np.square(np.dot(dev, prec_U)).sum(axis=-1) t = 0.5 * (df + dim) A = gammaln(t) B = gammaln(0.5 * df) C = dim/2. * np.log(df * np.pi) D = 0.5 * log_pdet E = -t * np.log(1 + (1./df) * maha) return _squeeze_output(A - B - C - D + E) def _cdf(self, x, loc, shape, df, dim, maxpts=None, lower_limit=None, random_state=None): # All of this - random state validation, maxpts, apply_along_axis, # etc. needs to go in this private method unless we want # frozen distribution's `cdf` method to duplicate it or call `cdf`, # which would require re-processing parameters if random_state is not None: rng = check_random_state(random_state) else: rng = self._random_state if not maxpts: maxpts = 1000 * dim x = self._process_quantiles(x, dim) lower_limit = (np.full(loc.shape, -np.inf) if lower_limit is None else lower_limit) # remove the mean x, lower_limit = x - loc, lower_limit - loc b, a = np.broadcast_arrays(x, lower_limit) i_swap = b < a signs = (-1)**(i_swap.sum(axis=-1)) # odd # of swaps -> negative a, b = a.copy(), b.copy() a[i_swap], b[i_swap] = b[i_swap], a[i_swap] n = x.shape[-1] limits = np.concatenate((a, b), axis=-1) def func1d(limits): a, b = limits[:n], limits[n:] return _qmvt(maxpts, df, shape, a, b, rng)[0] res = np.apply_along_axis(func1d, -1, limits) * signs # Fixing the output shape for existing distributions is a separate # issue. For now, let's keep this consistent with pdf. return _squeeze_output(res) def cdf(self, x, loc=None, shape=1, df=1, allow_singular=False, *, maxpts=None, lower_limit=None, random_state=None): """Multivariate t-distribution cumulative distribution function. Parameters ---------- x : array_like Points at which to evaluate the cumulative distribution function. %(_mvt_doc_default_callparams)s maxpts : int, optional Maximum number of points to use for integration. The default is 1000 times the number of dimensions. lower_limit : array_like, optional Lower limit of integration of the cumulative distribution function. Default is negative infinity. Must be broadcastable with `x`. %(_doc_random_state)s Returns ------- cdf : ndarray or scalar Cumulative distribution function evaluated at `x`. Examples -------- >>> from scipy.stats import multivariate_t >>> x = [0.4, 5] >>> loc = [0, 1] >>> shape = [[1, 0.1], [0.1, 1]] >>> df = 7 >>> multivariate_t.cdf(x, loc, shape, df) 0.64798491 """ dim, loc, shape, df = self._process_parameters(loc, shape, df) shape = _PSD(shape, allow_singular=allow_singular)._M return self._cdf(x, loc, shape, df, dim, maxpts, lower_limit, random_state) def _entropy(self, dim, df=1, shape=1): if df == np.inf: return multivariate_normal(None, cov=shape).entropy() shape_info = _PSD(shape) shape_term = 0.5 * shape_info.log_pdet def regular(dim, df): halfsum = 0.5 * (dim + df) half_df = 0.5 * df return ( -gammaln(halfsum) + gammaln(half_df) + 0.5 * dim * np.log(df * np.pi) + halfsum * (psi(halfsum) - psi(half_df)) + shape_term ) def asymptotic(dim, df): # Formula from Wolfram Alpha: # "asymptotic expansion -gammaln((m+d)/2) + gammaln(d/2) + (m*log(d*pi))/2 # + ((m+d)/2) * (digamma((m+d)/2) - digamma(d/2))" return ( dim * norm._entropy() + dim / df - dim * (dim - 2) * df**-2.0 / 4 + dim**2 * (dim - 2) * df**-3.0 / 6 + dim * (-3 * dim**3 + 8 * dim**2 - 8) * df**-4.0 / 24 + dim**2 * (3 * dim**3 - 10 * dim**2 + 16) * df**-5.0 / 30 + shape_term )[()] # preserves ~12 digits accuracy up to at least `dim=1e5`. See gh-18465. threshold = dim * 100 * 4 / (np.log(dim) + 1) return xpx.apply_where(df >= threshold, (dim, df), asymptotic, regular) def entropy(self, loc=None, shape=1, df=1): """Calculate the differential entropy of a multivariate t-distribution. Parameters ---------- %(_mvt_doc_default_callparams)s Returns ------- h : float Differential entropy """ dim, loc, shape, df = self._process_parameters(None, shape, df) return self._entropy(dim, df, shape) def rvs(self, loc=None, shape=1, df=1, size=1, random_state=None): """Draw random samples from a multivariate t-distribution. Parameters ---------- %(_mvt_doc_default_callparams)s size : integer, optional Number of samples to draw (default 1). %(_doc_random_state)s Returns ------- rvs : ndarray or scalar Random variates of size (`size`, `P`), where `P` is the dimension of the random variable. Examples -------- >>> from scipy.stats import multivariate_t >>> x = [0.4, 5] >>> loc = [0, 1] >>> shape = [[1, 0.1], [0.1, 1]] >>> df = 7 >>> multivariate_t.rvs(loc, shape, df) array([[0.93477495, 3.00408716]]) """ # For implementation details, see equation (3): # # Hofert, "On Sampling from the Multivariatet Distribution", 2013 # http://rjournal.github.io/archive/2013-2/hofert.pdf # dim, loc, shape, df = self._process_parameters(loc, shape, df) if random_state is not None: rng = check_random_state(random_state) else: rng = self._random_state if np.isinf(df): x = np.ones(size) else: x = rng.chisquare(df, size=size) / df z = rng.multivariate_normal(np.zeros(dim), shape, size=size) samples = loc + z / np.sqrt(x)[..., None] return _squeeze_output(samples) def _process_quantiles(self, x, dim): """ Adjust quantiles array so that last axis labels the components of each data point. """ x = np.asarray(x, dtype=float) if x.ndim == 0: x = x[np.newaxis] elif x.ndim == 1: if dim == 1: x = x[:, np.newaxis] else: x = x[np.newaxis, :] return x def _process_parameters(self, loc, shape, df): """ Infer dimensionality from location array and shape matrix, handle defaults, and ensure compatible dimensions. """ if loc is None and shape is None: loc = np.asarray(0, dtype=float) shape = np.asarray(1, dtype=float) dim = 1 elif loc is None: shape = np.asarray(shape, dtype=float) if shape.ndim < 2: dim = 1 else: dim = shape.shape[0] loc = np.zeros(dim) elif shape is None: loc = np.asarray(loc, dtype=float) dim = loc.size shape = np.eye(dim) else: shape = np.asarray(shape, dtype=float) loc = np.asarray(loc, dtype=float) dim = loc.size if dim == 1: loc = loc.reshape(1) shape = shape.reshape(1, 1) if loc.ndim != 1 or loc.shape[0] != dim: raise ValueError(f"Array 'loc' must be a vector of length {dim}.") if shape.ndim == 0: shape = shape * np.eye(dim) elif shape.ndim == 1: shape = np.diag(shape) elif shape.ndim == 2 and shape.shape != (dim, dim): rows, cols = shape.shape if rows != cols: msg = ("Array 'cov' must be square if it is two dimensional," f" but cov.shape = {str(shape.shape)}.") else: msg = ("Dimension mismatch: array 'cov' is of shape %s," " but 'loc' is a vector of length %d.") msg = msg % (str(shape.shape), len(loc)) raise ValueError(msg) elif shape.ndim > 2: raise ValueError(f"Array 'cov' must be at most two-dimensional, " f"but cov.ndim = {shape.ndim}") # Process degrees of freedom. if df is None: df = 1 elif df <= 0: raise ValueError("'df' must be greater than zero.") elif np.isnan(df): raise ValueError("'df' is 'nan' but must be greater than zero or 'np.inf'.") return dim, loc, shape, df
multivariate_t_gen
python
walkccc__LeetCode
solutions/2698. Find the Punishment Number of an Integer/2698.py
{ "start": 0, "end": 748 }
class ____: def punishmentNumber(self, n: int) -> int: def isPossible( accumulate: int, running: int, numChars: list[str], s: int, target: int) -> bool: """ Returns True if the sum of any split of `numChars` equals to the target. """ if s == len(numChars): return target == accumulate + running d = int(numChars[s]) return ( # Keep growing `running`. isPossible(accumulate, running * 10 + d, numChars, s + 1, target) or # Start a new `running`. isPossible(accumulate + running, d, numChars, s + 1, target) ) return sum(i * i for i in range(1, n + 1) if isPossible(0, 0, str(i * i), 0, i))
Solution
python
django__django
tests/migrations/test_migrations_squashed_complex/5_auto.py
{ "start": 35, "end": 188 }
class ____(migrations.Migration): dependencies = [("migrations", "4_auto")] operations = [migrations.RunPython(migrations.RunPython.noop)]
Migration
python
ray-project__ray
doc/source/serve/doc_code/model_composition/chaining_example.py
{ "start": 551, "end": 1350 }
class ____: def __init__(self, adder: DeploymentHandle, multiplier: DeploymentHandle): self._adder = adder self._multiplier = multiplier async def __call__(self, input: int) -> int: adder_response: DeploymentResponse = self._adder.remote(input) # Pass the adder response directly into the multiplier (no `await` needed). multiplier_response: DeploymentResponse = self._multiplier.remote( adder_response ) # `await` the final chained response. return await multiplier_response app = Ingress.bind( Adder.bind(increment=1), Multiplier.bind(multiple=2), ) handle: DeploymentHandle = serve.run(app) response = handle.remote(5) assert response.result() == 12, "(5 + 1) * 2 = 12" # __chaining_example_end__
Ingress
python
getsentry__sentry
src/sentry/notifications/notification_action/types.py
{ "start": 20973, "end": 22290 }
class ____(ABC): provider: str notify_action_form: type[NotificationActionForm] | None def __init__(self, validated_data: dict[str, Any], organization: Organization) -> None: self.validated_data = validated_data self.organization = organization def generate_action_form_payload(self) -> dict[str, Any]: return { "data": self.generate_action_form_data(), "integrations": _get_integrations(self.organization, self.provider), } def clean_data(self) -> dict[str, Any]: if self.notify_action_form is None: return self.validated_data notify_action_form = self.notify_action_form( **self.generate_action_form_payload(), ) if notify_action_form.is_valid(): return self.update_action_data(notify_action_form.cleaned_data) raise ValidationError(notify_action_form.errors) @abstractmethod def generate_action_form_data(self) -> dict[str, Any]: # translate validated data from BaseActionValidator to notify action form data pass @abstractmethod def update_action_data(self, cleaned_data: dict[str, Any]) -> dict[str, Any]: # update BaseActionValidator data with cleaned notify action form data pass
BaseActionValidatorHandler
python
pennersr__django-allauth
tests/apps/socialaccount/providers/paypal/tests.py
{ "start": 240, "end": 788 }
class ____(OAuth2TestsMixin, TestCase): provider_id = PaypalProvider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """ { "user_id": "https://www.paypal.com/webapps/auth/server/64ghr894040044", "name": "Jane Doe", "given_name": "Jane", "family_name": "Doe", "email": "janedoe@example.com" } """, ) def get_expected_to_str(self): return "janedoe@example.com"
PaypalTests
python
streamlit__streamlit
lib/streamlit/elements/widgets/slider.py
{ "start": 5442, "end": 7477 }
class ____: value: list[float] data_type: int single_value: bool orig_tz: tzinfo | None def deserialize_single_value(self, value: float) -> SliderScalar: if self.data_type == SliderProto.INT: return int(value) if self.data_type == SliderProto.DATETIME: return _micros_to_datetime(int(value), self.orig_tz) if self.data_type == SliderProto.DATE: return _micros_to_datetime(int(value), self.orig_tz).date() if self.data_type == SliderProto.TIME: return ( _micros_to_datetime(int(value), self.orig_tz) .time() .replace(tzinfo=self.orig_tz) ) return value def deserialize(self, ui_value: list[float] | None) -> Any: if ui_value is not None: val = ui_value else: # Widget has not been used; fallback to the original value, val = self.value # The widget always returns a float array, so fix the return type if necessary deserialized_values = [self.deserialize_single_value(v) for v in val] return ( deserialized_values[0] if self.single_value else tuple(deserialized_values) ) def serialize(self, v: Any) -> list[Any]: range_value = isinstance(v, (list, tuple)) # Convert to list to handle tuples processed_value = list(v) if range_value else [v] if self.data_type == SliderProto.DATE: return [ _datetime_to_micros(_date_to_datetime(val)) for val in processed_value ] if self.data_type == SliderProto.TIME: return [ _datetime_to_micros(_time_to_datetime(val)) for val in processed_value ] if self.data_type == SliderProto.DATETIME: return [_datetime_to_micros(val) for val in processed_value] # For numeric types, ensure they are floats if not already return [float(val) for val in processed_value]
SliderSerde
python
Pylons__pyramid
tests/test_events.py
{ "start": 2735, "end": 3473 }
class ____(ApplicationCreatedEventTests): def _getTargetClass(self): from pyramid.events import WSGIApplicationCreatedEvent return WSGIApplicationCreatedEvent def test_class_conforms_to_IWSGIApplicationCreatedEvent(self): from zope.interface.verify import verifyClass from pyramid.interfaces import IWSGIApplicationCreatedEvent verifyClass(IWSGIApplicationCreatedEvent, self._getTargetClass()) def test_object_conforms_to_IWSGIApplicationCreatedEvent(self): from zope.interface.verify import verifyObject from pyramid.interfaces import IWSGIApplicationCreatedEvent verifyObject(IWSGIApplicationCreatedEvent, self._makeOne())
WSGIApplicationCreatedEventTests
python
pandas-dev__pandas
asv_bench/benchmarks/io/json.py
{ "start": 5640, "end": 6359 }
class ____(BaseIO): fname = "__test__.json" params = [["split", "columns", "index", "values", "records"]] param_names = ["orient"] def setup(self, orient): N = 10**5 index = date_range("20000101", periods=N, freq="h") timedeltas = timedelta_range(start=1, periods=N, freq="s") datetimes = date_range(start=1, periods=N, freq="s") self.df = DataFrame( { "td_1": timedeltas, "td_2": timedeltas, "ts_1": datetimes, "ts_2": datetimes, }, index=index, ) def time_iso_format(self, orient): self.df.to_json(orient=orient, date_format="iso")
ToJSONISO
python
huggingface__transformers
src/transformers/models/llava_onevision/modular_llava_onevision.py
{ "start": 26480, "end": 34322 }
class ____(LlavaNextVideoForConditionalGeneration): @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.LongTensor] = None, pixel_values: Optional[torch.FloatTensor] = None, image_sizes: Optional[torch.LongTensor] = None, pixel_values_videos: Optional[torch.FloatTensor] = None, image_sizes_videos: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[Cache] = None, inputs_embeds: Optional[torch.FloatTensor] = None, vision_feature_layer: Optional[Union[int, list[int]]] = None, vision_feature_select_strategy: Optional[str] = None, vision_aspect_ratio: Optional[str] = None, batch_num_images: Optional[torch.LongTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, logits_to_keep: Union[int, torch.Tensor] = 0, **kwargs: Unpack[TransformersKwargs], ) -> Union[tuple, LlavaOnevisionCausalLMOutputWithPast]: r""" image_sizes_videos (`torch.LongTensor` of shape `(batch_size, frames, 2)`, *optional*): The sizes of the videos in the batch, being (height, width) for each frame in the video. vision_aspect_ratio (`str`, *optional*, defaults to `"anyres_max_9"`): Aspect ratio used when processong image features. The default value is "anyres_max_9". batch_num_images (`torch.LongTensor`, *optional*): Number of images in each sample. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. Example: ```python >>> from PIL import Image >>> import requests >>> import torch >>> from transformers import LlavaOnevisionProcessor, LlavaOnevisionForConditionalGeneration >>> model = LlavaOnevisionForConditionalGeneration.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf", dtype="float16", device_map="cuda:0") >>> processor = LlavaOnevisionProcessor.from_pretrained("llava-hf/llava-onevision-qwen2-7b-ov-hf") >>> conversation = [ ... { ... "role": "user", ... "content": [ ... {"type": "text", "text": "What is shown in this image?"}, ... {"type": "image"}, ... ], ... }, ... ] >>> prompt = processor.apply_chat_template(conversation, add_generation_prompt=True) >>> image_file = "http://images.cocodataset.org/val2017/000000039769.jpg" >>> raw_image = Image.open(requests.get(image_file, stream=True).raw) >>> inputs = processor(text=prompt, images=raw_image, return_tensors='pt').to(0, torch.float16) >>> output = model.generate(**inputs, max_new_tokens=20, do_sample=False) >>> processor.batch_decode(output, skip_special_tokens=True)[0] "user\n\nWhat is shown in this image?\nassistant\ncat" ```""" output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict vision_feature_layer = ( vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer ) vision_feature_select_strategy = ( vision_feature_select_strategy if vision_feature_select_strategy is not None else self.config.vision_feature_select_strategy ) vision_aspect_ratio = ( vision_aspect_ratio if vision_aspect_ratio is not None else self.config.vision_aspect_ratio ) outputs = self.model( input_ids=input_ids, pixel_values=pixel_values, pixel_values_videos=pixel_values_videos, image_sizes=image_sizes, image_sizes_videos=image_sizes_videos, vision_aspect_ratio=vision_aspect_ratio, vision_feature_layer=vision_feature_layer, vision_feature_select_strategy=vision_feature_select_strategy, batch_num_images=batch_num_images, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=True, cache_position=cache_position, logits_to_keep=logits_to_keep, **kwargs, ) hidden_states = outputs[0] # Only compute necessary logits, and do not upcast them to float if we are not computing the loss slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep logits = self.lm_head(hidden_states[:, slice_indices, :]) loss = None if labels is not None: loss = self.loss_function( logits=logits, labels=labels, vocab_size=self.config.text_config.vocab_size, **kwargs ) return LlavaOnevisionCausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, image_hidden_states=outputs.image_hidden_states, video_hidden_states=outputs.video_hidden_states, ) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, inputs_embeds=None, pixel_values=None, image_sizes=None, pixel_values_videos=None, image_sizes_videos=None, attention_mask=None, cache_position=None, logits_to_keep=None, **kwargs, ): # Overwritten -- in specific circumstances we don't want to forward image inputs to the model model_inputs = super().prepare_inputs_for_generation( input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, attention_mask=attention_mask, cache_position=cache_position, logits_to_keep=logits_to_keep, **kwargs, ) if cache_position[0] == 0: # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore # Otherwise we need pixel values to be passed to model model_inputs["pixel_values"] = pixel_values model_inputs["image_sizes"] = image_sizes model_inputs["pixel_values_videos"] = pixel_values_videos model_inputs["image_sizes_videos"] = image_sizes_videos return model_inputs __all__ = [ "LlavaOnevisionImageProcessorFast", "LlavaOnevisionModel", "LlavaOnevisionForConditionalGeneration", "LlavaOnevisionPreTrainedModel", ]
LlavaOnevisionForConditionalGeneration
python
getsentry__sentry-python
sentry_sdk/integrations/starlette.py
{ "start": 20953, "end": 26238 }
class ____: """ Extracts useful information from the Starlette request (like form data or cookies) and adds it to the Sentry event. """ request = None # type: Request def __init__(self, request): # type: (StarletteRequestExtractor, Request) -> None self.request = request def extract_cookies_from_request(self): # type: (StarletteRequestExtractor) -> Optional[Dict[str, Any]] cookies = None # type: Optional[Dict[str, Any]] if should_send_default_pii(): cookies = self.cookies() return cookies async def extract_request_info(self): # type: (StarletteRequestExtractor) -> Optional[Dict[str, Any]] client = sentry_sdk.get_client() request_info = {} # type: Dict[str, Any] with capture_internal_exceptions(): # Add cookies if should_send_default_pii(): request_info["cookies"] = self.cookies() # If there is no body, just return the cookies content_length = await self.content_length() if not content_length: return request_info # Add annotation if body is too big if content_length and not request_body_within_bounds( client, content_length ): request_info["data"] = AnnotatedValue.removed_because_over_size_limit() return request_info # Add JSON body, if it is a JSON request json = await self.json() if json: request_info["data"] = json return request_info # Add form as key/value pairs, if request has form data form = await self.form() if form: form_data = {} for key, val in form.items(): is_file = isinstance(val, UploadFile) form_data[key] = ( val if not is_file else AnnotatedValue.removed_because_raw_data() ) request_info["data"] = form_data return request_info # Raw data, do not add body just an annotation request_info["data"] = AnnotatedValue.removed_because_raw_data() return request_info async def content_length(self): # type: (StarletteRequestExtractor) -> Optional[int] if "content-length" in self.request.headers: return int(self.request.headers["content-length"]) return None def cookies(self): # type: (StarletteRequestExtractor) -> Dict[str, Any] return self.request.cookies async def form(self): # type: (StarletteRequestExtractor) -> Any if multipart is None: return None # Parse the body first to get it cached, as Starlette does not cache form() as it # does with body() and json() https://github.com/encode/starlette/discussions/1933 # Calling `.form()` without calling `.body()` first will # potentially break the users project. await self.request.body() return await self.request.form() def is_json(self): # type: (StarletteRequestExtractor) -> bool return _is_json_content_type(self.request.headers.get("content-type")) async def json(self): # type: (StarletteRequestExtractor) -> Optional[Dict[str, Any]] if not self.is_json(): return None try: return await self.request.json() except JSONDecodeError: return None def _transaction_name_from_router(scope): # type: (StarletteScope) -> Optional[str] router = scope.get("router") if not router: return None for route in router.routes: match = route.matches(scope) if match[0] == Match.FULL: try: return route.path except AttributeError: # routes added via app.host() won't have a path attribute return scope.get("path") return None def _set_transaction_name_and_source(scope, transaction_style, request): # type: (sentry_sdk.Scope, str, Any) -> None name = None source = SOURCE_FOR_STYLE[transaction_style] if transaction_style == "endpoint": endpoint = request.scope.get("endpoint") if endpoint: name = transaction_from_function(endpoint) or None elif transaction_style == "url": name = _transaction_name_from_router(request.scope) if name is None: name = _DEFAULT_TRANSACTION_NAME source = TransactionSource.ROUTE scope.set_transaction_name(name, source=source) def _get_transaction_from_middleware(app, asgi_scope, integration): # type: (Any, Dict[str, Any], StarletteIntegration) -> Tuple[Optional[str], Optional[str]] name = None source = None if integration.transaction_style == "endpoint": name = transaction_from_function(app.__class__) source = TransactionSource.COMPONENT elif integration.transaction_style == "url": name = _transaction_name_from_router(asgi_scope) source = TransactionSource.ROUTE return name, source
StarletteRequestExtractor
python
walkccc__LeetCode
solutions/937. Reorder Data in Log Files/937.py
{ "start": 0, "end": 423 }
class ____: def reorderLogFiles(self, logs: list[str]) -> list[str]: digitLogs = [] letterLogs = [] for log in logs: i = log.index(' ') if log[i + 1].isdigit(): digitLogs.append(log) else: letterLogs.append((log[:i], log[i + 1:])) letterLogs.sort(key=lambda x: (x[1], x[0])) return [identifier + ' ' + letters for identifier, letters in letterLogs] + digitLogs
Solution
python
wandb__wandb
wandb/vendor/pygments/lexers/basic.py
{ "start": 554, "end": 4739 }
class ____(RegexLexer): """ For `BlitzMax <http://blitzbasic.com>`_ source code. .. versionadded:: 1.4 """ name = 'BlitzMax' aliases = ['blitzmax', 'bmax'] filenames = ['*.bmx'] mimetypes = ['text/x-bmx'] bmax_vopwords = r'\b(Shl|Shr|Sar|Mod)\b' bmax_sktypes = r'@{1,2}|[!#$%]' bmax_lktypes = r'\b(Int|Byte|Short|Float|Double|Long)\b' bmax_name = r'[a-z_]\w*' bmax_var = (r'(%s)(?:(?:([ \t]*)(%s)|([ \t]*:[ \t]*\b(?:Shl|Shr|Sar|Mod)\b)' r'|([ \t]*)(:)([ \t]*)(?:%s|(%s)))(?:([ \t]*)(Ptr))?)') % \ (bmax_name, bmax_sktypes, bmax_lktypes, bmax_name) bmax_func = bmax_var + r'?((?:[ \t]|\.\.\n)*)([(])' flags = re.MULTILINE | re.IGNORECASE tokens = { 'root': [ # Text (r'[ \t]+', Text), (r'\.\.\n', Text), # Line continuation # Comments (r"'.*?\n", Comment.Single), (r'([ \t]*)\bRem\n(\n|.)*?\s*\bEnd([ \t]*)Rem', Comment.Multiline), # Data types ('"', String.Double, 'string'), # Numbers (r'[0-9]+\.[0-9]*(?!\.)', Number.Float), (r'\.[0-9]*(?!\.)', Number.Float), (r'[0-9]+', Number.Integer), (r'\$[0-9a-f]+', Number.Hex), (r'\%[10]+', Number.Bin), # Other (r'(?:(?:(:)?([ \t]*)(:?%s|([+\-*/&|~]))|Or|And|Not|[=<>^]))' % (bmax_vopwords), Operator), (r'[(),.:\[\]]', Punctuation), (r'(?:#[\w \t]*)', Name.Label), (r'(?:\?[\w \t]*)', Comment.Preproc), # Identifiers (r'\b(New)\b([ \t]?)([(]?)(%s)' % (bmax_name), bygroups(Keyword.Reserved, Text, Punctuation, Name.Class)), (r'\b(Import|Framework|Module)([ \t]+)(%s\.%s)' % (bmax_name, bmax_name), bygroups(Keyword.Reserved, Text, Keyword.Namespace)), (bmax_func, bygroups(Name.Function, Text, Keyword.Type, Operator, Text, Punctuation, Text, Keyword.Type, Name.Class, Text, Keyword.Type, Text, Punctuation)), (bmax_var, bygroups(Name.Variable, Text, Keyword.Type, Operator, Text, Punctuation, Text, Keyword.Type, Name.Class, Text, Keyword.Type)), (r'\b(Type|Extends)([ \t]+)(%s)' % (bmax_name), bygroups(Keyword.Reserved, Text, Name.Class)), # Keywords (r'\b(Ptr)\b', Keyword.Type), (r'\b(Pi|True|False|Null|Self|Super)\b', Keyword.Constant), (r'\b(Local|Global|Const|Field)\b', Keyword.Declaration), (words(( 'TNullMethodException', 'TNullFunctionException', 'TNullObjectException', 'TArrayBoundsException', 'TRuntimeException'), prefix=r'\b', suffix=r'\b'), Name.Exception), (words(( 'Strict', 'SuperStrict', 'Module', 'ModuleInfo', 'End', 'Return', 'Continue', 'Exit', 'Public', 'Private', 'Var', 'VarPtr', 'Chr', 'Len', 'Asc', 'SizeOf', 'Sgn', 'Abs', 'Min', 'Max', 'New', 'Release', 'Delete', 'Incbin', 'IncbinPtr', 'IncbinLen', 'Framework', 'Include', 'Import', 'Extern', 'EndExtern', 'Function', 'EndFunction', 'Type', 'EndType', 'Extends', 'Method', 'EndMethod', 'Abstract', 'Final', 'If', 'Then', 'Else', 'ElseIf', 'EndIf', 'For', 'To', 'Next', 'Step', 'EachIn', 'While', 'Wend', 'EndWhile', 'Repeat', 'Until', 'Forever', 'Select', 'Case', 'Default', 'EndSelect', 'Try', 'Catch', 'EndTry', 'Throw', 'Assert', 'Goto', 'DefData', 'ReadData', 'RestoreData'), prefix=r'\b', suffix=r'\b'), Keyword.Reserved), # Final resolve (for variable names and such) (r'(%s)' % (bmax_name), Name.Variable), ], 'string': [ (r'""', String.Double), (r'"C?', String.Double, '#pop'), (r'[^"]+', String.Double), ], }
BlitzMaxLexer
python
huggingface__transformers
tests/models/bigbird_pegasus/test_modeling_bigbird_pegasus.py
{ "start": 9298, "end": 18951 }
class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( BigBirdPegasusModel, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForSequenceClassification, BigBirdPegasusForQuestionAnswering, ) if is_torch_available() else () ) pipeline_model_mapping = ( { "feature-extraction": BigBirdPegasusModel, "question-answering": BigBirdPegasusForQuestionAnswering, "summarization": BigBirdPegasusForConditionalGeneration, "text-classification": BigBirdPegasusForSequenceClassification, "text-generation": BigBirdPegasusForCausalLM, "text2text-generation": BigBirdPegasusForConditionalGeneration, "translation": BigBirdPegasusForConditionalGeneration, "zero-shot": BigBirdPegasusForSequenceClassification, } if is_torch_available() else {} ) is_encoder_decoder = True test_missing_keys = False # TODO: Fix the failed tests def is_pipeline_test_to_skip( self, pipeline_test_case_name, config_class, model_architecture, tokenizer_name, image_processor_name, feature_extractor_name, processor_name, ): if pipeline_test_case_name == "QAPipelineTests" and not tokenizer_name.endswith("Fast"): return True return False def setUp(self): self.model_tester = BigBirdPegasusModelTester(self) self.config_tester = ConfigTester(self, config_class=BigBirdPegasusConfig) def test_config(self): self.config_tester.run_common_tests() def test_save_load_strict(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: model = model_class(config) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True) self.assertEqual(info["missing_keys"], set()) def test_decoder_model_past_with_large_inputs(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) def test_encoder_decoder_model_standalone(self): config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs) def test_model_various_attn_type(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() for type in ["original_full", "block_sparse"]: config_and_inputs[0].attention_type = type self.model_tester.create_and_check_model(*config_and_inputs) def test_generate_without_input_ids(self): if self.model_tester.attention_type == "block_sparse": self.skipTest( "Cannot pass for BigBird-block-sparse attention since input_ids must be multiple of block_size" ) super().test_generate_without_input_ids() def test_retain_grad_hidden_states_attentions(self): if self.model_tester.attention_type == "block_sparse": # this test can't pass since attention matrix (which is getting returned) can't have gradients (& just 0 at many locations) self.skipTest(reason="Cannot pass since returned attention matrix can't have gradients") super().test_retain_grad_hidden_states_attentions() # BigBirdPegasusForSequenceClassification does not support inputs_embeds def test_inputs_embeds(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in ( BigBirdPegasusModel, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, ): model = model_class(config) model.to(torch_device) model.eval() inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) if not self.is_encoder_decoder: input_ids = inputs["input_ids"] del inputs["input_ids"] else: encoder_input_ids = inputs["input_ids"] decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids) del inputs["input_ids"] inputs.pop("decoder_input_ids", None) wte = model.get_input_embeddings() if not self.is_encoder_decoder: inputs["inputs_embeds"] = wte(input_ids) else: inputs["inputs_embeds"] = wte(encoder_input_ids) inputs["decoder_inputs_embeds"] = wte(decoder_input_ids) with torch.no_grad(): model(**inputs)[0] @require_torch_fp16 def test_generate_fp16(self): config, input_dict = self.model_tester.prepare_config_and_inputs() input_dict.pop("decoder_attention_mask") input_dict.pop("decoder_input_ids") model = BigBirdPegasusForConditionalGeneration(config).eval().to(torch_device) model.half() model.generate(**input_dict) model.generate(**input_dict, do_sample=True, early_stopping=False, num_return_sequences=3) @slow def test_batched_forward_original_full(self): self._check_batched_forward(attn_type="original_full") @slow def test_batched_forward_block_sparse(self): self._check_batched_forward(attn_type="block_sparse", tolerance=1e-1) def _check_batched_forward(self, attn_type, tolerance=1e-3): config, _ = self.model_tester.prepare_config_and_inputs() config.max_position_embeddings = 128 config.block_size = 16 config.attention_type = attn_type model = BigBirdPegasusForConditionalGeneration(config).to(torch_device) model.eval() chunk_length = 32 sample_with_padding = [3, 8, 11] * chunk_length + [0] * chunk_length sample_without_padding = [4, 7, 9, 13] * chunk_length target_ids_without_padding = [2, 3] * 8 target_ids_with_padding = [7, 8] * 6 + 4 * [-100] attention_mask = torch.tensor( [[1] * 3 * chunk_length + [0] * chunk_length, [1] * 4 * chunk_length], device=torch_device, dtype=torch.long, ) input_ids = torch.tensor([sample_with_padding, sample_without_padding], device=torch_device, dtype=torch.long) labels = torch.tensor( [target_ids_without_padding, target_ids_with_padding], device=torch_device, dtype=torch.long ) with torch.no_grad(): logits_batched = model(input_ids=input_ids, attention_mask=attention_mask, labels=labels).logits with torch.no_grad(): logits_single_first = model(input_ids=input_ids[:1, :-chunk_length], labels=labels[:1]).logits torch.testing.assert_close(logits_batched[0, -3:], logits_single_first[0, -3:], rtol=tolerance, atol=tolerance) with torch.no_grad(): logits_single_second = model(input_ids=input_ids[1:], labels=labels[1:, :-4]).logits torch.testing.assert_close(logits_batched[1, :3], logits_single_second[0, :3], rtol=tolerance, atol=tolerance) def test_auto_padding(self): ids = [[7, 6, 9] * 65] config, _ = self.model_tester.prepare_config_and_inputs() input_ids = torch.tensor(ids, device=torch_device, dtype=torch.long) attention_mask = input_ids.new_ones(input_ids.shape) decoder_input_ids = torch.tensor([[33, 5, 8] * 3], device=torch_device, dtype=torch.long) config.block_size = 8 model = BigBirdPegasusForConditionalGeneration(config).eval().to(torch_device) output1 = model(input_ids=input_ids, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids)[ "logits" ] ids = [[7, 6, 9] * 65 + [0] * 5] input_ids = torch.tensor(ids, device=torch_device, dtype=torch.long) attention_mask = torch.tensor([[1] * 3 * 65 + [0] * 5], device=torch_device, dtype=torch.long) output2 = model(input_ids=input_ids, attention_mask=attention_mask, decoder_input_ids=decoder_input_ids)[ "logits" ] torch.testing.assert_close(output1, output2, rtol=1e-5, atol=1e-5) def test_for_change_to_full_attn(self): self.model_tester.seq_length = 9 config, input_dict = self.model_tester.prepare_config_and_inputs() # automatic switch will happen config.attention_type = "block_sparse" model = BigBirdPegasusForConditionalGeneration(config).eval().to(torch_device) state_dict = model.state_dict() outputs1 = model(**input_dict)["logits"] config.attention_type = "original_full" model = BigBirdPegasusForConditionalGeneration(config).eval().to(torch_device) model.load_state_dict(state_dict) outputs2 = model(**input_dict)["logits"] torch.testing.assert_close(outputs1, outputs2, rtol=1e-5, atol=1e-5) @unittest.skip( reason="This architecture has tied weights by default and there is no way to remove it, check: https://github.com/huggingface/transformers/pull/31771#issuecomment-2210915245" ) def test_load_save_without_tied_weights(self): pass @require_torch @require_sentencepiece @require_tokenizers @slow
BigBirdPegasusModelTest
python
numba__numba
numba/tests/test_sets.py
{ "start": 4690, "end": 6313 }
class ____(MemoryLeakMixin, TestCase): def setUp(self): super(BaseTest, self).setUp() self.rnd = random.Random(42) def _range(self, stop): return np.arange(int(stop)).tolist() def _random_choice(self, seq, n): """ Choose *n* possibly duplicate items from sequence. """ l = [self.rnd.choice(list(seq)) for i in range(n)] if isinstance(seq, np.ndarray): return np.array(l, dtype=seq.dtype) else: return l def duplicates_array(self, n): """ Get a 1d array with many duplicate values. """ a = self._range(np.sqrt(n)) return self._random_choice(a, n) def sparse_array(self, n): """ Get a 1d array with values spread around. """ # Note two calls to sparse_array() should generate reasonable overlap a = self._range(n ** 1.3) return self._random_choice(a, n) def _assert_equal_unordered(self, a, b): if isinstance(a, tuple): self.assertIsInstance(b, tuple) for u, v in zip(a, b): self._assert_equal_unordered(u, v) elif isinstance(a, list): self.assertIsInstance(b, list) self.assertPreciseEqual(sorted(a), sorted(b)) else: self.assertPreciseEqual(a, b) def unordered_checker(self, pyfunc): cfunc = jit(nopython=True)(pyfunc) def check(*args): expected = pyfunc(*args) got = cfunc(*args) self._assert_equal_unordered(expected, got) return check
BaseTest
python
walkccc__LeetCode
solutions/431. Encode N-ary Tree to Binary Tree/431.py
{ "start": 0, "end": 1205 }
class ____: # Encodes an n-ary tree to a binary tree. def encode(self, root: 'Node') -> TreeNode | None: if not root: return None rootTreeNode = TreeNode(root.val) q = collections.deque([(root, rootTreeNode)]) while q: parentNode, parentTreeNode = q.popleft() prevTreeNode = None headTreeNode = None for child in parentNode.children: currTreeNode = TreeNode(child.val) if prevTreeNode: prevTreeNode.right = currTreeNode else: headTreeNode = currTreeNode prevTreeNode = currTreeNode q.append((child, currTreeNode)) parentTreeNode.left = headTreeNode return rootTreeNode # Decodes your binary tree to an n-ary tree. def decode(self, root: TreeNode | None) -> 'Node': if not root: return None rootNode = Node(root.val, []) q = collections.deque([(rootNode, root)]) while q: parentNode, parentTreeNode = q.popleft() sibling = parentTreeNode.left while sibling: currNode = Node(sibling.val, []) parentNode.children.append(currNode) q.append((currNode, sibling)) sibling = sibling.right return rootNode
Codec
python
boto__boto3
tests/unit/dynamodb/test_conditions.py
{ "start": 4249, "end": 6545 }
class ____(TestK): def setUp(self): self.attr = Attr('mykey') self.attr2 = Attr('myotherkey') self.value = 'foo' self.value2 = 'foo2' def test_ne(self): assert self.attr.ne(self.value) == NotEquals(self.attr, self.value) def test_is_in(self): assert self.attr.is_in([self.value]) == In(self.attr, [self.value]) def test_exists(self): assert self.attr.exists() == AttributeExists(self.attr) def test_not_exists(self): assert self.attr.not_exists() == AttributeNotExists(self.attr) def test_contains(self): assert self.attr.contains(self.value) == Contains( self.attr, self.value ) def test_size(self): assert self.attr.size() == Size(self.attr) def test_attribute_type(self): assert self.attr.attribute_type(self.value) == AttributeType( self.attr, self.value ) def test_ne_equality(self): attr_copy = copy.deepcopy(self.attr) comp = self.attr.ne(self.value) comp2 = attr_copy.ne(self.value) assert comp == comp2 def test_is_in_equality(self): attr_copy = copy.deepcopy(self.attr) comp = self.attr.is_in([self.value]) comp2 = attr_copy.is_in([self.value]) assert comp == comp2 def test_exists_equality(self): attr_copy = copy.deepcopy(self.attr) comp = self.attr.exists() comp2 = attr_copy.exists() assert comp == comp2 def test_not_exists_equality(self): attr_copy = copy.deepcopy(self.attr) comp = self.attr.not_exists() comp2 = attr_copy.not_exists() assert comp == comp2 def test_contains_equality(self): attr_copy = copy.deepcopy(self.attr) comp = self.attr.contains(self.value) comp2 = attr_copy.contains(self.value) assert comp == comp2 def test_size_equality(self): attr_copy = copy.deepcopy(self.attr) comp = self.attr.size() comp2 = attr_copy.size() assert comp == comp2 def test_attribute_type_equality(self): attr_copy = copy.deepcopy(self.attr) comp = self.attr.attribute_type(self.value) comp2 = attr_copy.attribute_type(self.value) assert comp == comp2
TestA
python
getsentry__sentry
src/sentry/web/frontend/setup_wizard.py
{ "start": 1974, "end": 11238 }
class ____(BaseView): def handle_auth_required(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: if request.GET.get("signup") == "1" and settings.SENTRY_SIGNUP_URL: uri_components = list(urlparse(absolute_uri(request.get_full_path()))) # get the params from the url and apply it to the signup url params_for_signup = dict(parse_qsl(uri_components[4])) # remove the signup query param params_for_signup.pop("signup", None) # remove query params from next url uri_components[4] = "" # add the params to the signup url params = {"next": urlunparse(uri_components), **params_for_signup} return self.redirect(add_params_to_url(settings.SENTRY_SIGNUP_URL, params)) if request.GET.get("partner") is not None: redirect_to = auth.get_login_url() return self.redirect(add_params_to_url(redirect_to, request.GET)) return super().handle_auth_required(request, *args, **kwargs) @allow_cors_options def get(self, request: HttpRequest, wizard_hash) -> HttpResponseBase: """ This opens a page where with an active session fill stuff into the cache Redirects to organization whenever cache has been deleted """ if is_demo_user(request.user): return HttpResponse(status=403) elif not request.user.is_authenticated: return HttpResponse(status=400) context = { "hash": wizard_hash, "enableProjectSelection": False, "react_config": get_client_config(request, self.active_organization), } cache_key = f"{SETUP_WIZARD_CACHE_KEY}{wizard_hash}" org_slug = request.GET.get("org_slug") project_slug = request.GET.get("project_slug") wizard_data = default_cache.get(cache_key) if wizard_data is None: return self.redirect_to_org(request) member_org_ids = OrganizationMemberMapping.objects.filter( user_id=request.user.id ).values_list("organization_id", flat=True) org_mappings = OrganizationMapping.objects.filter( organization_id__in=member_org_ids, status=OrganizationStatus.ACTIVE, ).order_by("-date_created") # {'us': {'org_ids': [...], 'projects': [...], 'keys': [...]}} region_data_map: dict[str, dict[str, list[str]]] = defaultdict(lambda: defaultdict(list)) org_mappings_map = {} for mapping in org_mappings: region_data_map[mapping.region_name]["org_ids"].append(mapping.organization_id) serialized_mapping = serialize_org_mapping(mapping) org_mappings_map[mapping.organization_id] = serialized_mapping context["organizations"] = list(org_mappings_map.values()) context["enableProjectSelection"] = True # If org_slug and project_slug are provided, we will use them to select the project # If the project is not found or the slugs are not provided, we will show the project selection if org_slug is not None and project_slug is not None: target_org_mapping = next( (mapping for mapping in org_mappings if mapping.slug == org_slug), None ) if target_org_mapping is not None: target_project = project_service.get_by_slug( slug=project_slug, organization_id=target_org_mapping.organization_id ) if target_project is not None: cache_data = get_cache_data( mapping=target_org_mapping, project=target_project, user=request.user ) default_cache.set(cache_key, cache_data, SETUP_WIZARD_CACHE_TIMEOUT) context["enableProjectSelection"] = False return render_to_response("sentry/setup-wizard.html", context, request) @allow_cors_options def post(self, request: HttpRequest, wizard_hash=None) -> HttpResponse: """ This updates the cache content for a specific hash """ if is_demo_user(request.user): return HttpResponse( status=403, content='{"error":"Forbidden"}', content_type="application/json" ) elif not request.user.is_authenticated: return HttpResponse( status=400, content='{"error":"Unauthorized"}', content_type="application/json" ) json_data = json.loads(request.body) organization_id = json_data.get("organizationId", None) project_id = json_data.get("projectId", None) if organization_id is None or project_id is None or wizard_hash is None: return HttpResponse( status=400, content='{"error":"Some parameters are missing"}', content_type="application/json", ) member_org_ids = OrganizationMemberMapping.objects.filter( user_id=request.user.id ).values_list("organization_id", flat=True) mapping = get_object_or_404( OrganizationMapping, organization_id=organization_id, organization_id__in=member_org_ids, ) project = project_service.get_by_id(organization_id=mapping.organization_id, id=project_id) if project is None: return HttpResponse( status=404, content='{"error":"Project not found"}', content_type="application/json", ) try: cache_data = get_cache_data(mapping=mapping, project=project, user=request.user) except Http404: return HttpResponse( status=404, content='{"error":"No DSN found for this project"}', content_type="application/json", ) key = f"{SETUP_WIZARD_CACHE_KEY}{wizard_hash}" default_cache.set(key, cache_data, SETUP_WIZARD_CACHE_TIMEOUT) return HttpResponse(status=200, content="{}", content_type="application/json") @allow_cors_options def options(self, request, *args, **kwargs): return super().options(request, *args, **kwargs) @allow_cors_options def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def serialize_org_mapping(mapping: OrganizationMapping): status = OrganizationStatus(mapping.status) return { "id": mapping.organization_id, "name": mapping.name, "slug": mapping.slug, "region": mapping.region_name, "status": {"id": status.name.lower(), "name": status.label}, } def serialize_project_key(project_key: RpcProjectKey): return { "dsn": {"public": project_key.dsn_public}, "isActive": project_key.is_active, } def serialize_project(project: RpcProject, organization: dict, keys: list[dict]): return { "slug": project.slug, "id": project.id, "name": project.name, "platform": project.platform, "status": STATUS_LABELS.get(project.status, "unknown"), "organization": organization, "keys": keys, } def get_cache_data( mapping: OrganizationMapping, project: RpcProject, user: User | AnonymousUser | RpcUser ): project_key = project_key_service.get_default_project_key( organization_id=mapping.organization_id, project_id=project.id, ) if project_key is None: raise Http404() enriched_project = serialize_project( project=project, # The wizard only reads the a few fields so serializing the mapping should work fine organization=serialize_org_mapping(mapping), keys=[serialize_project_key(project_key)], ) serialized_token = get_org_token(mapping, user) return {"apiKeys": serialized_token, "projects": [enriched_project]} def get_token(mappings: list[OrganizationMapping], user: RpcUser): can_use_org_tokens = len(mappings) == 1 # If only one org, try to generate an org auth token if can_use_org_tokens: mapping = mappings[0] token = get_org_token(mapping=mapping, user=user) if token is not None: return token # Otherwise, generate a user token token = ApiToken.objects.create( user_id=user.id, scope_list=["project:releases"], token_type=AuthTokenType.USER, expires_at=None, ) return serialize(token) def get_org_token(mapping: OrganizationMapping, user: User | RpcUser | AnonymousUser): try: token_str = generate_token( mapping.slug, generate_region_url(region_name=mapping.region_name) ) except SystemUrlPrefixMissingException: return None token_hashed = hash_token(token_str) token = OrgAuthToken.objects.create( name=f"Generated by Sentry Wizard on {date.today()}", organization_id=mapping.organization_id, scope_list=["org:ci"], created_by_id=user.id, token_last_characters=token_str[-4:], token_hashed=token_hashed, ) return serialize(token, user, token=token_str)
SetupWizardView
python
skorch-dev__skorch
skorch/tests/callbacks/test_logging.py
{ "start": 597, "end": 8513 }
class ____: # fields logged by on_train_begin and on_train_end NUM_BASE_METRICS = 9 @pytest.fixture def net_cls(self): from skorch import NeuralNetClassifier return NeuralNetClassifier @pytest.fixture def data(self, classifier_data): X, y = classifier_data # accelerate training since we don't care for the loss X, y = X[:40], y[:40] return X, y @pytest.fixture def neptune_logger_cls(self): from skorch.callbacks import NeptuneLogger return NeptuneLogger @pytest.fixture def neptune_run_object(self): import neptune run = neptune.init_run( project="tests/dry-run", mode="offline", ) return run @pytest.fixture def mock_experiment(self, neptune_run_object): with neptune_run_object as run: return unittest.mock.create_autospec(run) @pytest.fixture def net_fitted( self, net_cls, classifier_module, data, neptune_logger_cls, mock_experiment, ): return net_cls( classifier_module, callbacks=[neptune_logger_cls(mock_experiment)], max_epochs=3, ).fit(*data) def test_experiment_closed_automatically(self, net_fitted, mock_experiment): assert mock_experiment.stop.call_count == 1 def test_version_logged(self, net_fitted, mock_experiment): assert mock_experiment.exists("source_code/integrations/skorch") def test_experiment_log_call_counts(self, net_fitted, mock_experiment): # (3 x dur + 3 x train_loss + 3 x valid_loss + 3 x valid_acc = 12) + base metrics assert mock_experiment.__getitem__.call_count == 12 + self.NUM_BASE_METRICS def test_experiment_not_closed( self, net_cls, classifier_module, data, neptune_logger_cls, mock_experiment, ): net_cls( classifier_module, callbacks=[ neptune_logger_cls(mock_experiment, close_after_train=False)], max_epochs=2, ).fit(*data) assert mock_experiment.stop.call_count == 0 def test_ignore_keys( self, net_cls, classifier_module, data, neptune_logger_cls, mock_experiment, ): # ignore 'dur' and 'valid_loss', 'unknown' doesn't exist but # this should not cause a problem npt = neptune_logger_cls( mock_experiment, keys_ignored=['dur', 'valid_loss', 'unknown']) net_cls( classifier_module, callbacks=[npt], max_epochs=3, ).fit(*data) # (3 epochs x 2 epoch metrics = 6 calls) + base metrics assert mock_experiment.__getitem__.call_count == 6 + self.NUM_BASE_METRICS def test_keys_ignored_is_string(self, neptune_logger_cls, mock_experiment): npt = neptune_logger_cls( mock_experiment, keys_ignored='a-key').initialize() expected = {'a-key', 'batches'} assert npt.keys_ignored_ == expected def test_fit_with_real_experiment( self, net_cls, classifier_module, data, neptune_logger_cls, neptune_run_object, ): net = net_cls( classifier_module, callbacks=[neptune_logger_cls(neptune_run_object)], max_epochs=5, ) net.fit(*data) assert neptune_run_object.exists('training/epoch_duration') assert neptune_run_object.exists('training/train/epoch/loss') assert neptune_run_object.exists('training/validation/epoch/loss') assert neptune_run_object.exists('training/validation/epoch/acc') # Checkpoint callback was not used assert not neptune_run_object.exists('training/model/checkpoint') def test_fit_with_handler( self, net_cls, classifier_module, data, neptune_logger_cls, neptune_run_object, ): net = net_cls( classifier_module, callbacks=[neptune_logger_cls(neptune_run_object['my_namespace'])], max_epochs=5, ) net.fit(*data) assert neptune_run_object.exists('my_namespace/training/epoch_duration') assert neptune_run_object.exists('my_namespace/training/train/epoch/loss') assert neptune_run_object.exists('my_namespace/training/validation/epoch/loss') assert neptune_run_object.exists('my_namespace/training/validation/epoch/acc') # Checkpoint callback was not used assert not neptune_run_object.exists('my_namespace/training/model/checkpoint') def test_log_on_batch_level_on( self, net_cls, classifier_module, data, neptune_logger_cls, mock_experiment, ): net = net_cls( classifier_module, callbacks=[neptune_logger_cls(mock_experiment, log_on_batch_end=True)], max_epochs=5, batch_size=4, train_split=False ) net.fit(*data) # (5 epochs x (40/4 batches x 2 batch metrics + 2 epoch metrics) = 110 calls) + base metrics assert mock_experiment.__getitem__.call_count == 110 + self.NUM_BASE_METRICS mock_experiment['training']['train']['batch']['batch_size'].append.assert_any_call(4) def test_log_on_batch_level_off( self, net_cls, classifier_module, data, neptune_logger_cls, mock_experiment, ): net = net_cls( classifier_module, callbacks=[neptune_logger_cls(mock_experiment, log_on_batch_end=False)], max_epochs=5, batch_size=4, train_split=False ) net.fit(*data) # (5 epochs x 2 epoch metrics = 10 calls) + base metrics assert mock_experiment.__getitem__.call_count == 10 + self.NUM_BASE_METRICS call_args = mock_experiment['training']['train'].__getitem__.call_args_list assert call('epoch') in call_args assert call('batch') not in call_args call_args = mock_experiment['training']['validation'].__getitem__.call_args_list assert call('epoch') in call_args assert call('batch') not in call_args def test_fit_with_real_experiment_saving_checkpoints( self, net_cls, classifier_module, data, neptune_logger_cls, neptune_run_object, ): from neptune.attributes.file_set import FileSet from skorch.callbacks import Checkpoint with tempfile.TemporaryDirectory() as directory: net = net_cls( classifier_module, callbacks=[ neptune_logger_cls( run=neptune_run_object, close_after_train=False, ), Checkpoint(dirname=directory), ], max_epochs=5, ) net.fit(*data) neptune_run_object['training/model/checkpoint'].upload_files(directory) assert neptune_run_object.exists('training/train/epoch/loss') assert neptune_run_object.exists('training/validation/epoch/loss') assert neptune_run_object.exists('training/validation/epoch/acc') assert neptune_run_object.exists('training/model/checkpoint') assert isinstance( neptune_run_object.get_structure()['training']['model']['checkpoint'], FileSet, ) neptune_run_object.stop() @pytest.mark.skipif( not sacred_installed, reason='Sacred is not installed')
TestNeptune
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 147702, "end": 148984 }
class ____(sgqlc.types.Input): """Autogenerated input type of CancelSponsorship""" __schema__ = github_schema __field_names__ = ("sponsor_id", "sponsor_login", "sponsorable_id", "sponsorable_login", "client_mutation_id") sponsor_id = sgqlc.types.Field(ID, graphql_name="sponsorId") """The ID of the user or organization who is acting as the sponsor, paying for the sponsorship. Required if sponsorLogin is not given. """ sponsor_login = sgqlc.types.Field(String, graphql_name="sponsorLogin") """The username of the user or organization who is acting as the sponsor, paying for the sponsorship. Required if sponsorId is not given. """ sponsorable_id = sgqlc.types.Field(ID, graphql_name="sponsorableId") """The ID of the user or organization who is receiving the sponsorship. Required if sponsorableLogin is not given. """ sponsorable_login = sgqlc.types.Field(String, graphql_name="sponsorableLogin") """The username of the user or organization who is receiving the sponsorship. Required if sponsorableId is not given. """ client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation."""
CancelSponsorshipInput
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_permissions.py
{ "start": 3874, "end": 4211 }
class ____: @require_permission_check(Permissions.LAUNCH_PIPELINE_EXECUTION) def mutate(self, graphene_info, **kwargs): location_name = kwargs["locationName"] assert_permission_for_location( graphene_info, Permissions.LAUNCH_PIPELINE_EXECUTION, location_name )
FakeEnumLocationPermissionMutation
python
pandas-dev__pandas
asv_bench/benchmarks/frame_ctor.py
{ "start": 2930, "end": 3156 }
class ____: goal_time = 0.2 def setup(self): N = 1000 M = 100 self.data = [list(range(M)) for i in range(N)] def time_frame_from_lists(self): self.df = DataFrame(self.data)
FromLists
python
dagster-io__dagster
python_modules/dagster/dagster/_core/types/dagster_type.py
{ "start": 21466, "end": 22948 }
class ____(DagsterType): def __init__(self, inner_type: DagsterType): inner_type = resolve_dagster_type(inner_type) if inner_type is Nothing: raise DagsterInvalidDefinitionError( "Type Nothing can not be wrapped in List or Optional" ) key = "Optional." + cast(str, inner_type.key) self.inner_type = inner_type super(OptionalType, self).__init__( key=key, name=None, kind=DagsterTypeKind.NULLABLE, type_check_fn=self.type_check_method, loader=_create_nullable_input_schema(inner_type), # This throws a type error with Py typing_type=t.Optional[inner_type.typing_type], ) @property def display_name(self) -> str: return self.inner_type.display_name + "?" def type_check_method(self, context, value): return ( TypeCheck(success=True) if value is None else self.inner_type.type_check(context, value) ) @property def inner_types(self): return [self.inner_type] + self.inner_type.inner_types # pyright: ignore[reportOperatorIssue] @property def type_param_keys(self): return [self.inner_type.key] @property def supports_fan_in(self): return self.inner_type.supports_fan_in def get_inner_type_for_fan_in(self): return self.inner_type.get_inner_type_for_fan_in()
OptionalType
python
getsentry__sentry
tests/sentry/integrations/api/endpoints/test_doc_integrations.py
{ "start": 4752, "end": 10765 }
class ____(DocIntegrationsTest): method = "POST" payload: dict[str, Any] = { "name": "Enemy", "author": "Imagine Dragons", "description": "An opening theme song 👀", "url": "https://github.com/getsentry/sentry/", "popularity": 5, "resources": [{"title": "Docs", "url": "https://github.com/getsentry/sentry/"}], "features": [1, 2, 3], } ignored_keys = ["is_draft", "metadata"] def setUp(self) -> None: super().setUp() self.login_as(user=self.staff_user, staff=True) def test_staff_create_doc(self) -> None: """ Tests that a draft DocIntegration is created for superuser requests along with all the appropriate IntegrationFeatures """ response = self.get_success_response(status_code=status.HTTP_201_CREATED, **self.payload) doc = DocIntegration.objects.get(name=self.payload["name"], author=self.payload["author"]) assert serialize(doc) == response.data assert doc.is_draft features = IntegrationFeature.objects.filter( target_id=doc.id, target_type=IntegrationTypes.DOC_INTEGRATION.value ) assert features.exists() assert len(features) == 3 for feature in features: # Ensure payload features are in the database assert feature.feature in self.payload["features"] # Ensure they are also serialized in the response assert serialize(feature) in response.data["features"] # TODO(schew2381): Change test to check superuser can't access POST def test_superuser_create_doc(self) -> None: """ Tests that a draft DocIntegration is created for superuser requests along with all the appropriate IntegrationFeatures """ self.login_as(user=self.superuser, superuser=True) response = self.get_success_response(status_code=status.HTTP_201_CREATED, **self.payload) doc = DocIntegration.objects.get(name=self.payload["name"], author=self.payload["author"]) assert serialize(doc) == response.data assert doc.is_draft features = IntegrationFeature.objects.filter( target_id=doc.id, target_type=IntegrationTypes.DOC_INTEGRATION.value ) assert features.exists() assert len(features) == 3 for feature in features: # Ensure payload features are in the database assert feature.feature in self.payload["features"] # Ensure they are also serialized in the response assert serialize(feature) in response.data["features"] def test_create_invalid_auth(self) -> None: """ Tests that the POST endpoint is only accessible for superusers """ self.login_as(user=self.user) self.get_error_response(status_code=status.HTTP_403_FORBIDDEN, **self.payload) def test_create_repeated_slug(self) -> None: """ Tests that repeated names throw errors when generating slugs """ payload = {**self.payload, "name": self.doc_1.name} response = self.get_error_response(status_code=status.HTTP_400_BAD_REQUEST, **payload) assert "name" in response.data.keys() def test_generated_slug_not_entirely_numeric(self) -> None: """ Tests that generated slug based on name is not entirely numeric """ payload = {**self.payload, "name": "1234"} response = self.get_success_response(status_code=status.HTTP_201_CREATED, **payload) slug = response.data["slug"] assert slug.startswith("1234-") assert not slug.isdecimal() def test_create_invalid_metadata(self) -> None: """ Tests that incorrectly structured metadata throws an error """ invalid_resources = { "not_an_array": {}, "extra_keys": [{**self.payload["resources"][0], "extra": "key"}], "missing_keys": [{"title": "Missing URL field"}], } for resources in invalid_resources.values(): payload = {**self.payload, "resources": resources} response = self.get_error_response(status_code=status.HTTP_400_BAD_REQUEST, **payload) assert "metadata" in response.data.keys() def test_create_empty_metadata(self) -> None: """ Tests that sending no metadata keys does not trigger any server/database errors """ payload = {**self.payload} del payload["resources"] response = self.get_success_response(status_code=status.HTTP_201_CREATED, **payload) assert "resources" not in response.data.keys() def test_create_ignore_keys(self) -> None: """ Tests that certain reserved keys cannot be overridden by the request payload. They must be created by the API. """ payload = {**self.payload, "is_draft": False, "metadata": {"should": "not override"}} self.get_success_response(status_code=status.HTTP_201_CREATED, **payload) doc = DocIntegration.objects.get(name=self.payload["name"], author=self.payload["author"]) # Ensure the DocIntegration was not created with the ignored keys' values for key in self.ignored_keys: assert getattr(doc, key) is not payload[key] def test_create_duplicate_features(self) -> None: """ Tests that providing duplicate keys do not result in a server error; instead, the excess are ignored. """ payload = {**self.payload, "features": [0, 0, 0, 0, 1, 1, 1, 2]} self.get_success_response(status_code=status.HTTP_201_CREATED, **payload) doc = DocIntegration.objects.get(name=self.payload["name"], author=self.payload["author"]) features = IntegrationFeature.objects.filter( target_id=doc.id, target_type=IntegrationTypes.DOC_INTEGRATION.value ) assert features.exists() assert len(features) == 3
PostDocIntegrationsTest
python
pytorch__pytorch
test/inductor/test_group_batch_fusion.py
{ "start": 547, "end": 1445 }
class ____(torch.nn.Module): def __init__( self, d_model: int, size: int, device="cuda", ) -> None: super().__init__() self.size = size self.device = device self.gating_proj = torch.nn.Linear(d_model, d_model).to(self.device) self.transform_proj = torch.nn.Linear(d_model, d_model).to(self.device) self.gating_func = torch.nn.Sigmoid().to(self.device) self.d_model = d_model def forward( self, inputs: list[torch.Tensor], ) -> torch.Tensor: results = [] for i in range(self.size): x = inputs[i] gating_proj = self.gating_proj(x) transform_proj = self.transform_proj(x) x = gating_proj * self.gating_func(transform_proj) results.append(x) return torch.cat(results, dim=-1)
TestHighwaySelfGating
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/math_ops/topk_op_test.py
{ "start": 9325, "end": 10403 }
class ____(test.Benchmark): def benchmarkTopK(self): for (m, n, p, use_gpu) in itertools.product( [128], [10, 100, 1000, 10000, 100000], [0.001, 0.01, 0.5, 0.99, 1.0], [False, True]): k = int(p * n) if k == 0: continue name = "m_%d_n_%d_k_%g_use_gpu_%s" % (m, n, k, use_gpu) device = "/%s:0" % ("gpu" if use_gpu else "cpu") with ops.Graph().as_default(): with ops.device(device): x = random_ops.random_uniform((m, n)) v = resource_variable_ops.ResourceVariable(x) op = nn_ops.top_k(v, k) with session.Session() as sess: self.evaluate(v.initializer) r = self.run_op_benchmark(sess, op, min_iters=100, name=name) gb_processed_input = m * n / 1.0e9 throughput = gb_processed_input / r["wall_time"] print("Benchmark: %s \t wall_time: %0.03g s \t " "Throughput: %0.03g GB/s" % (name, r["wall_time"], throughput)) sys.stdout.flush() if __name__ == "__main__": test.main()
TopKBenchmark
python
pydantic__pydantic
pydantic/fields.py
{ "start": 1595, "end": 3108 }
class ____(TypedDict, total=False): """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.from_field`.""" # TODO PEP 747: use TypeForm: annotation: type[Any] | None default_factory: Callable[[], Any] | Callable[[dict[str, Any]], Any] | None alias: str | None alias_priority: int | None validation_alias: str | AliasPath | AliasChoices | None serialization_alias: str | None title: str | None field_title_generator: Callable[[str, FieldInfo], str] | None description: str | None examples: list[Any] | None exclude: bool | None exclude_if: Callable[[Any], bool] | None gt: annotated_types.SupportsGt | None ge: annotated_types.SupportsGe | None lt: annotated_types.SupportsLt | None le: annotated_types.SupportsLe | None multiple_of: float | None strict: bool | None min_length: int | None max_length: int | None pattern: str | re.Pattern[str] | None allow_inf_nan: bool | None max_digits: int | None decimal_places: int | None union_mode: Literal['smart', 'left_to_right'] | None discriminator: str | types.Discriminator | None deprecated: Deprecated | str | bool | None json_schema_extra: JsonDict | Callable[[JsonDict], None] | None frozen: bool | None validate_default: bool | None repr: bool init: bool | None init_var: bool | None kw_only: bool | None coerce_numbers_to_str: bool | None fail_fast: bool | None
_FromFieldInfoInputs
python
astropy__astropy
astropy/utils/iers/iers.py
{ "start": 2773, "end": 2862 }
class ____(AstropyWarning): """ Generic warning class for IERS. """
IERSWarning
python
Farama-Foundation__Gymnasium
gymnasium/spaces/oneof.py
{ "start": 262, "end": 8344 }
class ____(Space[Any]): """An exclusive tuple (more precisely: the direct sum) of :class:`Space` instances. Elements of this space are elements of one of the constituent spaces. Example: >>> from gymnasium.spaces import OneOf, Box, Discrete >>> observation_space = OneOf((Discrete(2), Box(-1, 1, shape=(2,))), seed=123) >>> observation_space.sample() # the first element is the space index (Discrete in this case) and the second element is the sample from Discrete (np.int64(0), np.int64(0)) >>> observation_space.sample() # this time the Box space was sampled as index=1 (np.int64(1), array([-0.00711833, -0.7257502 ], dtype=float32)) >>> observation_space[0] Discrete(2) >>> observation_space[1] Box(-1.0, 1.0, (2,), float32) >>> len(observation_space) 2 """ def __init__( self, spaces: Iterable[Space[Any]], seed: int | typing.Sequence[int] | np.random.Generator | None = None, ): r"""Constructor of :class:`OneOf` space. The generated instance will represent the cartesian product :math:`\text{spaces}[0] \times ... \times \text{spaces}[-1]`. Args: spaces (Iterable[Space]): The spaces that are involved in the cartesian product. seed: Optionally, you can use this argument to seed the RNGs of the ``spaces`` to ensure reproducible sampling. """ assert isinstance(spaces, Iterable), f"{spaces} is not an iterable" self.spaces = tuple(spaces) assert len(self.spaces) > 0, "Empty `OneOf` spaces are not supported." for space in self.spaces: assert isinstance( space, Space ), f"{space} does not inherit from `gymnasium.Space`. Actual Type: {type(space)}" super().__init__(None, None, seed) @property def is_np_flattenable(self): """Checks whether this space can be flattened to a :class:`spaces.Box`.""" return all(space.is_np_flattenable for space in self.spaces) def seed(self, seed: int | tuple[int, ...] | None = None) -> tuple[int, ...]: """Seed the PRNG of this space and all subspaces. Depending on the type of seed, the subspaces will be seeded differently * ``None`` - All the subspaces will use a random initial seed * ``Int`` - The integer is used to seed the :class:`Tuple` space that is used to generate seed values for each of the subspaces. Warning, this does not guarantee unique seeds for all the subspaces. * ``Tuple[int, ...]`` - Values used to seed the subspaces, first value seeds the OneOf and subsequent seed the subspaces. This allows the seeding of multiple composite subspaces ``[42, 54, ...]``. Args: seed: An optional int or tuple of ints to seed the OneOf space and subspaces. See above for more details. Returns: A tuple of ints used to seed the OneOf space and subspaces """ if seed is None: super_seed = super().seed(None) return (super_seed,) + tuple(space.seed(None) for space in self.spaces) elif isinstance(seed, int): super_seed = super().seed(seed) subseeds = self.np_random.integers( np.iinfo(np.int32).max, size=len(self.spaces) ) # this is necessary such that after int or list/tuple seeding, the OneOf PRNG are equivalent super().seed(seed) return (super_seed,) + tuple( space.seed(int(subseed)) for space, subseed in zip(self.spaces, subseeds) ) elif isinstance(seed, (tuple, list)): if len(seed) != len(self.spaces) + 1: raise ValueError( f"Expects that the subspaces of seeds equals the number of subspaces + 1. Actual length of seeds: {len(seed)}, length of subspaces: {len(self.spaces)}" ) return (super().seed(seed[0]),) + tuple( space.seed(subseed) for space, subseed in zip(self.spaces, seed[1:]) ) else: raise TypeError( f"Expected None, int, or tuple of ints, actual type: {type(seed)}" ) def sample( self, mask: tuple[Any | None, ...] | None = None, probability: tuple[Any | None, ...] | None = None, ) -> tuple[int, Any]: """Generates a single random sample inside this space. This method draws independent samples from the subspaces. Args: mask: An optional tuple of optional masks for each of the subspace's samples, expects the same number of masks as spaces probability: An optional tuple of optional probability masks for each of the subspace's samples, expects the same number of probability masks as spaces Returns: Tuple of the subspace's samples """ subspace_idx = self.np_random.integers(0, len(self.spaces), dtype=np.int64) subspace = self.spaces[subspace_idx] if mask is not None and probability is not None: raise ValueError( f"Only one of `mask` or `probability` can be provided, actual values: mask={mask}, probability={probability}" ) elif mask is not None: assert isinstance( mask, tuple ), f"Expected type of `mask` is tuple, actual type: {type(mask)}" assert len(mask) == len( self.spaces ), f"Expected length of `mask` is {len(self.spaces)}, actual length: {len(mask)}" subspace_sample = subspace.sample(mask=mask[subspace_idx]) elif probability is not None: assert isinstance( probability, tuple ), f"Expected type of `probability` is tuple, actual type: {type(probability)}" assert len(probability) == len( self.spaces ), f"Expected length of `probability` is {len(self.spaces)}, actual length: {len(probability)}" subspace_sample = subspace.sample(probability=probability[subspace_idx]) else: subspace_sample = subspace.sample() return subspace_idx, subspace_sample def contains(self, x: tuple[int, Any]) -> bool: """Return boolean specifying if x is a valid member of this space.""" # subspace_idx, subspace_value = x return ( isinstance(x, tuple) and len(x) == 2 and isinstance(x[0], (np.int64, int)) and 0 <= x[0] < len(self.spaces) and self.spaces[x[0]].contains(x[1]) ) def __repr__(self) -> str: """Gives a string representation of this space.""" return "OneOf(" + ", ".join([str(s) for s in self.spaces]) + ")" def to_jsonable( self, sample_n: typing.Sequence[tuple[int, Any]] ) -> list[list[Any]]: """Convert a batch of samples from this space to a JSONable data type.""" return [ [int(i), self.spaces[i].to_jsonable([subsample])[0]] for (i, subsample) in sample_n ] def from_jsonable(self, sample_n: list[list[Any]]) -> list[tuple[Any, ...]]: """Convert a JSONable data type to a batch of samples from this space.""" return [ ( np.int64(space_idx), self.spaces[space_idx].from_jsonable([jsonable_sample])[0], ) for space_idx, jsonable_sample in sample_n ] def __getitem__(self, index: int) -> Space[Any]: """Get the subspace at specific `index`.""" return self.spaces[index] def __len__(self) -> int: """Get the number of subspaces that are involved in the cartesian product.""" return len(self.spaces) def __eq__(self, other: Any) -> bool: """Check whether ``other`` is equivalent to this instance.""" return isinstance(other, OneOf) and self.spaces == other.spaces
OneOf
python
kamyu104__LeetCode-Solutions
Python/kth-smallest-subarray-sum.py
{ "start": 33, "end": 756 }
class ____(object): def kthSmallestSubarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ def check(nums, k, x): cnt = curr = left = 0 for right in xrange(len(nums)): curr += nums[right] while curr > x: curr -= nums[left] left += 1 cnt += right-left+1 return cnt >= k left, right = min(nums), sum(nums) while left <= right: mid = left + (right-left)//2 if check(nums, k, mid): right = mid-1 else: left = mid+1 return left
Solution
python
getsentry__sentry
src/sentry/audit_log/events.py
{ "start": 8911, "end": 9258 }
class ____(AuditLogEvent): def __init__(self) -> None: super().__init__(event_id=62, name="SSO_EDIT", api_name="sso.edit") def render(self, audit_log_entry: AuditLogEntry) -> str: settings = ", ".join(f"{k} {v}" for k, v in audit_log_entry.data.items()) return "edited sso settings: " + settings
SSOEditAuditLogEvent
python
dagster-io__dagster
python_modules/dagster/dagster/_core/remote_representation/handle.py
{ "start": 4063, "end": 4530 }
class ____: instigator_name: str repository_handle: RepositoryHandle @property def repository_name(self) -> str: return self.repository_handle.repository_name @property def location_name(self) -> str: return self.repository_handle.location_name def get_remote_origin(self): return self.repository_handle.get_remote_origin().get_instigator_origin( self.instigator_name ) @record
InstigatorHandle
python
huggingface__transformers
src/transformers/models/mobilebert/modeling_mobilebert.py
{ "start": 16024, "end": 16558 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.intermediate_size, config.true_hidden_size) self.LayerNorm = NORM2FN[config.normalization_type](config.true_hidden_size, eps=config.layer_norm_eps) def forward(self, hidden_states: torch.Tensor, residual_tensor: torch.Tensor) -> torch.Tensor: layer_outputs = self.dense(hidden_states) layer_outputs = self.LayerNorm(layer_outputs + residual_tensor) return layer_outputs
FFNOutput
python
python-poetry__poetry
src/poetry/installation/operations/operation.py
{ "start": 234, "end": 1197 }
class ____(ABC): def __init__(self, reason: str | None = None, priority: float = 0) -> None: self._reason = reason self._skipped = False self._skip_reason: str | None = None self._priority = priority @property @abstractmethod def job_type(self) -> str: ... @property def reason(self) -> str | None: return self._reason @property def skipped(self) -> bool: return self._skipped @property def skip_reason(self) -> str | None: return self._skip_reason @property def priority(self) -> float: return self._priority @property @abstractmethod def package(self) -> Package: ... def format_version(self, package: Package) -> str: version: str = package.full_pretty_version return version def skip(self, reason: str) -> Self: self._skipped = True self._skip_reason = reason return self
Operation
python
dask__distributed
distributed/dashboard/components/worker.py
{ "start": 8109, "end": 9026 }
class ____(DashboardComponent): def __init__(self, worker, **kwargs): self.worker = worker self.source = ColumnDataSource({"x": [], "y": []}) x_range = DataRange1d(follow="end", follow_interval=20000, range_padding=0) fig = figure( title="Executing History", x_axis_type="datetime", y_range=[-0.1, worker.state.nthreads + 0.1], height=150, tools="", x_range=x_range, **kwargs, ) fig.line(source=self.source, x="x", y="y") fig.add_tools( ResetTool(), PanTool(dimensions="width"), WheelZoomTool(dimensions="width") ) self.root = fig @without_property_validation @log_errors def update(self): self.source.stream( {"x": [time() * 1000], "y": [self.worker.state.executing_count]}, 1000 )
ExecutingTimeSeries
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_bootstrap65.py
{ "start": 350, "end": 3250 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("bootstrap65.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "column"}) chart.axis_ids = [68407680, 68409600] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series( {"values": "=Sheet1!$A$1:$A$5", "fill": {"color": Color("automatic")}} ) chart.add_series({"values": "=Sheet1!$B$1:$B$5"}) chart.add_series({"values": "=Sheet1!$C$1:$C$5"}) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual() def test_create_file_with_automatic_string(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "column"}) chart.axis_ids = [68407680, 68409600] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series( {"values": "=Sheet1!$A$1:$A$5", "fill": {"color": "automatic"}} ) chart.add_series({"values": "=Sheet1!$B$1:$B$5"}) chart.add_series({"values": "=Sheet1!$C$1:$C$5"}) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual() def test_create_file_with_automatic_method(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({"type": "column"}) chart.axis_ids = [68407680, 68409600] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column("A1", data[0]) worksheet.write_column("B1", data[1]) worksheet.write_column("C1", data[2]) chart.add_series( {"values": "=Sheet1!$A$1:$A$5", "fill": {"color": Color.automatic()}} ) chart.add_series({"values": "=Sheet1!$B$1:$B$5"}) chart.add_series({"values": "=Sheet1!$C$1:$C$5"}) worksheet.insert_chart("E9", chart) workbook.close() self.assertExcelEqual()
TestCompareXLSXFiles
python
sympy__sympy
sympy/physics/quantum/pauli.py
{ "start": 11253, "end": 12966 }
class ____(Ket): """Ket for a two-level system quantum system. Parameters ========== n : Number The state number (0 or 1). """ def __new__(cls, n): if n not in (0, 1): raise ValueError("n must be 0 or 1") return Ket.__new__(cls, n) @property def n(self): return self.label[0] @classmethod def dual_class(self): return SigmaZBra @classmethod def _eval_hilbert_space(cls, label): return ComplexSpace(2) def _eval_innerproduct_SigmaZBra(self, bra, **hints): return KroneckerDelta(self.n, bra.n) def _apply_from_right_to_SigmaZ(self, op, **options): if self.n == 0: return self else: return S.NegativeOne * self def _apply_from_right_to_SigmaX(self, op, **options): return SigmaZKet(1) if self.n == 0 else SigmaZKet(0) def _apply_from_right_to_SigmaY(self, op, **options): return I * SigmaZKet(1) if self.n == 0 else (-I) * SigmaZKet(0) def _apply_from_right_to_SigmaMinus(self, op, **options): if self.n == 0: return SigmaZKet(1) else: return S.Zero def _apply_from_right_to_SigmaPlus(self, op, **options): if self.n == 0: return S.Zero else: return SigmaZKet(0) def _represent_default_basis(self, **options): format = options.get('format', 'sympy') if format == 'sympy': return Matrix([[1], [0]]) if self.n == 0 else Matrix([[0], [1]]) else: raise NotImplementedError('Representation in format ' + format + ' not implemented.')
SigmaZKet
python
zarr-developers__zarr-python
src/zarr/errors.py
{ "start": 2844, "end": 2979 }
class ____(FutureWarning): """ A warning intended for end users raised to indicate deprecated features. """
ZarrFutureWarning
python
numpy__numpy
numpy/_core/tests/test_umath.py
{ "start": 53567, "end": 53884 }
class ____: def test_exp2_values(self): x = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024] y = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for dt in ['f', 'd', 'g']: xf = np.array(x, dtype=dt) yf = np.array(y, dtype=dt) assert_almost_equal(np.exp2(yf), xf)
TestExp2
python
simonw__datasette
datasette/events.py
{ "start": 181, "end": 564 }
class ____(ABC): @abstractproperty def name(self): pass created: datetime = field( init=False, default_factory=lambda: datetime.now(timezone.utc) ) actor: dict | None def properties(self): properties = asdict(self) properties.pop("actor", None) properties.pop("created", None) return properties @dataclass
Event
python
jupyterlab__jupyterlab
jupyterlab/debuglog.py
{ "start": 324, "end": 2229 }
class ____(Configurable): debug_log_path = Unicode("", config=True, help="Path to use for the debug log file") @contextlib.contextmanager def debug_logging(self): log_path = self.debug_log_path if os.path.isdir(log_path): log_path = os.path.join(log_path, "jupyterlab-debug.log") if not log_path: handle, log_path = tempfile.mkstemp(prefix="jupyterlab-debug-", suffix=".log") os.close(handle) log = self.log # Transfer current log level to the handlers: for h in log.handlers: h.setLevel(self.log_level) log.setLevel("DEBUG") # Create our debug-level file handler: _debug_handler = logging.FileHandler(log_path, "w", "utf8", delay=True) _log_formatter = self._log_formatter_cls(fmt=self.log_format, datefmt=self.log_datefmt) _debug_handler.setFormatter(_log_formatter) _debug_handler.setLevel("DEBUG") log.addHandler(_debug_handler) try: yield except Exception as ex: _, _, exc_traceback = sys.exc_info() msg = traceback.format_exception(ex.__class__, ex, exc_traceback) for line in msg: self.log.debug(line) if isinstance(ex, SystemExit): warnings.warn(f"An error occurred. See the log file for details: {log_path!s}") raise warnings.warn("An error occurred.") warnings.warn(msg[-1].strip()) warnings.warn(f"See the log file for details: {log_path!s}") self.exit(1) else: log.removeHandler(_debug_handler) _debug_handler.flush() _debug_handler.close() try: os.remove(log_path) except FileNotFoundError: pass log.removeHandler(_debug_handler)
DebugLogFileMixin
python
getsentry__sentry
src/sentry/workflow_engine/models/detector.py
{ "start": 1333, "end": 1487 }
class ____(TypedDict): id: int type: str enabled: bool status: int trigger_condition: DataConditionGroupSnapshot | None
DetectorSnapshot
python
tensorflow__tensorflow
tensorflow/python/data/ops/random_op.py
{ "start": 1409, "end": 2476 }
class ____(dataset_ops.DatasetSource): """A `Dataset` of pseudorandom values.""" def __init__(self, seed=None, rerandomize_each_iteration=None, name=None): """A `Dataset` of pseudorandom values.""" self._seed, self._seed2 = random_seed.get_seed(seed) self._rerandomize = rerandomize_each_iteration self._name = name if rerandomize_each_iteration: if not tf2.enabled(): warnings.warn("In TF 1, the `rerandomize_each_iteration=True` option " "is only supported for repeat-based epochs.") variant_tensor = ged_ops.random_dataset_v2( seed=self._seed, seed2=self._seed2, seed_generator=gen_dataset_ops.dummy_seed_generator(), rerandomize_each_iteration=self._rerandomize, **self._common_args) else: variant_tensor = ged_ops.random_dataset( seed=self._seed, seed2=self._seed2, **self._common_args) super().__init__(variant_tensor) @property def element_spec(self): return tensor_spec.TensorSpec([], dtypes.int64)
_RandomDataset
python
google__jax
jax/_src/traceback_util.py
{ "start": 4991, "end": 9021 }
class ____(Exception): def __str__(self): return _simplified_tb_msg SimplifiedTraceback.__module__ = "jax.errors" def _running_under_ipython() -> bool: """Returns true if we appear to be in an IPython session.""" try: get_ipython() # type: ignore return True except NameError: return False def _ipython_supports_tracebackhide() -> bool: """Returns true if the IPython version supports __tracebackhide__.""" import IPython # pytype: disable=import-error return IPython.version_info[:2] >= (7, 17) def _filtering_mode() -> str: mode = config.traceback_filtering.value if mode is None or mode == "auto": if (_running_under_ipython() and _ipython_supports_tracebackhide()): mode = "tracebackhide" else: mode = "quiet_remove_frames" return mode def api_boundary( fun: C, *, repro_api_name: str | None = None, repro_user_func: bool = False) -> C: '''Wraps ``fun`` to form a boundary for filtering exception tracebacks. When an exception occurs below ``fun``, this appends to it a custom ``__cause__`` that carries a filtered traceback. The traceback imitates the stack trace of the original exception, but with JAX-internal frames removed. This boundary annotation works in composition with itself. The topmost frame corresponding to an :func:`~api_boundary` is the one below which stack traces are filtered. In other words, if ``api_boundary(f)`` calls ``api_boundary(g)``, directly or indirectly, the filtered stack trace provided is the same as if ``api_boundary(f)`` were to simply call ``g`` instead. This annotation is primarily useful in wrapping functions output by JAX's transformations. For example, consider ``g = jax.jit(f)``. When ``g`` is called, JAX's JIT compilation machinery is invoked, which in turn calls ``f`` in order to trace and translate it. If the function ``f`` raises an exception, the stack unwinds through JAX's JIT internals up to the original call site of ``g``. Because the function returned by :func:`~jax.jit` is annotated as an :func:`~api_boundary`, such an exception is accompanied by an additional traceback that excludes the frames specific to JAX's implementation. For the "repro" kwargs, see the comments for `repro.boundary`. ''' @functools.wraps(fun) def reraise_with_filtered_traceback(*args, **kwargs): __tracebackhide__ = True try: return fun(*args, **kwargs) except Exception as e: mode = _filtering_mode() if _is_under_reraiser(e) or mode == "off": raise if mode == "tracebackhide": _add_tracebackhide_to_hidden_frames(e.__traceback__) raise tb = e.__traceback__ try: e.with_traceback(filter_traceback(tb)) if mode == "quiet_remove_frames": e.add_note("--------------------\n" + _simplified_tb_msg) else: if mode == "remove_frames": msg = format_exception_only(e) msg = f'{msg}\n\n{_jax_message_append}' jax_error = UnfilteredStackTrace(msg) jax_error.with_traceback(_add_call_stack_frames(tb)) else: raise ValueError(f"JAX_TRACEBACK_FILTERING={mode} is not a valid value.") jax_error.__cause__ = e.__cause__ jax_error.__context__ = e.__context__ jax_error.__suppress_context__ = e.__suppress_context__ e.__cause__ = jax_error e.__context__ = None del jax_error raise finally: del mode, tb if (repro_api_name or repro_user_func) and repro: reraise_with_filtered_traceback = repro.boundary( reraise_with_filtered_traceback, api_name=repro_api_name, is_user=repro_user_func) return cast(C, reraise_with_filtered_traceback) try: # TODO: import from the final location from jax._src import repro # type: ignore repro_is_enabled = repro.is_enabled except ImportError: repro = None # type: ignore def repro_is_enabled(): return False # type: ignore
SimplifiedTraceback
python
keras-team__keras
keras/src/trainers/compile_utils_test.py
{ "start": 11380, "end": 24138 }
class ____(testing.TestCase): def test_single_output_case(self): compile_loss = CompileLoss( loss=losses_module.MeanSquaredError(), ) # Test symbolic build y_true = backend.KerasTensor((3, 4)) y_pred = backend.KerasTensor((3, 4)) compile_loss.build(y_true, y_pred) # Test eager build y_true = np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]) y_pred = np.array([[0.4, 0.1], [0.2, 0.6], [0.6, 0.1]]) compile_loss.build(y_true, y_pred) value = compile_loss(y_true, y_pred) self.assertAllClose(value, 0.068333, atol=1e-5) def test_single_output_case_with_crossentropy_loss(self): compile_loss = CompileLoss(loss="crossentropy") # Test symbolic build y_true = backend.KerasTensor((3, 4)) y_pred = backend.KerasTensor((3, 4)) compile_loss.build(y_true, y_pred) # Test eager build y_true = np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]) y_pred = np.array([[0.4, 0.1], [0.2, 0.6], [0.6, 0.1]]) compile_loss.build(y_true, y_pred) value = compile_loss(y_true, y_pred) self.assertAllClose(value, 0.706595, atol=1e-5) @parameterized.parameters(True, False) def test_list_output_case(self, broadcast): if broadcast: # Test broadcasting single loss to all outputs compile_loss = CompileLoss( loss="mse", ) else: compile_loss = CompileLoss( loss=["mse", "mse"], ) # Test symbolic build y_true = [backend.KerasTensor((3, 4)), backend.KerasTensor((3, 4))] y_pred = [backend.KerasTensor((3, 4)), backend.KerasTensor((3, 4))] compile_loss.build(y_true, y_pred) # Test eager build y_true = [ np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]), np.array([[0.7, 0.8], [0.9, 1.0], [1.1, 1.2]]), ] y_pred = [ np.array([[1.2, 1.1], [1.0, 0.9], [0.8, 0.7]]), np.array([[0.6, 0.5], [0.4, 0.3], [0.2, 0.1]]), ] compile_loss.build(y_true, y_pred) value = compile_loss(y_true, y_pred) self.assertAllClose(value, 0.953333, atol=1e-5) @parameterized.parameters(True, False) def test_dict_output_case(self, broadcast): if broadcast: # Test broadcasting single loss to all outputs compile_loss = CompileLoss( loss="mse", ) else: compile_loss = CompileLoss( loss={"a": "mse", "b": "mse"}, ) # Test symbolic build y_true = { "a": backend.KerasTensor((3, 4)), "b": backend.KerasTensor((3, 4)), } y_pred = { "a": backend.KerasTensor((3, 4)), "b": backend.KerasTensor((3, 4)), } compile_loss.build(y_true, y_pred) # Test eager build y_true = { "a": np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]), "b": np.array([[0.7, 0.8], [0.9, 1.0], [1.1, 1.2]]), } y_pred = { "a": np.array([[1.2, 1.1], [1.0, 0.9], [0.8, 0.7]]), "b": np.array([[0.6, 0.5], [0.4, 0.3], [0.2, 0.1]]), } sample_weight = { "a": np.array([1.0, 2.0, 3.0]), "b": np.array([3.0, 2.0, 1.0]), } compile_loss.build(y_true, y_pred) value = compile_loss(y_true, y_pred, sample_weight) self.assertAllClose(value, 1.266666, atol=1e-5) def test_list_loss_dict_data(self): compile_loss = CompileLoss(loss=["mse", "mae"], output_names=["b", "a"]) y_true = [backend.KerasTensor((3, 4)), backend.KerasTensor((3, 4))] y_pred = [backend.KerasTensor((3, 4)), backend.KerasTensor((3, 4))] compile_loss.build(y_true, y_pred) y_true = { "a": np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]), "b": np.array([[0.7, 0.8], [0.9, 1.0], [1.1, 1.2]]), } y_pred = { "a": np.array([[1.2, 1.1], [1.0, 0.9], [0.8, 0.7]]), "b": np.array([[0.6, 0.5], [0.4, 0.3], [0.2, 0.1]]), } value = compile_loss(y_true, y_pred) self.assertAllClose(value, 1.07666, atol=1e-5) def test_struct_loss(self): y_true = { "a": { "c": np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]), "d": np.array([[0.7, 0.8], [0.9, 1.0], [1.1, 1.2]]), }, "b": np.array([[0.7, 0.8], [0.9, 1.0], [1.1, 1.2]]), } y_pred = { "a": { "c": np.array([[1.2, 1.1], [1.0, 0.9], [0.8, 0.7]]), "d": np.array([[0.6, 0.5], [0.4, 0.3], [0.2, 0.1]]), }, "b": np.array([[0.6, 0.5], [0.4, 0.3], [0.2, 0.1]]), } loss = {"a": {"c": "mse", "d": "mae"}} compile_loss = CompileLoss(loss=loss, output_names=["c", "d", "b"]) y_true_symb = tree.map_structure( lambda _: backend.KerasTensor((3, 4)), y_true ) y_pred_symb = tree.map_structure( lambda _: backend.KerasTensor((3, 4)), y_pred ) compile_loss.build(y_true_symb, y_pred_symb) value = compile_loss(y_true, y_pred) self.assertAllClose(value, 1.07666, atol=1e-5) def test_struct_loss_valid_weights(self): y_true = { "a": np.array([1, 2]), "b": np.array([1, 2]), } y_pred = { "a": np.array([3, 4]), "b": np.array([3, 4]), } loss = {"a": "mse", "b": "mse"} compile_loss = CompileLoss( loss=loss, output_names=["a", "b"], loss_weights={ "a": np.ones((2,)), "b": np.zeros((2,)), }, ) compile_loss.build(y_true, y_pred) value = compile_loss(y_true, y_pred) self.assertAllClose(value, 4) # Metrics still report unweighted loss. a_loss_mean, b_loss_mean = compile_loss.metrics self.assertEqual(a_loss_mean.result(), 4) self.assertEqual(b_loss_mean.result(), 4) def test_struct_loss_invalid_weights(self): y_true = { "a": { "c": np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]), "d": np.array([[0.7, 0.8], [0.9, 1.0], [1.1, 1.2]]), }, "b": np.array([[0.7, 0.8], [0.9, 1.0], [1.1, 1.2]]), } y_pred = { "a": { "c": np.array([[1.2, 1.1], [1.0, 0.9], [0.8, 0.7]]), "d": np.array([[0.6, 0.5], [0.4, 0.3], [0.2, 0.1]]), }, "b": np.array([[0.6, 0.5], [0.4, 0.3], [0.2, 0.1]]), } loss = {"a": {"c": "mse", "d": "mae"}} compile_loss = CompileLoss( loss=loss, output_names=["c", "d", "b"], loss_weights=[1] ) y_true_symb = tree.map_structure( lambda _: backend.KerasTensor((3, 4)), y_true ) y_pred_symb = tree.map_structure( lambda _: backend.KerasTensor((3, 4)), y_pred ) with self.assertRaisesRegex( ValueError, "must match the number of losses" ): compile_loss.build(y_true_symb, y_pred_symb) def test_struct_loss_indice_path(self): y_true = { "a": ( np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]), np.array([[0.7, 0.8], [0.9, 1.0], [1.1, 1.2]]), ), "b": np.array([[0.7, 0.8], [0.9, 1.0], [1.1, 1.2]]), } y_pred = { "a": ( np.array([[1.2, 1.1], [1.0, 0.9], [0.8, 0.7]]), np.array([[0.6, 0.5], [0.4, 0.3], [0.2, 0.1]]), ), "b": np.array([[0.6, 0.5], [0.4, 0.3], [0.2, 0.1]]), } loss = {"a": ["mse", "mae"]} compile_loss = CompileLoss(loss=loss, output_names=["c", "d", "b"]) y_true_symb = tree.map_structure( lambda _: backend.KerasTensor((3, 4)), y_true ) y_pred_symb = tree.map_structure( lambda _: backend.KerasTensor((3, 4)), y_pred ) compile_loss.build(y_true_symb, y_pred_symb) value = compile_loss(y_true, y_pred) self.assertAllClose(value, 1.07666, atol=1e-5) def test_struct_loss_namedtuple(self): Point = namedtuple("Point", ["x", "y"]) y_true = { "a": Point( np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]), np.array([[0.7, 0.8], [0.9, 1.0], [1.1, 1.2]]), ), "b": np.array([[0.7, 0.8], [0.9, 1.0], [1.1, 1.2]]), } y_pred = { "a": Point( np.array([[1.2, 1.1], [1.0, 0.9], [0.8, 0.7]]), np.array([[0.6, 0.5], [0.4, 0.3], [0.2, 0.1]]), ), "b": np.array([[0.6, 0.5], [0.4, 0.3], [0.2, 0.1]]), } loss = {"a": Point("mse", "mae")} compile_loss = CompileLoss(loss=loss, output_names=["c", "d", "b"]) y_true_symb = tree.map_structure( lambda _: backend.KerasTensor((3, 4)), y_true ) y_pred_symb = tree.map_structure( lambda _: backend.KerasTensor((3, 4)), y_pred ) compile_loss.build(y_true_symb, y_pred_symb) value = compile_loss(y_true, y_pred) self.assertAllClose(value, 1.07666, atol=1e-5) def test_struct_loss_invalid_path(self): y_true = { "a": { "c": np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]), "d": np.array([[0.7, 0.8], [0.9, 1.0], [1.1, 1.2]]), }, "b": np.array([[0.7, 0.8], [0.9, 1.0], [1.1, 1.2]]), } y_pred = { "a": { "c": np.array([[1.2, 1.1], [1.0, 0.9], [0.8, 0.7]]), "d": np.array([[0.6, 0.5], [0.4, 0.3], [0.2, 0.1]]), }, "b": np.array([[0.6, 0.5], [0.4, 0.3], [0.2, 0.1]]), } loss = {"a": {"c": "mse"}, "b": {"d": "mae"}} compile_loss = CompileLoss(loss=loss, output_names=["c", "d", "b"]) y_true_symb = tree.map_structure( lambda _: backend.KerasTensor((3, 4)), y_true ) y_pred_symb = tree.map_structure( lambda _: backend.KerasTensor((3, 4)), y_pred ) with self.assertRaisesRegex( KeyError, "can't be found in the model's output" ): compile_loss.build(y_true_symb, y_pred_symb) def test_different_container_types(self): y1, y2, y3 = np.array([[1]]), np.array([[2]]), np.array([[3]]) y_true = ([{"a": y1}, {"b": ([y2], y3)}],) y_pred = [({"a": y1}, {"b": [(y2,), y3]})] loss = "mse" compile_loss = CompileLoss(loss=loss, output_names=["a", "b", "c"]) y_true_symb = tree.map_structure( lambda _: backend.KerasTensor((1, 1)), y_true ) y_pred_symb = tree.map_structure( lambda _: backend.KerasTensor((1, 1)), y_pred ) compile_loss.build(y_true_symb, y_pred_symb) compile_loss(y_true, y_pred) def test_structure_mismatch(self): y_true = [np.array([[1]]), np.array([[1]])] y_pred = [np.array([[1]]), np.array([[1]])] loss = ["mse", "mse"] compile_loss = CompileLoss(loss=loss, output_names=["a", "b"]) y_true_symb = tree.map_structure( lambda _: backend.KerasTensor((1, 1)), y_true ) y_pred_symb = tree.map_structure( lambda _: backend.KerasTensor((1, 1)), y_pred ) compile_loss.build(y_true_symb, y_pred_symb) with self.assertRaisesRegex( ValueError, "y_true and y_pred have different structures." ): wrong_struc_y_true = [np.array([[1]])] compile_loss(wrong_struc_y_true, y_pred) @parameterized.parameters( ["mse", None, None], [None, "mse", None], [None, None, "mse"], [None, "mse", "mse"], ["mse", None, "mse"], ) def test_y_true_partial_y_pred_span(self, *loss_conf): loss_conf = list(loss_conf) ones = np.ones((320, 3)) zeros = np.zeros((320, 3)) twos = np.ones((320, 3)) * 2 y_pred = [zeros, ones, twos] y_true = [y for y, loss in zip(y_pred, loss_conf) if loss is not None] y_true = y_true[0] if len(y_true) == 1 else y_true compile_loss = CompileLoss(loss=loss_conf, output_names=["a", "b", "c"]) # build call compile_loss(y_true, y_pred) # built call loss = compile_loss(y_true, y_pred) self.assertEqual(loss, 0.0)
TestCompileLoss
python
huggingface__transformers
tests/models/moonshine/test_modeling_moonshine.py
{ "start": 1278, "end": 4846 }
class ____: def __init__( self, parent, batch_size=3, # need batch_size != num_hidden_layers seq_length=1000, is_training=False, use_labels=False, vocab_size=147, hidden_size=8, intermediate_size=32, num_hidden_layers=2, num_attention_heads=2, num_key_value_heads=2, encoder_hidden_act="gelu", decoder_hidden_act="silu", decoder_start_token_id=85, bos_token_id=98, eos_token_id=98, pad_token_id=0, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.hidden_size = hidden_size self.use_labels = use_labels self.vocab_size = vocab_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.encoder_hidden_act = encoder_hidden_act self.decoder_hidden_act = decoder_hidden_act self.decoder_start_token_id = decoder_start_token_id self.bos_token_id = bos_token_id self.eos_token_id = eos_token_id self.pad_token_id = pad_token_id def prepare_config_and_inputs(self): input_values = floats_tensor([self.batch_size, self.seq_length], scale=1.0) attention_mask = random_attention_mask([self.batch_size, self.seq_length]) decoder_input_ids = torch.tensor(self.batch_size * [[self.decoder_start_token_id]], device=torch_device) decoder_attention_mask = decoder_input_ids.ne(self.pad_token_id) config = self.get_config() return config, input_values, attention_mask, decoder_input_ids, decoder_attention_mask def get_config(self): return MoonshineConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, intermediate_size=self.intermediate_size, encoder_num_hidden_layers=self.num_hidden_layers, decoder_num_hidden_layers=self.num_hidden_layers, encoder_num_attention_heads=self.num_attention_heads, decoder_num_attention_heads=self.num_attention_heads, encoder_num_key_value_heads=self.num_key_value_heads, decoder_num_key_value_heads=self.num_key_value_heads, encoder_hidden_act=self.encoder_hidden_act, decoder_hidden_act=self.decoder_hidden_act, decoder_start_token_id=self.decoder_start_token_id, bos_token_id=self.bos_token_id, eos_token_id=self.eos_token_id, ) def check_output_attentions(self, config, input_values, attention_mask): model = MoonshineModel(config=config) model.config.layerdrop = 1.0 model.to(torch_device) model.train() outputs = model(input_values, attention_mask=attention_mask, output_attentions=True) self.parent.assertTrue(len(outputs.attentions) > 0) def prepare_config_and_inputs_for_common(self): config, input_values, attention_mask, decoder_input_ids, decoder_attention_mask = ( self.prepare_config_and_inputs() ) inputs_dict = { "input_values": input_values, "attention_mask": attention_mask, "decoder_input_ids": decoder_input_ids, "decoder_attention_mask": decoder_attention_mask, } return config, inputs_dict @require_torch
MoonshineModelTester
python
apache__airflow
airflow-core/tests/unit/timetables/test_assets_timetable.py
{ "start": 8950, "end": 12699 }
class ____: @pytest.fixture(autouse=True) def clear_assets(self): from tests_common.test_utils.db import clear_db_assets clear_db_assets() yield clear_db_assets() @pytest.fixture def create_test_assets(self): """Fixture to create test assets and corresponding models.""" return [Asset(uri=f"test://asset{i}", name=f"hello{i}") for i in range(1, 3)] def test_asset_dag_run_queue_processing(self, session, dag_maker, create_test_assets): from airflow.assets.evaluation import AssetEvaluator assets = create_test_assets asset_models = session.query(AssetModel).all() evaluator = AssetEvaluator(session) with dag_maker(schedule=AssetAny(*assets)) as dag: EmptyOperator(task_id="hello") # Add AssetDagRunQueue entries to simulate asset event processing for am in asset_models: session.add(AssetDagRunQueue(asset_id=am.id, target_dag_id=dag.dag_id)) session.commit() # Fetch and evaluate asset triggers for all DAGs affected by asset events records = session.scalars(select(AssetDagRunQueue)).all() dag_statuses = defaultdict(lambda: defaultdict(bool)) for record in records: dag_statuses[record.target_dag_id][record.asset.uri] = True serialized_dags = session.execute( select(SerializedDagModel).where(SerializedDagModel.dag_id.in_(dag_statuses.keys())) ).fetchall() for (serialized_dag,) in serialized_dags: dag = SerializedDAG.deserialize(serialized_dag.data) for asset_uri, status in dag_statuses[dag.dag_id].items(): cond = dag.timetable.asset_condition assert evaluator.run(cond, {asset_uri: status}), "DAG trigger evaluation failed" def test_dag_with_complex_asset_condition(self, session, dag_maker): # Create Asset instances asset1 = Asset(uri="test://asset1", name="hello1") asset2 = Asset(uri="test://asset2", name="hello2") # Create and add AssetModel instances to the session am1 = AssetModel(uri=asset1.uri, name=asset1.name, group="asset") am2 = AssetModel(uri=asset2.uri, name=asset2.name, group="asset") session.add_all([am1, am2]) session.commit() # Setup a DAG with complex asset triggers (AssetAny with AssetAll) with dag_maker(schedule=AssetAny(asset1, AssetAll(asset2, asset1))) as dag: EmptyOperator(task_id="hello") assert isinstance(dag.timetable.asset_condition, AssetAny), ( "DAG's asset trigger should be an instance of AssetAny" ) assert any(isinstance(trigger, AssetAll) for trigger in dag.timetable.asset_condition.objects), ( "DAG's asset trigger should include AssetAll" ) serialized_triggers = SerializedDAG.serialize(dag.timetable.asset_condition) deserialized_triggers = SerializedDAG.deserialize(serialized_triggers) assert isinstance(deserialized_triggers, AssetAny), ( "Deserialized triggers should be an instance of AssetAny" ) assert any(isinstance(trigger, AssetAll) for trigger in deserialized_triggers.objects), ( "Deserialized triggers should include AssetAll" ) serialized_timetable_dict = SerializedDAG.to_dict(dag)["dag"]["timetable"]["__var"] assert "asset_condition" in serialized_timetable_dict, ( "Serialized timetable should contain 'asset_condition'" ) assert isinstance(serialized_timetable_dict["asset_condition"], dict), ( "Serialized 'asset_condition' should be a dict" )
TestAssetConditionWithTimetable
python
pennersr__django-allauth
allauth/headless/base/response.py
{ "start": 4934, "end": 5114 }
class ____(BaseAuthenticationResponse): def __init__(self, request): super().__init__(request, user=request.user, status=HTTPStatus.UNAUTHORIZED)
ReauthenticationResponse
python
scikit-image__scikit-image
tests/skimage/transform/test_thin_plate_splines.py
{ "start": 213, "end": 3348 }
class ____: tform_class = ThinPlateSplineTransform def test_call_before_estimation(self): tps = self.tform_class() assert tps.src is None with pytest.raises(ValueError, match="Transformation is undefined"): tps(SRC) def test_call_invalid_coords_shape(self): tps = self.tform_class.from_estimate(SRC, DST) coords = np.array([1, 2, 3]) with pytest.raises( ValueError, match=r"Input `coords` must have shape \(N, 2\)" ): tps(coords) def test_call_on_SRC(self): tps = self.tform_class.from_estimate(SRC, DST) result = tps(SRC) np.testing.assert_allclose(result, DST, atol=1e-15) def test_tps_transform_inverse(self): tps = self.tform_class.from_estimate(SRC, DST) with pytest.raises(NotImplementedError): tps.inverse() def test_tps_estimation_faulty_input(self): src = np.array([[0, 0], [0, 5], [5, 5], [5, 0]]) dst = np.array([[5, 0], [0, 0], [0, 5]]) with pytest.raises(ValueError, match="Shape of `src` and `dst` didn't match"): tps = self.tform_class.from_estimate(src, dst) less_than_3pts = np.array([[0, 0], [0, 5]]) with pytest.raises(ValueError, match="Need at least 3 points"): self.tform_class.from_estimate(less_than_3pts, dst) with pytest.raises(ValueError, match="Need at least 3 points"): self.tform_class.from_estimate(src, less_than_3pts) with pytest.raises(ValueError, match="Need at least 3 points"): self.tform_class.from_estimate(less_than_3pts, less_than_3pts) not_2d = np.array([0, 1, 2, 3]) with pytest.raises(ValueError, match=".*`src` must be a 2-dimensional array"): self.tform_class.from_estimate(not_2d, dst) with pytest.raises(ValueError, match=".*`dst` must be a 2-dimensional array"): self.tform_class.from_estimate(src, not_2d) # When the estimation fails, the instance attributes remain unchanged tps = self.tform_class() assert tps.src is None with pytest.warns(FutureWarning, match='`estimate` is deprecated'): with pytest.raises( ValueError, match=".*`dst` must be a 2-dimensional array" ): tps.estimate(src, not_2d) assert tps.src is None def test_rotate(self): image = ski.data.astronaut() desired = ski.transform.rotate(image, angle=90) src = np.array([[0, 0], [0, 511], [511, 511], [511, 0]]) dst = np.array([[511, 0], [0, 0], [0, 511], [511, 511]]) tps = self.tform_class.from_estimate(src, dst) result = ski.transform.warp(image, tps) np.testing.assert_allclose(result, desired, atol=1e-13) # Estimate method. tps2 = self.tform_class() with pytest.warns(FutureWarning, match='`estimate` is deprecated'): assert tps2.estimate(src, dst) result = ski.transform.warp(image, tps2) np.testing.assert_allclose(result, desired, atol=1e-13)
TestThinPlateSplineTransform
python
PyCQA__pylint
tests/functional/i/inherit_non_class.py
{ "start": 1454, "end": 1521 }
class ____(slice): # [inherit-non-class] pass
NotInheritableSlice
python
django__django
tests/unmanaged_models/models.py
{ "start": 1607, "end": 1852 }
class ____(models.Model): mm_a = models.ManyToManyField(A02, through="Intermediate") f_a = models.CharField(max_length=10, db_index=True) f_b = models.IntegerField() class Meta: db_table = "c01" managed = False
C02
python
getsentry__sentry
tests/sentry/api/endpoints/test_organization_relay_usage.py
{ "start": 204, "end": 3912 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-relay-usage" @cached_property def user(self): return self.create_user("test@test.com") def _public_keys(self): return [ "nDJl79SbEYH9-8NEJAI7ezrgYfolPW3Bnkg00k1zOfA", "AitWAgB-oHFywmKnUMRKMXcrsyPkESV-5gR-vsMqXgQ", "SMSesqan65THCV6M4qs4kBzPai60LzuDn-xNsvYpuP8", ] def _history_fixture(self): pks = self._public_keys() return [ { "relay_id": "r1", "public_key": pks[0], "version": "1.1.1", "first_seen": datetime(2001, 1, 1, tzinfo=timezone.utc), "last_seen": datetime(2001, 1, 2, tzinfo=timezone.utc), }, { "relay_id": "r1", "public_key": pks[0], "version": "1.1.2", "first_seen": datetime(2001, 2, 1, tzinfo=timezone.utc), "last_seen": datetime(2001, 2, 2, tzinfo=timezone.utc), }, { "relay_id": "r2", "public_key": pks[1], "version": "1.1.1", "first_seen": datetime(2002, 1, 1, tzinfo=timezone.utc), "last_seen": datetime(2002, 1, 1, tzinfo=timezone.utc), }, { "relay_id": "r3", "public_key": pks[2], "version": "1.1.1", "first_seen": datetime(2003, 1, 1, tzinfo=timezone.utc), "last_seen": datetime(2003, 1, 1, tzinfo=timezone.utc), }, ] def setUp(self) -> None: for relay_data in self._history_fixture(): RelayUsage.objects.create(**relay_data) def _set_org_public_keys(self, public_keys): self.login_as(user=self.user) url = reverse("sentry-api-0-organization-details", args=[self.organization.slug]) trusted_relays = [ {"name": f"n_{idx}", "description": f"d_{idx}", "publicKey": pk} for idx, pk in enumerate(public_keys) ] data = {"trustedRelays": trusted_relays} resp = self.client.put(url, data=data) assert resp.status_code == 200 def test_no_valid_public_keys(self) -> None: """ An organization with no valid public keys should return an empty history list """ self.login_as(user=self.user) response = self.get_success_response(self.organization.slug) assert response.data == [] def test_endpoint_checks_feature_present(self) -> None: self.login_as(user=self.user) resp = self.get_response(self.organization.slug) assert resp.status_code == 200 def test_only_records_for_known_public_keys_are_returned(self) -> None: """ Only the relay history for relays belonging to the origanization are returned. A relay "belongs" to an organization if the relay uses a public key registered to the organization. """ self.login_as(user=self.user) pks = self._public_keys() self._set_org_public_keys([pks[0], pks[1]]) response = self.get_success_response(self.organization.slug) data = response.data # test that we get the expected number of records assert len(data) == 3 r1_1 = [r for r in data if r["relayId"] == "r1" and r["version"] == "1.1.1"] r1_2 = [r for r in data if r["relayId"] == "r1" and r["version"] == "1.1.2"] r2 = [r for r in data if r["relayId"] == "r2"] assert len(r1_1) == 1 assert len(r1_2) == 1 assert len(r2) == 1
OrganizationRelayHistoryTest
python
pytest-dev__pytest
testing/python/approx.py
{ "start": 2762, "end": 38588 }
class ____: def test_error_messages_native_dtypes(self, assert_approx_raises_regex): # Treat bool exactly. assert_approx_raises_regex( {"a": 1.0, "b": True}, {"a": 1.0, "b": False}, [ "", " comparison failed. Mismatched elements: 1 / 2:", f" Max absolute difference: {SOME_FLOAT}", f" Max relative difference: {SOME_FLOAT}", r" Index\s+\| Obtained\s+\| Expected", r".*(True|False)\s+", ], ) assert_approx_raises_regex( 2.0, 1.0, [ "", " comparison failed", f" Obtained: {SOME_FLOAT}", f" Expected: {SOME_FLOAT} ± {SOME_TOLERANCE}", ], ) assert_approx_raises_regex( {"a": 1.0, "b": 1000.0, "c": 1000000.0}, { "a": 2.0, "b": 1000.0, "c": 3000000.0, }, [ r"", r" comparison failed. Mismatched elements: 2 / 3:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected\s+", rf" a \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_TOLERANCE}", rf" c \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_TOLERANCE}", ], ) assert_approx_raises_regex( {"a": 1.0, "b": None, "c": None}, { "a": None, "b": 1000.0, "c": None, }, [ r"", r" comparison failed. Mismatched elements: 2 / 3:", r" Max absolute difference: -inf", r" Max relative difference: -inf", r" Index \| Obtained\s+\| Expected\s+", rf" a \| {SOME_FLOAT} \| None", rf" b \| None\s+\| {SOME_FLOAT} ± {SOME_FLOAT}", ], ) assert_approx_raises_regex( [1.0, 2.0, 3.0, 4.0], [1.0, 3.0, 3.0, 5.0], [ r"", r" comparison failed. Mismatched elements: 2 / 4:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected ", rf" 1 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", rf" 3 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", ], ) assert_approx_raises_regex( (1, 2.2, 4), (1, 3.2, 4), [ r"", r" comparison failed. Mismatched elements: 1 / 3:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected ", rf" 1 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", ], ) # Specific test for comparison with 0.0 (relative diff will be 'inf') assert_approx_raises_regex( [0.0], [1.0], [ r"", r" comparison failed. Mismatched elements: 1 / 1:", rf" Max absolute difference: {SOME_FLOAT}", r" Max relative difference: inf", r" Index \| Obtained\s+\| Expected ", rf"\s*0\s*\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", ], ) def test_error_messages_numpy_dtypes(self, assert_approx_raises_regex): np = pytest.importorskip("numpy") a = np.linspace(0, 100, 20) b = np.linspace(0, 100, 20) a[10] += 0.5 assert_approx_raises_regex( a, b, [ r"", r" comparison failed. Mismatched elements: 1 / 20:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected", rf" \(10,\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", ], ) assert_approx_raises_regex( np.array( [ [[1.1987311, 12412342.3], [3.214143244, 1423412423415.677]], [[1, 2], [3, 219371297321973]], ] ), np.array( [ [[1.12313, 12412342.3], [3.214143244, 534523542345.677]], [[1, 2], [3, 7]], ] ), [ r"", r" comparison failed. Mismatched elements: 3 / 8:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index\s+\| Obtained\s+\| Expected\s+", rf" \(0, 0, 0\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", rf" \(0, 1, 1\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", rf" \(1, 1, 1\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", ], ) # Specific test for comparison with 0.0 (relative diff will be 'inf') assert_approx_raises_regex( np.array([0.0]), np.array([1.0]), [ r"", r" comparison failed. Mismatched elements: 1 / 1:", rf" Max absolute difference: {SOME_FLOAT}", r" Max relative difference: inf", r" Index \| Obtained\s+\| Expected ", rf"\s*\(0,\)\s*\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", ], ) def test_error_messages_invalid_args(self, assert_approx_raises_regex): np = pytest.importorskip("numpy") with pytest.raises(AssertionError) as e: assert np.array([[1.2, 3.4], [4.0, 5.0]]) == pytest.approx( np.array([[4.0], [5.0]]) ) message = "\n".join(str(e.value).split("\n")[1:]) assert message == "\n".join( [ " ", " Impossible to compare arrays with different shapes.", " Shapes: (2, 1) and (2, 2)", ] ) with pytest.raises(AssertionError) as e: assert [1.0, 2.0, 3.0] == pytest.approx([4.0, 5.0]) message = "\n".join(str(e.value).split("\n")[1:]) assert message == "\n".join( [ " ", " Impossible to compare lists with different sizes.", " Lengths: 2 and 3", ] ) def test_error_messages_with_different_verbosity(self, assert_approx_raises_regex): np = pytest.importorskip("numpy") for v in [0, 1, 2]: # Verbosity level doesn't affect the error message for scalars assert_approx_raises_regex( 2.0, 1.0, [ "", " comparison failed", f" Obtained: {SOME_FLOAT}", f" Expected: {SOME_FLOAT} ± {SOME_FLOAT}", ], verbosity_level=v, ) a = np.linspace(1, 101, 20) b = np.linspace(2, 102, 20) assert_approx_raises_regex( a, b, [ r"^ $", r"^ comparison failed. Mismatched elements: 20 / 20:$", rf"^ Max absolute difference: {SOME_FLOAT}$", rf"^ Max relative difference: {SOME_FLOAT}$", r"^ Index \| Obtained\s+\| Expected\s+$", rf"^ \(0,\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}e-{SOME_INT}$", rf"^ \(1,\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}e-{SOME_INT}\.\.\.$", "^ $", rf"^ ...Full output truncated \({SOME_INT} lines hidden\), use '-vv' to show$", ], verbosity_level=0, ) assert_approx_raises_regex( a, b, [ r" ", r" comparison failed. Mismatched elements: 20 / 20:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected", ] + [ rf" \({i},\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}" for i in range(20) ], verbosity_level=2, ) def test_repr_string(self): assert repr(approx(1.0)) == "1.0 ± 1.0e-06" assert repr(approx([1.0, 2.0])) == "approx([1.0 ± 1.0e-06, 2.0 ± 2.0e-06])" assert repr(approx((1.0, 2.0))) == "approx((1.0 ± 1.0e-06, 2.0 ± 2.0e-06))" assert repr(approx(inf)) == "inf" assert repr(approx(1.0, rel=nan)) == "1.0 ± ???" assert repr(approx(1.0, rel=inf)) == "1.0 ± inf" # Dictionaries aren't ordered, so we need to check both orders. assert repr(approx({"a": 1.0, "b": 2.0})) in ( "approx({'a': 1.0 ± 1.0e-06, 'b': 2.0 ± 2.0e-06})", "approx({'b': 2.0 ± 2.0e-06, 'a': 1.0 ± 1.0e-06})", ) assert repr(approx(42, abs=1)) == "42 ± 1" assert repr(approx(5, rel=0.01)) == "5 ± 0.05" assert repr(approx(24000, abs=500)) == "24000 ± 500" assert repr(approx(1500, abs=555)) == "1500 ± 555" def test_repr_complex_numbers(self): assert repr(approx(inf + 1j)) == "(inf+1j)" assert repr(approx(1.0j, rel=inf)) == "1j ± inf" # can't compute a sensible tolerance assert repr(approx(nan + 1j)) == "(nan+1j) ± ???" assert repr(approx(1.0j)) == "1j ± 1.0e-06 ∠ ±180°" # relative tolerance is scaled to |3+4j| = 5 assert repr(approx(3 + 4 * 1j)) == "(3+4j) ± 5.0e-06 ∠ ±180°" # absolute tolerance is not scaled assert repr(approx(3.3 + 4.4 * 1j, abs=0.02)) == "(3.3+4.4j) ± 0.02 ∠ ±180°" @pytest.mark.parametrize( "value, expected_repr_string", [ (5.0, "approx(5.0 ± 5.0e-06)"), ([5.0], "approx([5.0 ± 5.0e-06])"), ([[5.0]], "approx([[5.0 ± 5.0e-06]])"), ([[5.0, 6.0]], "approx([[5.0 ± 5.0e-06, 6.0 ± 6.0e-06]])"), ([[5.0], [6.0]], "approx([[5.0 ± 5.0e-06], [6.0 ± 6.0e-06]])"), ], ) def test_repr_nd_array(self, value, expected_repr_string): """Make sure that arrays of all different dimensions are repr'd correctly.""" np = pytest.importorskip("numpy") np_array = np.array(value) assert repr(approx(np_array)) == expected_repr_string def test_bool(self): with pytest.raises(AssertionError) as err: assert approx(1) assert err.match(r"approx\(\) is not supported in a boolean context") def test_mixed_sequence(self, assert_approx_raises_regex) -> None: """Approx should work on sequences that also contain non-numbers (#13010).""" assert_approx_raises_regex( [1.1, 2, "word"], [1.0, 2, "different"], [ "", r" comparison failed. Mismatched elements: 2 / 3:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected\s+", r"\s*0\s*\|\s*1\.1\s*\|\s*1\.0\s*±\s*1\.0e\-06\s*", r"\s*2\s*\|\s*word\s*\|\s*different\s*", ], verbosity_level=2, ) assert_approx_raises_regex( [1.1, 2, "word"], [1.0, 2, "word"], [ "", r" comparison failed. Mismatched elements: 1 / 3:", rf" Max absolute difference: {SOME_FLOAT}", rf" Max relative difference: {SOME_FLOAT}", r" Index \| Obtained\s+\| Expected\s+", r"\s*0\s*\|\s*1\.1\s*\|\s*1\.0\s*±\s*1\.0e\-06\s*", ], verbosity_level=2, ) assert [1.1, 2, "word"] == pytest.approx([1.1, 2, "word"]) def test_operator_overloading(self): assert 1 == approx(1, rel=1e-6, abs=1e-12) assert not (1 != approx(1, rel=1e-6, abs=1e-12)) assert 10 != approx(1, rel=1e-6, abs=1e-12) assert not (10 == approx(1, rel=1e-6, abs=1e-12)) def test_exactly_equal(self): examples = [ (2.0, 2.0), (0.1e200, 0.1e200), (1.123e-300, 1.123e-300), (12345, 12345.0), (0.0, -0.0), (345678, 345678), (Decimal("1.0001"), Decimal("1.0001")), (Fraction(1, 3), Fraction(-1, -3)), ] for a, x in examples: assert a == approx(x) def test_opposite_sign(self): examples = [(eq, 1e-100, -1e-100), (ne, 1e100, -1e100)] for op, a, x in examples: assert op(a, approx(x)) def test_zero_tolerance(self): within_1e10 = [(1.1e-100, 1e-100), (-1.1e-100, -1e-100)] for a, x in within_1e10: assert x == approx(x, rel=0.0, abs=0.0) assert a != approx(x, rel=0.0, abs=0.0) assert a == approx(x, rel=0.0, abs=5e-101) assert a != approx(x, rel=0.0, abs=5e-102) assert a == approx(x, rel=5e-1, abs=0.0) assert a != approx(x, rel=5e-2, abs=0.0) @pytest.mark.parametrize( ("rel", "abs"), [ (-1e100, None), (None, -1e100), (1e100, -1e100), (-1e100, 1e100), (-1e100, -1e100), ], ) def test_negative_tolerance(self, rel: float | None, abs: float | None) -> None: # Negative tolerances are not allowed. with pytest.raises(ValueError): 1.1 == approx(1, rel, abs) def test_negative_tolerance_message(self): # Error message for negative tolerance should include the value. with pytest.raises(ValueError, match="-3"): 0 == approx(1, abs=-3) with pytest.raises(ValueError, match="-3"): 0 == approx(1, rel=-3) def test_inf_tolerance(self): # Everything should be equal if the tolerance is infinite. large_diffs = [(1, 1000), (1e-50, 1e50), (-1.0, -1e300), (0.0, 10)] for a, x in large_diffs: assert a != approx(x, rel=0.0, abs=0.0) assert a == approx(x, rel=inf, abs=0.0) assert a == approx(x, rel=0.0, abs=inf) assert a == approx(x, rel=inf, abs=inf) def test_inf_tolerance_expecting_zero(self) -> None: # If the relative tolerance is zero but the expected value is infinite, # the actual tolerance is a NaN, which should be an error. with pytest.raises(ValueError): 1 == approx(0, rel=inf, abs=0.0) with pytest.raises(ValueError): 1 == approx(0, rel=inf, abs=inf) def test_nan_tolerance(self) -> None: with pytest.raises(ValueError): 1.1 == approx(1, rel=nan) with pytest.raises(ValueError): 1.1 == approx(1, abs=nan) with pytest.raises(ValueError): 1.1 == approx(1, rel=nan, abs=nan) def test_reasonable_defaults(self): # Whatever the defaults are, they should work for numbers close to 1 # than have a small amount of floating-point error. assert 0.1 + 0.2 == approx(0.3) def test_default_tolerances(self): # This tests the defaults as they are currently set. If you change the # defaults, this test will fail but you should feel free to change it. # None of the other tests (except the doctests) should be affected by # the choice of defaults. examples = [ # Relative tolerance used. (eq, 1e100 + 1e94, 1e100), (ne, 1e100 + 2e94, 1e100), (eq, 1e0 + 1e-6, 1e0), (ne, 1e0 + 2e-6, 1e0), # Absolute tolerance used. (eq, 1e-100, +1e-106), (eq, 1e-100, +2e-106), (eq, 1e-100, 0), ] for op, a, x in examples: assert op(a, approx(x)) def test_custom_tolerances(self): assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e0) assert 1e8 + 1e0 == approx(1e8, rel=5e-9, abs=5e0) assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e-1) assert 1e8 + 1e0 != approx(1e8, rel=5e-9, abs=5e-1) assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-8) assert 1e0 + 1e-8 == approx(1e0, rel=5e-9, abs=5e-8) assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-9) assert 1e0 + 1e-8 != approx(1e0, rel=5e-9, abs=5e-9) assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-16) assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-9, abs=5e-16) assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-17) assert 1e-8 + 1e-16 != approx(1e-8, rel=5e-9, abs=5e-17) def test_relative_tolerance(self): within_1e8_rel = [(1e8 + 1e0, 1e8), (1e0 + 1e-8, 1e0), (1e-8 + 1e-16, 1e-8)] for a, x in within_1e8_rel: assert a == approx(x, rel=5e-8, abs=0.0) assert a != approx(x, rel=5e-9, abs=0.0) def test_absolute_tolerance(self): within_1e8_abs = [(1e8 + 9e-9, 1e8), (1e0 + 9e-9, 1e0), (1e-8 + 9e-9, 1e-8)] for a, x in within_1e8_abs: assert a == approx(x, rel=0, abs=5e-8) assert a != approx(x, rel=0, abs=5e-9) def test_expecting_zero(self): examples = [ (ne, 1e-6, 0.0), (ne, -1e-6, 0.0), (eq, 1e-12, 0.0), (eq, -1e-12, 0.0), (ne, 2e-12, 0.0), (ne, -2e-12, 0.0), (ne, inf, 0.0), (ne, nan, 0.0), ] for op, a, x in examples: assert op(a, approx(x, rel=0.0, abs=1e-12)) assert op(a, approx(x, rel=1e-6, abs=1e-12)) def test_expecting_inf(self): examples = [ (eq, inf, inf), (eq, -inf, -inf), (ne, inf, -inf), (ne, 0.0, inf), (ne, nan, inf), ] for op, a, x in examples: assert op(a, approx(x)) def test_expecting_nan(self): examples = [ (eq, nan, nan), (eq, -nan, -nan), (eq, nan, -nan), (ne, 0.0, nan), (ne, inf, nan), ] for op, a, x in examples: # Nothing is equal to NaN by default. assert a != approx(x) # If ``nan_ok=True``, then NaN is equal to NaN. assert op(a, approx(x, nan_ok=True)) def test_int(self): within_1e6 = [(1000001, 1000000), (-1000001, -1000000)] for a, x in within_1e6: assert a == approx(x, rel=5e-6, abs=0) assert a != approx(x, rel=5e-7, abs=0) assert approx(x, rel=5e-6, abs=0) == a assert approx(x, rel=5e-7, abs=0) != a def test_decimal(self): within_1e6 = [ (Decimal("1.000001"), Decimal("1.0")), (Decimal("-1.000001"), Decimal("-1.0")), ] for a, x in within_1e6: assert a == approx(x) assert a == approx(x, rel=Decimal("5e-6"), abs=0) assert a != approx(x, rel=Decimal("5e-7"), abs=0) assert approx(x, rel=Decimal("5e-6"), abs=0) == a assert approx(x, rel=Decimal("5e-7"), abs=0) != a def test_fraction(self): within_1e6 = [ (1 + Fraction(1, 1000000), Fraction(1)), (-1 - Fraction(-1, 1000000), Fraction(-1)), ] for a, x in within_1e6: assert a == approx(x, rel=5e-6, abs=0) assert a != approx(x, rel=5e-7, abs=0) assert approx(x, rel=5e-6, abs=0) == a assert approx(x, rel=5e-7, abs=0) != a def test_complex(self): within_1e6 = [ (1.000001 + 1.0j, 1.0 + 1.0j), (1.0 + 1.000001j, 1.0 + 1.0j), (-1.000001 + 1.0j, -1.0 + 1.0j), (1.0 - 1.000001j, 1.0 - 1.0j), ] for a, x in within_1e6: assert a == approx(x, rel=5e-6, abs=0) assert a != approx(x, rel=5e-7, abs=0) assert approx(x, rel=5e-6, abs=0) == a assert approx(x, rel=5e-7, abs=0) != a def test_expecting_bool(self) -> None: assert True == approx(True) # noqa: E712 assert False == approx(False) # noqa: E712 assert True != approx(False) # noqa: E712 assert True != approx(False, abs=2) # noqa: E712 assert 1 != approx(True) def test_expecting_bool_numpy(self) -> None: """Check approx comparing with numpy.bool (#13047).""" np = pytest.importorskip("numpy") assert np.False_ != approx(True) assert np.True_ != approx(False) assert np.True_ == approx(True) assert np.False_ == approx(False) assert np.True_ != approx(False, abs=2) def test_list(self): actual = [1 + 1e-7, 2 + 1e-8] expected = [1, 2] # Return false if any element is outside the tolerance. assert actual == approx(expected, rel=5e-7, abs=0) assert actual != approx(expected, rel=5e-8, abs=0) assert approx(expected, rel=5e-7, abs=0) == actual assert approx(expected, rel=5e-8, abs=0) != actual def test_list_decimal(self): actual = [Decimal("1.000001"), Decimal("2.000001")] expected = [Decimal("1"), Decimal("2")] assert actual == approx(expected) def test_list_wrong_len(self): assert [1, 2] != approx([1]) assert [1, 2] != approx([1, 2, 3]) def test_tuple(self): actual = (1 + 1e-7, 2 + 1e-8) expected = (1, 2) # Return false if any element is outside the tolerance. assert actual == approx(expected, rel=5e-7, abs=0) assert actual != approx(expected, rel=5e-8, abs=0) assert approx(expected, rel=5e-7, abs=0) == actual assert approx(expected, rel=5e-8, abs=0) != actual def test_tuple_wrong_len(self): assert (1, 2) != approx((1,)) assert (1, 2) != approx((1, 2, 3)) def test_tuple_vs_other(self): assert 1 != approx((1,)) def test_dict(self): actual = {"a": 1 + 1e-7, "b": 2 + 1e-8} # Dictionaries became ordered in python3.6, so switch up the order here # to make sure it doesn't matter. expected = {"b": 2, "a": 1} # Return false if any element is outside the tolerance. assert actual == approx(expected, rel=5e-7, abs=0) assert actual != approx(expected, rel=5e-8, abs=0) assert approx(expected, rel=5e-7, abs=0) == actual assert approx(expected, rel=5e-8, abs=0) != actual def test_dict_decimal(self): actual = {"a": Decimal("1.000001"), "b": Decimal("2.000001")} # Dictionaries became ordered in python3.6, so switch up the order here # to make sure it doesn't matter. expected = {"b": Decimal("2"), "a": Decimal("1")} assert actual == approx(expected) def test_dict_wrong_len(self): assert {"a": 1, "b": 2} != approx({"a": 1}) assert {"a": 1, "b": 2} != approx({"a": 1, "c": 2}) assert {"a": 1, "b": 2} != approx({"a": 1, "b": 2, "c": 3}) def test_dict_nonnumeric(self): assert {"a": 1.0, "b": None} == pytest.approx({"a": 1.0, "b": None}) assert {"a": 1.0, "b": 1} != pytest.approx({"a": 1.0, "b": None}) assert {"a": 1.0, "b": True} != pytest.approx({"a": 1.0, "b": False}, abs=2) def test_dict_vs_other(self): assert 1 != approx({"a": 0}) def test_dict_for_div_by_zero(self, assert_approx_raises_regex): assert_approx_raises_regex( {"foo": 42.0}, {"foo": 0.0}, [ r"", r" comparison failed. Mismatched elements: 1 / 1:", rf" Max absolute difference: {SOME_FLOAT}", r" Max relative difference: inf", r" Index \| Obtained\s+\| Expected ", rf" foo | {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}", ], ) def test_dict_differing_lengths(self, assert_approx_raises_regex): assert_approx_raises_regex( {"a": 0}, {"a": 0, "b": 1}, [ " ", r" Impossible to compare mappings with different sizes\.", r" Lengths: 2 and 1", ], ) def test_numpy_array(self): np = pytest.importorskip("numpy") actual = np.array([1 + 1e-7, 2 + 1e-8]) expected = np.array([1, 2]) # Return false if any element is outside the tolerance. assert actual == approx(expected, rel=5e-7, abs=0) assert actual != approx(expected, rel=5e-8, abs=0) assert approx(expected, rel=5e-7, abs=0) == expected assert approx(expected, rel=5e-8, abs=0) != actual # Should be able to compare lists with numpy arrays. assert list(actual) == approx(expected, rel=5e-7, abs=0) assert list(actual) != approx(expected, rel=5e-8, abs=0) assert actual == approx(list(expected), rel=5e-7, abs=0) assert actual != approx(list(expected), rel=5e-8, abs=0) def test_numpy_tolerance_args(self): """ Check that numpy rel/abs args are handled correctly for comparison against an np.array Check both sides of the operator, hopefully it doesn't impact things. Test all permutations of where the approx and np.array() can show up """ np = pytest.importorskip("numpy") expected = 100.0 actual = 99.0 abs_diff = expected - actual rel_diff = (expected - actual) / expected tests = [ (eq, abs_diff, 0), (eq, 0, rel_diff), (ne, 0, rel_diff / 2.0), # rel diff fail (ne, abs_diff / 2.0, 0), # abs diff fail ] for op, _abs, _rel in tests: assert op(np.array(actual), approx(expected, abs=_abs, rel=_rel)) # a, b assert op(approx(expected, abs=_abs, rel=_rel), np.array(actual)) # b, a assert op(actual, approx(np.array(expected), abs=_abs, rel=_rel)) # a, b assert op(approx(np.array(expected), abs=_abs, rel=_rel), actual) # b, a assert op(np.array(actual), approx(np.array(expected), abs=_abs, rel=_rel)) assert op(approx(np.array(expected), abs=_abs, rel=_rel), np.array(actual)) def test_numpy_expecting_nan(self): np = pytest.importorskip("numpy") examples = [ (eq, nan, nan), (eq, -nan, -nan), (eq, nan, -nan), (ne, 0.0, nan), (ne, inf, nan), ] for op, a, x in examples: # Nothing is equal to NaN by default. assert np.array(a) != approx(x) assert a != approx(np.array(x)) # If ``nan_ok=True``, then NaN is equal to NaN. assert op(np.array(a), approx(x, nan_ok=True)) assert op(a, approx(np.array(x), nan_ok=True)) def test_numpy_expecting_inf(self): np = pytest.importorskip("numpy") examples = [ (eq, inf, inf), (eq, -inf, -inf), (ne, inf, -inf), (ne, 0.0, inf), (ne, nan, inf), ] for op, a, x in examples: assert op(np.array(a), approx(x)) assert op(a, approx(np.array(x))) assert op(np.array(a), approx(np.array(x))) def test_numpy_array_wrong_shape(self): np = pytest.importorskip("numpy") a12 = np.array([[1, 2]]) a21 = np.array([[1], [2]]) assert a12 != approx(a21) assert a21 != approx(a12) def test_numpy_array_implicit_conversion(self): np = pytest.importorskip("numpy") class ImplicitArray: """Type which is implicitly convertible to a numpy array.""" def __init__(self, vals): self.vals = vals def __array__(self, dtype=None, copy=None): return np.array(self.vals) vec1 = ImplicitArray([1.0, 2.0, 3.0]) vec2 = ImplicitArray([1.0, 2.0, 4.0]) # see issue #12114 for test case assert vec1 != approx(vec2) def test_numpy_array_protocol(self): """ array-like objects such as tensorflow's DeviceArray are handled like ndarray. See issue #8132 """ np = pytest.importorskip("numpy") class DeviceArray: def __init__(self, value, size): self.value = value self.size = size def __array__(self): return self.value * np.ones(self.size) class DeviceScalar: def __init__(self, value): self.value = value def __array__(self): return np.array(self.value) expected = 1 actual = 1 + 1e-6 assert approx(expected) == DeviceArray(actual, size=1) assert approx(expected) == DeviceArray(actual, size=2) assert approx(expected) == DeviceScalar(actual) assert approx(DeviceScalar(expected)) == actual assert approx(DeviceScalar(expected)) == DeviceScalar(actual) def test_doctests(self, mocked_doctest_runner) -> None: import doctest parser = doctest.DocTestParser() assert approx.__doc__ is not None test = parser.get_doctest( approx.__doc__, {"approx": approx}, approx.__name__, None, None ) mocked_doctest_runner.run(test) def test_unicode_plus_minus(self, pytester: Pytester) -> None: """ Comparing approx instances inside lists should not produce an error in the detailed diff. Integration test for issue #2111. """ pytester.makepyfile( """ import pytest def test_foo(): assert [3] == [pytest.approx(4)] """ ) expected = "4.0e-06" result = pytester.runpytest() result.stdout.fnmatch_lines( [f"*At index 0 diff: 3 != 4 ± {expected}", "=* 1 failed in *="] ) @pytest.mark.parametrize( "x, name", [ pytest.param([[1]], "data structures", id="nested-list"), pytest.param({"key": {"key": 1}}, "dictionaries", id="nested-dict"), ], ) def test_expected_value_type_error(self, x, name): with pytest.raises( TypeError, match=rf"pytest.approx\(\) does not support nested {name}:", ): approx(x) @pytest.mark.parametrize( "x", [ pytest.param(None), pytest.param("string"), pytest.param(["string"], id="nested-str"), pytest.param({"key": "string"}, id="dict-with-string"), ], ) def test_nonnumeric_okay_if_equal(self, x): assert x == approx(x) @pytest.mark.parametrize( "x", [ pytest.param("string"), pytest.param(["string"], id="nested-str"), pytest.param({"key": "string"}, id="dict-with-string"), ], ) def test_nonnumeric_false_if_unequal(self, x): """For non-numeric types, x != pytest.approx(y) reduces to x != y""" assert "ab" != approx("abc") assert ["ab"] != approx(["abc"]) # in particular, both of these should return False assert {"a": 1.0} != approx({"a": None}) assert {"a": None} != approx({"a": 1.0}) assert 1.0 != approx(None) assert None != approx(1.0) # noqa: E711 assert 1.0 != approx([None]) assert None != approx([1.0]) # noqa: E711 def test_nonnumeric_dict_repr(self): """Dicts with non-numerics and infinites have no tolerances""" x1 = {"foo": 1.0000005, "bar": None, "foobar": inf} assert ( repr(approx(x1)) == "approx({'foo': 1.0000005 ± 1.0e-06, 'bar': None, 'foobar': inf})" ) def test_nonnumeric_list_repr(self): """Lists with non-numerics and infinites have no tolerances""" x1 = [1.0000005, None, inf] assert repr(approx(x1)) == "approx([1.0000005 ± 1.0e-06, None, inf])" @pytest.mark.parametrize( "op", [ pytest.param(operator.le, id="<="), pytest.param(operator.lt, id="<"), pytest.param(operator.ge, id=">="), pytest.param(operator.gt, id=">"), ], ) def test_comparison_operator_type_error(self, op): """pytest.approx should raise TypeError for operators other than == and != (#2003).""" with pytest.raises(TypeError): op(1, approx(1, rel=1e-6, abs=1e-12)) def test_numpy_array_with_scalar(self): np = pytest.importorskip("numpy") actual = np.array([1 + 1e-7, 1 - 1e-8]) expected = 1.0 assert actual == approx(expected, rel=5e-7, abs=0) assert actual != approx(expected, rel=5e-8, abs=0) assert approx(expected, rel=5e-7, abs=0) == actual assert approx(expected, rel=5e-8, abs=0) != actual def test_numpy_scalar_with_array(self): np = pytest.importorskip("numpy") actual = 1.0 expected = np.array([1 + 1e-7, 1 - 1e-8]) assert actual == approx(expected, rel=5e-7, abs=0) assert actual != approx(expected, rel=5e-8, abs=0) assert approx(expected, rel=5e-7, abs=0) == actual assert approx(expected, rel=5e-8, abs=0) != actual def test_generic_ordered_sequence(self): class MySequence: def __getitem__(self, i): return [1, 2, 3, 4][i] def __len__(self): return 4 expected = MySequence() assert [1, 2, 3, 4] == approx(expected, abs=1e-4) expected_repr = "approx([1 ± 1.0e-06, 2 ± 2.0e-06, 3 ± 3.0e-06, 4 ± 4.0e-06])" assert repr(approx(expected)) == expected_repr def test_decimal_approx_repr(self, monkeypatch) -> None: monkeypatch.setitem(decimal.getcontext().traps, decimal.FloatOperation, True) approx_obj = pytest.approx(decimal.Decimal("2.60")) assert decimal.Decimal("2.600001") == approx_obj def test_allow_ordered_sequences_only(self) -> None: """pytest.approx() should raise an error on unordered sequences (#9692).""" with pytest.raises(TypeError, match="only supports ordered sequences"): assert {1, 2, 3} == approx({1, 2, 3}) def test_strange_sequence(self): """https://github.com/pytest-dev/pytest/issues/11797""" a = MyVec3(1, 2, 3) b = MyVec3(0, 1, 2) # this would trigger the error inside the test pytest.approx(a, abs=0.5)._repr_compare(b) assert b == pytest.approx(a, abs=2) assert b != pytest.approx(a, abs=0.5) def test_approx_dicts_with_mismatch_on_keys(self) -> None: """https://github.com/pytest-dev/pytest/issues/13816""" expected = {"a": 1, "b": 3} actual = {"a": 1, "c": 3} with pytest.raises( AssertionError, match=re.escape( "comparison failed.\n Mappings has different keys: " "expected dict_keys(['a', 'b']) but got dict_keys(['a', 'c'])" ), ): assert actual == approx(expected)
TestApprox
python
keras-team__keras
keras/src/dtype_policies/dtype_policy_test.py
{ "start": 25083, "end": 25964 }
class ____(test_case.TestCase): def test_empty_name(self): """Test initialization with an empty name.""" with self.assertRaisesRegex(ValueError, "Cannot convert"): DTypePolicy("") def test_special_character_name(self): """Test initialization with special characters in the name.""" with self.assertRaisesRegex(ValueError, "Cannot convert"): DTypePolicy("@mixed_float16!") def test_very_long_name(self): """Test initialization with a very long name.""" with self.assertRaisesRegex(ValueError, "Cannot convert"): DTypePolicy("mixed_float16" * 100) def test_almost_valid_name(self): """Test initialization with a name close to a valid one.""" with self.assertRaisesRegex(ValueError, "Cannot convert"): DTypePolicy("mixed_float15")
DTypePolicyEdgeCasesTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclass16.py
{ "start": 270, "end": 385 }
class ____(B): color: str reveal_type(A.__init__, expected_text="(self: A, *args: Any, **kwargs: Any) -> None")
A
python
getsentry__sentry
src/sentry/api/endpoints/project_templates_index.py
{ "start": 1298, "end": 3545 }
class ____(OrganizationEndpoint): owner = ApiOwner.ALERTS_NOTIFICATIONS publish_status = { "GET": ApiPublishStatus.PRIVATE, "POST": ApiPublishStatus.PRIVATE, } permission_classes = (OrganizationPermission,) @ensure_rollout_enabled(PROJECT_TEMPLATE_FEATURE_FLAG) def get(self, request: Request, organization: Organization) -> Response: """ List of Project Templates, does not include the options for the project template. Return a list of project templates available to the authenticated user. """ queryset = ProjectTemplate.objects.filter(organization=organization) return self.paginate( request=request, queryset=queryset, order_by="date_added", on_results=lambda x: serialize(x, request.user, ProjectTemplateSerializer()), paginator_cls=OffsetPaginator, ) @ensure_rollout_enabled(PROJECT_TEMPLATE_FEATURE_FLAG) def post(self, request: Request, organization: Organization) -> Response: """ Create a new Project Template for the organization. The Request body should be a JSON object with the following keys: - name: string - options: {key: 'value'} - optional - creates a ProjectTemplateOption for each key-value pair """ serializer = ProjectTemplateWriteSerializer(data=request.data) if not serializer.is_valid(): return Response(status=400, data=serializer.errors) data = serializer.validated_data project_template = ProjectTemplate.objects.create( name=data.get("name"), organization=organization, ) options = data.get("options", {}) for key, value in options.items(): project_template.options.create(key=key, value=value) self.create_audit_entry( request=request, organization=organization, target_object=project_template.id, event=audit_log.get_event_id(AUDIT_LOG_EVENT_ID), data=project_template.get_audit_log_data(), ) return Response(serialize(project_template, request.user), status=201)
OrganizationProjectTemplatesIndexEndpoint
python
jazzband__django-redis
django_redis/exceptions.py
{ "start": 0, "end": 300 }
class ____(Exception): def __init__(self, connection, parent=None): self.connection = connection def __str__(self) -> str: error_type = type(self.__cause__).__name__ error_msg = str(self.__cause__) return f"Redis {error_type}: {error_msg}"
ConnectionInterrupted
python
huggingface__transformers
src/transformers/models/mask2former/modeling_mask2former.py
{ "start": 1887, "end": 3230 }
class ____(ModelOutput): r""" multi_scale_features (`tuple(torch.FloatTensor)`): Tuple of multi-scale features of scales [1/8, 1/16, 1/32] and shape `(batch_size, num_channels, height, width)`from the Multi-Scale Deformable Attenntion based Pixel Decoder. mask_features (`torch.FloatTensor`): Tensor of shape `(batch_size, num_channels, height, width)`, 1/4 scale features from the last Pixel Decoder Layer. attentions (`tuple(torch.FloatTensor)`, *optional*): Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`. Attentions weights from pixel decoder. Returned when `output_attentions=True` is passed or when `config.output_attentions=True` """ multi_scale_features: Optional[tuple[torch.FloatTensor]] = None mask_features: Optional[torch.FloatTensor] = None attentions: Optional[tuple[torch.FloatTensor]] = None @dataclass @auto_docstring( custom_intro=""" Base class for outputs of the Transformer decoder. This class adds two attributes to BaseModelOutputWithCrossAttentions for mask predictions logits and a tuple of intermediate decoder activations, i.e. the output of each decoder layer, each of them gone through a layernorm. """ )
Mask2FormerPixelDecoderOutput
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/triggers/vertex_ai.py
{ "start": 6064, "end": 6904 }
class ____(BaseVertexAIJobTrigger): """Make async calls to Vertex AI to check the state of a Pipeline Job.""" job_type_verbose_name = "Pipeline Job" job_serializer_class = types.PipelineJob statuses_success = { PipelineState.PIPELINE_STATE_PAUSED, PipelineState.PIPELINE_STATE_SUCCEEDED, } @cached_property def async_hook(self) -> PipelineJobAsyncHook: return PipelineJobAsyncHook(gcp_conn_id=self.conn_id, impersonation_chain=self.impersonation_chain) async def _wait_job(self) -> types.PipelineJob: job: types.PipelineJob = await self.async_hook.wait_for_pipeline_job( project_id=self.project_id, location=self.location, job_id=self.job_id, poll_interval=self.poll_interval, ) return job
RunPipelineJobTrigger
python
pandas-dev__pandas
pandas/tests/indexes/ranges/test_indexing.py
{ "start": 115, "end": 2122 }
class ____: def test_get_indexer(self): index = RangeIndex(start=0, stop=20, step=2) target = RangeIndex(10) indexer = index.get_indexer(target) expected = np.array([0, -1, 1, -1, 2, -1, 3, -1, 4, -1], dtype=np.intp) tm.assert_numpy_array_equal(indexer, expected) def test_get_indexer_pad(self): index = RangeIndex(start=0, stop=20, step=2) target = RangeIndex(10) indexer = index.get_indexer(target, method="pad") expected = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4], dtype=np.intp) tm.assert_numpy_array_equal(indexer, expected) def test_get_indexer_backfill(self): index = RangeIndex(start=0, stop=20, step=2) target = RangeIndex(10) indexer = index.get_indexer(target, method="backfill") expected = np.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5], dtype=np.intp) tm.assert_numpy_array_equal(indexer, expected) def test_get_indexer_limit(self): # GH#28631 idx = RangeIndex(4) target = RangeIndex(6) result = idx.get_indexer(target, method="pad", limit=1) expected = np.array([0, 1, 2, 3, 3, -1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) @pytest.mark.parametrize("stop", [0, -1, -2]) def test_get_indexer_decreasing(self, stop): # GH#28678 index = RangeIndex(7, stop, -3) result = index.get_indexer(range(9)) expected = np.array([-1, 2, -1, -1, 1, -1, -1, 0, -1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) def test_get_indexer_missing_value_casting_string_dtype(self): # GH#55833 idx = Index(["a", "b", None]) result = idx.get_indexer([None]) expected = np.array([2], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) result = idx.get_indexer([None, True]) expected = np.array([2, -1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected)
TestGetIndexer
python
PyCQA__pylint
tests/functional/r/regression/regression_2913.py
{ "start": 103, "end": 184 }
class ____: """My base class.""" # pylint: enable=too-few-public-methods
Base
python
indygreg__python-build-standalone
pythonbuild/utils.py
{ "start": 7741, "end": 21501 }
class ____(Exception): """Represents an integrity error when downloading a URL.""" def __init__(self, *args, length: int): self.length = length super().__init__(*args) def secure_download_stream(url, size, sha256): """Securely download a URL to a stream of chunks. If the integrity of the download fails, an IntegrityError is raised. """ h = hashlib.sha256() length = 0 with urllib.request.urlopen(url) as fh: if not url.endswith(".gz") and fh.info().get("Content-Encoding") == "gzip": fh = gzip.GzipFile(fileobj=fh) while True: chunk = fh.read(65536) if not chunk: break h.update(chunk) length += len(chunk) yield chunk digest = h.hexdigest() if length != size or digest != sha256: raise IntegrityError( "integrity mismatch on %s: wanted size=%d, sha256=%s; got size=%d, sha256=%s" % (url, size, sha256, length, digest), length=length, ) def download_to_path(url: str, path: pathlib.Path, size: int, sha256: str): """Download a URL to a filesystem path, possibly with verification.""" # We download to a temporary file and rename at the end so there's # no chance of the final file being partially written or containing # bad data. print("downloading %s to %s" % (url, path)) if path.exists(): good = True if path.stat().st_size != size: print("existing file size is wrong; removing") good = False if good: if hash_path(path) != sha256: print("existing file hash is wrong; removing") good = False if good: print("%s exists and passes integrity checks" % path) return path.unlink() # Need to write to random path to avoid race conditions. If there is a # race, worst case we'll download the same file N>1 times. Meh. tmp = path.with_name( "%s.tmp%s" % ( path.name, "".join(random.choices(string.ascii_uppercase + string.digits, k=8)), ) ) for attempt in range(8): try: try: with tmp.open("wb") as fh: for chunk in secure_download_stream(url, size, sha256): fh.write(chunk) break except IntegrityError as e: tmp.unlink() # If we didn't get most of the expected file, retry if e.length > size * 0.75: raise print(f"Integrity error on {url}; retrying: {e}") time.sleep(2**attempt) except http.client.HTTPException as e: print(f"HTTP exception on {url}; retrying: {e}") time.sleep(2**attempt) except urllib.error.URLError as e: print(f"urllib error on {url}; retrying: {e}") time.sleep(2**attempt) else: raise Exception("download failed after multiple retries: %s" % url) tmp.rename(path) print("successfully downloaded %s" % url) def download_entry(key: str, dest_path: pathlib.Path, local_name=None) -> pathlib.Path: entry = DOWNLOADS[key] url = entry["url"] size = entry["size"] sha256 = entry["sha256"] assert isinstance(url, str) assert isinstance(size, int) assert isinstance(sha256, str) local_path = dest_path / (local_name or url[url.rindex("/") + 1 :]) download_to_path(url, local_path, size, sha256) return local_path def create_tar_from_directory(fh, base_path: pathlib.Path, path_prefix=None): with tarfile.open(name="", mode="w", fileobj=fh) as tf: for root, dirs, files in os.walk(base_path): dirs.sort() for f in sorted(files): full = base_path / root / f rel = full.relative_to(base_path) if path_prefix: rel = pathlib.Path(path_prefix) / rel tf.add(full, rel) def extract_tar_to_directory(source: pathlib.Path, dest: pathlib.Path): with tarfile.open(source, "r") as tf: tf.extractall(dest) def extract_zip_to_directory(source: pathlib.Path, dest: pathlib.Path): with zipfile.ZipFile(source, "r") as zf: zf.extractall(dest) # 2024-01-01T00:00:00Z DEFAULT_MTIME = 1704067200 def normalize_tar_archive(data: io.BytesIO) -> io.BytesIO: """Normalize the contents of a tar archive. We want tar archives to be as deterministic as possible. This function will take tar archive data in a buffer and return a new buffer containing a more deterministic tar archive. """ members = [] with tarfile.open(fileobj=data) as tf: for ti in tf: # We don't care about directory entries. Tools can handle this fine. if ti.isdir(): continue filedata = tf.extractfile(ti) if filedata is not None: filedata = io.BytesIO(filedata.read()) members.append((ti, filedata)) # Sort the archive members. We put PYTHON.json first so metadata can # be read without reading the entire archive. def sort_key(v): if v[0].name == "python/PYTHON.json": return 0, v[0].name else: return 1, v[0].name members.sort(key=sort_key) # Normalize attributes on archive members. for entry in members: ti = entry[0] # The pax headers attribute takes priority over the other named # attributes. To minimize potential for our assigns to no-op, we # clear out the pax headers. We can't reset all the pax headers, # as this would nullify symlinks. for a in ("mtime", "uid", "uname", "gid", "gname"): try: ti.pax_headers.__delattr__(a) except AttributeError: pass ti.pax_headers = {} ti.mtime = DEFAULT_MTIME ti.uid = 0 ti.uname = "root" ti.gid = 0 ti.gname = "root" # Give user/group read/write on all entries. ti.mode |= stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP # If user executable, give to group as well. if ti.mode & stat.S_IXUSR: ti.mode |= stat.S_IXGRP dest = io.BytesIO() with tarfile.open(fileobj=dest, mode="w") as tf: for ti, filedata in members: tf.addfile(ti, filedata) dest.seek(0) return dest def clang_toolchain(host_platform: str, target_triple: str) -> str: if host_platform == "linux_x86_64": # musl currently has issues with LLVM 15+. if "musl" in target_triple: return "llvm-14-x86_64-linux" else: return "llvm-21-x86_64-linux" elif host_platform == "linux_aarch64": return "llvm-21-aarch64-linux" elif host_platform == "macos_arm64": return "llvm-aarch64-macos" elif host_platform == "macos_x86_64": return "llvm-x86_64-macos" else: raise Exception("unhandled host platform") def compress_python_archive( source_path: pathlib.Path, dist_path: pathlib.Path, basename: str ): dest_path = dist_path / ("%s.tar.zst" % basename) temp_path = dist_path / ("%s.tar.zst.tmp" % basename) print("compressing Python archive to %s" % dest_path) try: with source_path.open("rb") as ifh, temp_path.open("wb") as ofh: params = zstandard.ZstdCompressionParameters.from_level( 22, strategy=zstandard.STRATEGY_BTULTRA2 ) cctx = zstandard.ZstdCompressor(compression_params=params) cctx.copy_stream(ifh, ofh, source_path.stat().st_size) temp_path.rename(dest_path) finally: temp_path.unlink(missing_ok=True) print("%s has SHA256 %s" % (dest_path, hash_path(dest_path))) return dest_path def add_licenses_to_extension_entry(entry): """Add licenses keys to a ``extensions`` entry for JSON distribution info.""" have_licenses = False licenses = set() license_paths = set() license_public_domain = None have_local_link = False for link in entry["links"]: name = link["name"] if "path_static" in link or "path_dynamic" in link: have_local_link = True for value in DOWNLOADS.values(): if name not in value.get("library_names", []): continue # Don't add licenses annotations if they aren't defined. This leaves # things as "unknown" to consumers. if "licenses" not in value: continue have_licenses = True licenses |= set(value["licenses"]) license_paths.add("licenses/%s" % value["license_file"]) license_public_domain = value.get("license_public_domain", False) if have_local_link and not have_licenses: raise Exception( "missing license for local library for extension entry: %s" % entry ) if not have_licenses: return entry["licenses"] = sorted(licenses) entry["license_paths"] = sorted(license_paths) entry["license_public_domain"] = license_public_domain def add_env_common(env): """Adds extra keys to environment variables.""" cpu_count = multiprocessing.cpu_count() env["NUM_CPUS"] = "%d" % cpu_count env["NUM_JOBS_AGGRESSIVE"] = "%d" % max(cpu_count + 2, cpu_count * 2) if "CI" in os.environ: env["CI"] = "1" env_path = os.path.expanduser("~/.python-build-standalone-env") try: with open(env_path) as fh: for line in fh: line = line.strip() if line.startswith("#"): continue key, value = line.split("=", 1) print("adding %s from %s" % (key, env_path)) env[key] = value except FileNotFoundError: pass def exec_and_log(args, cwd, env): p = subprocess.Popen( args, cwd=cwd, env=env, bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) for line in iter(p.stdout.readline, b""): log(line.rstrip()) p.wait() if p.returncode: if "PYBUILD_BREAK_ON_FAILURE" in os.environ: import pdb pdb.set_trace() print("process exited %d" % p.returncode) sys.exit(p.returncode) def validate_python_json(info, extension_modules): """Validate a PYTHON.json file for problems. Raises an exception if an issue is detected. """ if extension_modules: missing = set(info["build_info"]["extensions"].keys()) - set( extension_modules.keys() ) if missing: raise Exception( "extension modules in PYTHON.json lack metadata: %s" % ", ".join(sorted(missing)) ) for name, variants in sorted(info["build_info"]["extensions"].items()): for ext in variants: local_links = set() for link in ext["links"]: if "path_static" in link: local_links.add(link["path_static"]) if "path_dynamic" in link: local_links.add(link["path_dynamic"]) if not local_links and "framework" not in link and "system" not in link: raise Exception( f"Invalid link entry for extension {name}: link type not defined" ) if ( local_links and not ext.get("licenses") and not ext.get("license_public_domain") ): raise Exception( "Missing license annotations for extension %s for library files %s" % (name, ", ".join(sorted(local_links))) ) def release_download_statistics(mode="by_asset"): import github by_tag = collections.Counter() by_build = collections.Counter() by_build_install_only = collections.Counter() # Default paging settings time out. Reduce page size as a workaround. gh = github.Github(per_page=5) repo = gh.get_repo("astral-sh/python-build-standalone") for release in repo.get_releases(): tag = release.tag_name for asset in release.assets: name = asset.name count = asset.download_count by_tag[tag] += count if name.endswith(".tar.zst"): # cpython-3.10.2-aarch64-apple-darwin-debug-20220220T1113.tar.zst build_parts = name.split("-") build = "-".join(build_parts[2:-1]) by_build[build] += count elif name.endswith("install_only.tar.gz"): # cpython-3.10.13+20240224-x86_64-apple-darwin-install_only.tar.gz build_parts = name.split("-") build = "-".join(build_parts[2:-1]) by_build_install_only[build] += count if mode == "by_asset": print("%d\t%s\t%s" % (count, tag, name)) if mode == "by_build": for build, count in sorted(by_build.items()): print("%d\t%s" % (count, build)) elif mode == "by_build_install_only": for build, count in sorted(by_build_install_only.items()): print("%d\t%s" % (count, build)) elif mode == "by_tag": for tag, count in sorted(by_tag.items()): print("%d\t%s" % (count, tag)) elif mode == "total": print("%d" % by_tag.total()) else: raise Exception("unhandled display mode: %s" % mode)
IntegrityError
python
donnemartin__interactive-coding-challenges
arrays_strings/priority_queue/test_priority_queue.py
{ "start": 18, "end": 958 }
class ____(unittest.TestCase): def test_priority_queue(self): priority_queue = PriorityQueue() self.assertEqual(priority_queue.extract_min(), None) priority_queue.insert(PriorityQueueNode('a', 20)) priority_queue.insert(PriorityQueueNode('b', 5)) priority_queue.insert(PriorityQueueNode('c', 15)) priority_queue.insert(PriorityQueueNode('d', 22)) priority_queue.insert(PriorityQueueNode('e', 40)) priority_queue.insert(PriorityQueueNode('f', 3)) priority_queue.decrease_key('f', 2) priority_queue.decrease_key('a', 19) mins = [] while priority_queue.array: mins.append(priority_queue.extract_min().key) self.assertEqual(mins, [2, 5, 15, 19, 22, 40]) print('Success: test_min_heap') def main(): test = TestPriorityQueue() test.test_priority_queue() if __name__ == '__main__': main()
TestPriorityQueue
python
ansible__ansible
lib/ansible/config/manager.py
{ "start": 1607, "end": 11980 }
class ____(t.Protocol): """Protocol representing an `EncryptedString`, since it cannot be imported here.""" # DTFIX-FUTURE: collapse this with the one in collection loader, once we can def _decrypt(self) -> str: ... def _get_config_label(plugin_type: str, plugin_name: str, config: str) -> str: """Return a label for the given config.""" entry = f'{config!r}' if plugin_type: entry += ' for' if plugin_name: entry += f' {plugin_name!r}' entry += f' {plugin_type} plugin' return entry def ensure_type(value: object, value_type: str | None, origin: str | None = None, origin_ftype: str | None = None) -> t.Any: """ Converts `value` to the requested `value_type`; raises `ValueError` for failed conversions. Values for `value_type` are: * boolean/bool: Return a `bool` by applying non-strict `bool` filter rules: 'y', 'yes', 'on', '1', 'true', 't', 1, 1.0, True return True, any other value is False. * integer/int: Return an `int`. Accepts any `str` parseable by `int` or numeric value with a zero mantissa (including `bool`). * float: Return a `float`. Accepts any `str` parseable by `float` or numeric value (including `bool`). * list: Return a `list`. Accepts `list` or `Sequence`. Also accepts, `str`, splitting on ',' while stripping whitespace and unquoting items. * none: Return `None`. Accepts only the string "None". * path: Return a resolved path. Accepts `str`. * temppath/tmppath/tmp: Return a unique temporary directory inside the resolved path specified by the value. * pathspec: Return a `list` of resolved paths. Accepts a `list` or `Sequence`. Also accepts `str`, splitting on ':'. * pathlist: Return a `list` of resolved paths. Accepts a `list` or `Sequence`. Also accepts `str`, splitting on `,` while stripping whitespace from paths. * dictionary/dict: Return a `dict`. Accepts `dict` or `Mapping`. * string/str: Return a `str`. Accepts `bool`, `int`, `float`, `complex` or `str`. Path resolution ensures paths are `str` with expansion of '{{CWD}}', environment variables and '~'. Non-absolute paths are expanded relative to the basedir from `origin`, if specified. No conversion is performed if `value_type` is unknown or `value` is `None`. When `origin_ftype` is "ini", a `str` result will be unquoted. """ if value is None: return None original_value = value copy_tags = value_type not in ('temppath', 'tmppath', 'tmp') value = _ensure_type(value, value_type, origin) if copy_tags and value is not original_value: if isinstance(value, list): value = [AnsibleTagHelper.tag_copy(original_value, item) for item in value] value = AnsibleTagHelper.tag_copy(original_value, value) if isinstance(value, str) and origin_ftype and origin_ftype == 'ini': value = unquote(value) return value def _ensure_type(value: object, value_type: str | None, origin: str | None = None) -> t.Any: """Internal implementation for `ensure_type`, call that function instead.""" original_value = value basedir = origin if origin and os.path.isabs(origin) and os.path.exists(to_bytes(origin)) else None if value_type: value_type = value_type.lower() match value_type: case 'boolean' | 'bool': return boolean(value, strict=False) case 'integer' | 'int': if isinstance(value, int): # handle both int and bool (which is an int) return int(value) if isinstance(value, (float, str)): try: # use Decimal for all other source type conversions; non-zero mantissa is a failure if (decimal_value := decimal.Decimal(value)) == (int_part := int(decimal_value)): return int_part except (decimal.DecimalException, ValueError): pass case 'float': if isinstance(value, float): return value if isinstance(value, (int, str)): try: return float(value) except ValueError: pass case 'list': if isinstance(value, list): return value if isinstance(value, str): return [unquote(x.strip()) for x in value.split(',')] if isinstance(value, Sequence) and not isinstance(value, bytes): return list(value) case 'none': if value == "None": return None case 'path': if isinstance(value, str): return resolve_path(value, basedir=basedir) case 'temppath' | 'tmppath' | 'tmp': if isinstance(value, str): value = resolve_path(value, basedir=basedir) if not os.path.exists(value): makedirs_safe(value, 0o700) prefix = 'ansible-local-%s' % os.getpid() value = tempfile.mkdtemp(prefix=prefix, dir=value) atexit.register(cleanup_tmp_file, value, warn=True) return value case 'pathspec': if isinstance(value, str): value = value.split(os.pathsep) if isinstance(value, Sequence) and not isinstance(value, bytes) and all(isinstance(x, str) for x in value): return [resolve_path(x, basedir=basedir) for x in value] case 'pathlist': if isinstance(value, str): value = [x.strip() for x in value.split(',')] if isinstance(value, Sequence) and not isinstance(value, bytes) and all(isinstance(x, str) for x in value): return [resolve_path(x, basedir=basedir) for x in value] case 'dictionary' | 'dict': if isinstance(value, dict): return value if isinstance(value, Mapping): return dict(value) case 'string' | 'str': if isinstance(value, str): return value if isinstance(value, (bool, int, float, complex)): return str(value) if isinstance(value, _EncryptedStringProtocol): return value._decrypt() case _: # FIXME: define and document a pass-through value_type (None, 'raw', 'object', '', ...) and then deprecate acceptance of unknown types return value # return non-str values of unknown value_type as-is raise ValueError(f'Invalid value provided for {value_type!r}: {original_value!r}') # FIXME: see if this can live in utils/path def resolve_path(path: str, basedir: str | None = None) -> str: """ resolve relative or 'variable' paths """ if '{{CWD}}' in path: # allow users to force CWD using 'magic' {{CWD}} path = path.replace('{{CWD}}', os.getcwd()) return unfrackpath(path, follow=False, basedir=basedir) # FIXME: generic file type? def get_config_type(cfile): ftype = None if cfile is not None: ext = os.path.splitext(cfile)[-1] if ext in ('.ini', '.cfg'): ftype = 'ini' elif ext in ('.yaml', '.yml'): ftype = 'yaml' else: raise AnsibleOptionsError("Unsupported configuration file extension for %s: %s" % (cfile, to_native(ext))) return ftype def find_ini_config_file(warnings=None): """ Load INI Config File order(first found is used): ENV, CWD, HOME, /etc/ansible """ # FIXME: eventually deprecate ini configs if warnings is None: # Note: In this case, warnings does nothing warnings = set() potential_paths = [] # A value that can never be a valid path so that we can tell if ANSIBLE_CONFIG was set later # We can't use None because we could set path to None. # Environment setting path_from_env = os.getenv("ANSIBLE_CONFIG", Sentinel) if path_from_env is not Sentinel: path_from_env = unfrackpath(path_from_env, follow=False) if os.path.isdir(to_bytes(path_from_env)): path_from_env = os.path.join(path_from_env, "ansible.cfg") potential_paths.append(path_from_env) # Current working directory warn_cmd_public = False try: cwd = os.getcwd() perms = os.stat(cwd) cwd_cfg = os.path.join(cwd, "ansible.cfg") if perms.st_mode & stat.S_IWOTH: # Working directory is world writable so we'll skip it. # Still have to look for a file here, though, so that we know if we have to warn if os.path.exists(cwd_cfg): warn_cmd_public = True else: potential_paths.append(to_text(cwd_cfg, errors='surrogate_or_strict')) except OSError: # If we can't access cwd, we'll simply skip it as a possible config source pass # Per user location potential_paths.append(unfrackpath("~/.ansible.cfg", follow=False)) # System location potential_paths.append("/etc/ansible/ansible.cfg") for path in potential_paths: b_path = to_bytes(path) if os.path.exists(b_path) and os.access(b_path, os.R_OK): break else: path = None # Emit a warning if all the following are true: # * We did not use a config from ANSIBLE_CONFIG # * There's an ansible.cfg in the current working directory that we skipped if path_from_env != path and warn_cmd_public: warnings.add(u"Ansible is being run in a world writable directory (%s)," u" ignoring it as an ansible.cfg source." u" For more information see" u" https://docs.ansible.com/ansible/devel/reference_appendices/config.html#cfg-in-world-writable-dir" % to_text(cwd)) return path def _add_base_defs_deprecations(base_defs): """Add deprecation source 'ansible.builtin' to deprecations in base.yml""" def process(entry): if 'deprecated' in entry: entry['deprecated']['collection_name'] = 'ansible.builtin' for dummy, data in base_defs.items(): process(data) for section in ('ini', 'env', 'vars'): if section in data: for entry in data[section]: process(entry)
_EncryptedStringProtocol
python
pymupdf__PyMuPDF
src/__init__.py
{ "start": 821574, "end": 834098 }
class ____(mupdf.FzPathWalker2): def __init__(self, dev): super().__init__() self.use_virtual_moveto() self.use_virtual_lineto() self.use_virtual_curveto() self.use_virtual_closepath() self.dev = dev def closepath(self, ctx): # trace_close(). #log(f'Walker(): {self.dev.pathdict=}') try: if self.dev.linecount == 3: if jm_checkrect(self.dev): #log(f'end1: {self.dev.pathdict=}') return self.dev.linecount = 0 # reset # of consec. lines if self.dev.havemove: if self.dev.lastpoint != self.dev.firstpoint: item = ("l", JM_py_from_point(self.dev.lastpoint), JM_py_from_point(self.dev.firstpoint)) self.dev.pathdict[dictkey_items].append(item) self.dev.lastpoint = self.dev.firstpoint self.dev.pathdict["closePath"] = False else: #log('setting self.dev.pathdict[ "closePath"] to true') self.dev.pathdict[ "closePath"] = True #log(f'end2: {self.dev.pathdict=}') self.dev.havemove = 0 except Exception: if g_exceptions_verbose: exception_info() raise def curveto(self, ctx, x1, y1, x2, y2, x3, y3): # trace_curveto(). #log(f'Walker(): {self.dev.pathdict=}') try: self.dev.linecount = 0 # reset # of consec. lines p1 = mupdf.fz_make_point(x1, y1) p2 = mupdf.fz_make_point(x2, y2) p3 = mupdf.fz_make_point(x3, y3) p1 = mupdf.fz_transform_point(p1, self.dev.ctm) p2 = mupdf.fz_transform_point(p2, self.dev.ctm) p3 = mupdf.fz_transform_point(p3, self.dev.ctm) self.dev.pathrect = mupdf.fz_include_point_in_rect(self.dev.pathrect, p1) self.dev.pathrect = mupdf.fz_include_point_in_rect(self.dev.pathrect, p2) self.dev.pathrect = mupdf.fz_include_point_in_rect(self.dev.pathrect, p3) list_ = ( "c", JM_py_from_point(self.dev.lastpoint), JM_py_from_point(p1), JM_py_from_point(p2), JM_py_from_point(p3), ) self.dev.lastpoint = p3 self.dev.pathdict[ dictkey_items].append( list_) except Exception: if g_exceptions_verbose: exception_info() raise def lineto(self, ctx, x, y): # trace_lineto(). #log(f'Walker(): {self.dev.pathdict=}') try: p1 = mupdf.fz_transform_point( mupdf.fz_make_point(x, y), self.dev.ctm) self.dev.pathrect = mupdf.fz_include_point_in_rect( self.dev.pathrect, p1) list_ = ( 'l', JM_py_from_point( self.dev.lastpoint), JM_py_from_point(p1), ) self.dev.lastpoint = p1 items = self.dev.pathdict[ dictkey_items] items.append( list_) self.dev.linecount += 1 # counts consecutive lines if self.dev.linecount == 4 and self.dev.path_type != trace_device_FILL_PATH: # shrink to "re" or "qu" item jm_checkquad(self.dev) except Exception: if g_exceptions_verbose: exception_info() raise def moveto(self, ctx, x, y): # trace_moveto(). if 0 and isinstance(self.dev.pathdict, dict): log(f'self.dev.pathdict:') for n, v in self.dev.pathdict.items(): log( ' {type(n)=} {len(n)=} {n!r} {n}: {v!r}: {v}') #log(f'Walker(): {type(self.dev.pathdict)=} {self.dev.pathdict=}') try: #log( '{=dev.ctm type(dev.ctm)}') self.dev.lastpoint = mupdf.fz_transform_point( mupdf.fz_make_point(x, y), self.dev.ctm, ) if mupdf.fz_is_infinite_rect( self.dev.pathrect): self.dev.pathrect = mupdf.fz_make_rect( self.dev.lastpoint.x, self.dev.lastpoint.y, self.dev.lastpoint.x, self.dev.lastpoint.y, ) self.dev.firstpoint = self.dev.lastpoint self.dev.havemove = 1 self.dev.linecount = 0 # reset # of consec. lines except Exception: if g_exceptions_verbose: exception_info() raise def jm_lineart_path(dev, ctx, path): ''' Create the "items" list of the path dictionary * either create or empty the path dictionary * reset the end point of the path * reset count of consecutive lines * invoke fz_walk_path(), which create the single items * if no items detected, empty path dict again ''' #log(f'{getattr(dev, "pathdict", None)=}') try: dev.pathrect = mupdf.FzRect( mupdf.FzRect.Fixed_INFINITE) dev.linecount = 0 dev.lastpoint = mupdf.FzPoint( 0, 0) dev.pathdict = dict() dev.pathdict[ dictkey_items] = [] # First time we create a Walker instance is slow, e.g. 0.3s, then later # times run in around 0.01ms. If Walker is defined locally instead of # globally, each time takes 0.3s. # walker = Walker(dev) # Unlike fz_run_page(), fz_path_walker callbacks are not passed # a pointer to the struct, instead they get an arbitrary # void*. The underlying C++ Director callbacks use this void* to # identify the fz_path_walker instance so in turn we need to pass # arg=walker.m_internal. mupdf.fz_walk_path( mupdf.FzPath(mupdf.ll_fz_keep_path(path)), walker, walker.m_internal) # Check if any items were added ... if not dev.pathdict[ dictkey_items]: dev.pathdict = None except Exception: if g_exceptions_verbose: exception_info() raise def jm_lineart_stroke_path( dev, ctx, path, stroke, ctm, colorspace, color, alpha, color_params): #log(f'{dev.pathdict=} {dev.clips=}') try: assert isinstance( ctm, mupdf.fz_matrix) dev.pathfactor = 1 if ctm.a != 0 and abs(ctm.a) == abs(ctm.d): dev.pathfactor = abs(ctm.a) elif ctm.b != 0 and abs(ctm.b) == abs(ctm.c): dev.pathfactor = abs(ctm.b) dev.ctm = mupdf.FzMatrix( ctm) # fz_concat(ctm, dev_ptm); dev.path_type = trace_device_STROKE_PATH jm_lineart_path( dev, ctx, path) if dev.pathdict is None: return dev.pathdict[ dictkey_type] = 's' dev.pathdict[ 'stroke_opacity'] = alpha dev.pathdict[ 'color'] = jm_lineart_color( colorspace, color) dev.pathdict[ dictkey_width] = dev.pathfactor * stroke.linewidth dev.pathdict[ 'lineCap'] = ( stroke.start_cap, stroke.dash_cap, stroke.end_cap, ) dev.pathdict[ 'lineJoin'] = dev.pathfactor * stroke.linejoin if 'closePath' not in dev.pathdict: #log('setting dev.pathdict["closePath"] to false') dev.pathdict['closePath'] = False # output the "dashes" string if stroke.dash_len: buff = mupdf.fz_new_buffer( 256) mupdf.fz_append_string( buff, "[ ") # left bracket for i in range( stroke.dash_len): # We use mupdf python's SWIG-generated floats_getitem() fn to # access float *stroke.dash_list[]. value = mupdf.floats_getitem( stroke.dash_list, i) # stroke.dash_list[i]. mupdf.fz_append_string( buff, f'{_format_g(dev.pathfactor * value)} ') mupdf.fz_append_string( buff, f'] {_format_g(dev.pathfactor * stroke.dash_phase)}') dev.pathdict[ 'dashes'] = buff else: dev.pathdict[ 'dashes'] = '[] 0' dev.pathdict[ dictkey_rect] = JM_py_from_rect(dev.pathrect) dev.pathdict['layer'] = dev.layer_name dev.pathdict[ 'seqno'] = dev.seqno if dev.clips: dev.pathdict[ 'level'] = dev.depth jm_append_merge(dev) dev.seqno += 1 except Exception: if g_exceptions_verbose: exception_info() raise def jm_lineart_clip_path(dev, ctx, path, even_odd, ctm, scissor): if not dev.clips: return dev.ctm = mupdf.FzMatrix(ctm) # fz_concat(ctm, trace_device_ptm); dev.path_type = trace_device_CLIP_PATH jm_lineart_path(dev, ctx, path) if dev.pathdict is None: return dev.pathdict[ dictkey_type] = 'clip' dev.pathdict[ 'even_odd'] = bool(even_odd) if 'closePath' not in dev.pathdict: #log(f'setting dev.pathdict["closePath"] to False') dev.pathdict['closePath'] = False dev.pathdict['scissor'] = JM_py_from_rect(compute_scissor(dev)) dev.pathdict['level'] = dev.depth dev.pathdict['layer'] = dev.layer_name jm_append_merge(dev) dev.depth += 1 def jm_lineart_clip_stroke_path(dev, ctx, path, stroke, ctm, scissor): if not dev.clips: return dev.ctm = mupdf.FzMatrix(ctm) # fz_concat(ctm, trace_device_ptm); dev.path_type = trace_device_CLIP_STROKE_PATH jm_lineart_path(dev, ctx, path) if dev.pathdict is None: return dev.pathdict['dictkey_type'] = 'clip' dev.pathdict['even_odd'] = None if 'closePath' not in dev.pathdict: #log(f'setting dev.pathdict["closePath"] to False') dev.pathdict['closePath'] = False dev.pathdict['scissor'] = JM_py_from_rect(compute_scissor(dev)) dev.pathdict['level'] = dev.depth dev.pathdict['layer'] = dev.layer_name jm_append_merge(dev) dev.depth += 1 def jm_lineart_clip_stroke_text(dev, ctx, text, stroke, ctm, scissor): if not dev.clips: return compute_scissor(dev) dev.depth += 1 def jm_lineart_clip_text(dev, ctx, text, ctm, scissor): if not dev.clips: return compute_scissor(dev) dev.depth += 1 def jm_lineart_clip_image_mask( dev, ctx, image, ctm, scissor): if not dev.clips: return compute_scissor(dev) dev.depth += 1 def jm_lineart_pop_clip(dev, ctx): if not dev.clips or not dev.scissors: return len_ = len(dev.scissors) if len_ < 1: return del dev.scissors[-1] dev.depth -= 1 def jm_lineart_begin_layer(dev, ctx, name): if name: dev.layer_name = name else: dev.layer_name = "" def jm_lineart_end_layer(dev, ctx): dev.layer_name = "" def jm_lineart_begin_group(dev, ctx, bbox, cs, isolated, knockout, blendmode, alpha): #log(f'{dev.pathdict=} {dev.clips=}') if not dev.clips: return dev.pathdict = { # Py_BuildValue("{s:s,s:N,s:N,s:N,s:s,s:f,s:i,s:N}", "type": "group", "rect": JM_py_from_rect(bbox), "isolated": bool(isolated), "knockout": bool(knockout), "blendmode": mupdf.fz_blendmode_name(blendmode), "opacity": alpha, "level": dev.depth, "layer": dev.layer_name } jm_append_merge(dev) dev.depth += 1 def jm_lineart_end_group(dev, ctx): #log(f'{dev.pathdict=} {dev.clips=}') if not dev.clips: return dev.depth -= 1 def jm_lineart_stroke_text(dev, ctx, text, stroke, ctm, colorspace, color, alpha, color_params): jm_trace_text(dev, text, 1, ctm, colorspace, color, alpha, dev.seqno) dev.seqno += 1 def jm_dev_linewidth( dev, ctx, path, stroke, matrix, colorspace, color, alpha, color_params): dev.linewidth = stroke.linewidth jm_increase_seqno( dev, ctx) def jm_increase_seqno( dev, ctx, *vargs): try: dev.seqno += 1 except Exception: if g_exceptions_verbose: exception_info() raise def planish_line(p1: point_like, p2: point_like) -> Matrix: """Compute matrix which maps line from p1 to p2 to the x-axis, such that it maintains its length and p1 * matrix = Point(0, 0). Args: p1, p2: point_like Returns: Matrix which maps p1 to Point(0, 0) and p2 to a point on the x axis at the same distance to Point(0,0). Will always combine a rotation and a transformation. """ p1 = Point(p1) p2 = Point(p2) return Matrix(util_hor_matrix(p1, p2))
Walker
python
django-import-export__django-import-export
import_export/utils.py
{ "start": 36, "end": 841 }
class ____: """Context manager wraps `atomic` if `using_transactions`. Replaces code:: if using_transactions: with transaction.atomic(using=using): return something() return something() """ def __init__(self, using_transactions, using): self.using_transactions = using_transactions if using_transactions: self.context_manager = transaction.atomic(using=using) def __enter__(self): if self.using_transactions: self.context_manager.__enter__() def __exit__(self, *args): if self.using_transactions: self.context_manager.__exit__(*args) def get_related_model(field): if hasattr(field, "related_model"): return field.related_model
atomic_if_using_transaction
python
allegroai__clearml
clearml/backend_api/services/v2_20/organization.py
{ "start": 209, "end": 2971 }
class ____(Request): """ Get all the user and system tags used for the company tasks and models :param include_system: If set to 'true' then the list of the system tags is also returned. The default value is 'false' :type include_system: bool :param filter: Filter on entities to collect tags from :type filter: dict """ _service = "organization" _action = "get_tags" _version = "2.20" _schema = { "definitions": {}, "properties": { "filter": { "description": "Filter on entities to collect tags from", "properties": { "system_tags": { "description": "The list of system tag values to filter by. Use 'null' value to specify empty system tags. Use '__Snot' value to specify that the following value should be excluded", "items": {"type": "string"}, "type": "array", }, "tags": { "description": "The list of tag values to filter by. Use 'null' value to specify empty tags. Use '__Snot' value to specify that the following value should be excluded", "items": {"type": "string"}, "type": "array", }, }, "type": ["object", "null"], }, "include_system": { "default": False, "description": "If set to 'true' then the list of the system tags is also returned. The default value is 'false'", "type": ["boolean", "null"], }, }, "type": "object", } def __init__(self, include_system: Optional[bool] = False, filter: Optional[dict] = None, **kwargs: Any) -> None: super(GetTagsRequest, self).__init__(**kwargs) self.include_system = include_system self.filter = filter @schema_property("include_system") def include_system(self) -> Optional[bool]: return self._property_include_system @include_system.setter def include_system(self, value: Optional[bool]) -> None: if value is None: self._property_include_system = None return self.assert_isinstance(value, "include_system", (bool,)) self._property_include_system = value @schema_property("filter") def filter(self) -> Optional[dict]: return self._property_filter @filter.setter def filter(self, value: Optional[dict]) -> None: if value is None: self._property_filter = None return self.assert_isinstance(value, "filter", (dict,)) self._property_filter = value
GetTagsRequest
python
jazzband__django-model-utils
tests/models.py
{ "start": 9978, "end": 10203 }
class ____(models.Model): name = models.CharField(max_length=20) number = models.IntegerField() name_tracker = ModelTracker(fields=['name']) number_tracker = ModelTracker(fields=['number'])
ModelTrackedMultiple
python
pytorch__pytorch
torch/utils/_contextlib.py
{ "start": 5915, "end": 6402 }
class ____(_DecoratorContextManager): """Allow a context manager to be used as a decorator without parentheses.""" @overload def __new__(cls, orig_func: F) -> F: ... # type: ignore[misc] @overload def __new__(cls, orig_func: None = None) -> Self: ... def __new__(cls, orig_func: F | None = None) -> Self | F: # type: ignore[misc] if orig_func is None: return super().__new__(cls) return cls()(orig_func)
_NoParamDecoratorContextManager
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py
{ "start": 55795, "end": 57844 }
class ____: @mock.patch(VERTEX_AI_PATH.format("dataset.DatasetHook")) def test_execute(self, mock_hook): op = ImportDataOperator( task_id=TASK_ID, gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN, region=GCP_LOCATION, project_id=GCP_PROJECT, dataset_id=TEST_DATASET_ID, import_configs=TEST_IMPORT_CONFIG, retry=RETRY, timeout=TIMEOUT, metadata=METADATA, ) SAMPLE_DATASET = { "name": "sample_translation_dataset", "display_name": "VertexAI dataset", "data_item_count": None, } INITIAL_DS_SIZE = 1 FINAL_DS_SIZE = 101 INITIAL_DS = {**SAMPLE_DATASET, "data_item_count": INITIAL_DS_SIZE} FINAL_DS = {**SAMPLE_DATASET, "data_item_count": FINAL_DS_SIZE} get_ds_mock = mock_hook.return_value.get_dataset get_ds_mock.side_effect = [Dataset(INITIAL_DS), Dataset(FINAL_DS)] res = op.execute(context={}) mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN) mock_hook.return_value.import_data.assert_called_once_with( region=GCP_LOCATION, project_id=GCP_PROJECT, dataset=TEST_DATASET_ID, import_configs=TEST_IMPORT_CONFIG, retry=RETRY, timeout=TIMEOUT, metadata=METADATA, ) assert res["total_data_items_imported"] == FINAL_DS_SIZE - INITIAL_DS_SIZE assert get_ds_mock.call_count == 2 sample_get_ds_kwargs = dict( region=GCP_LOCATION, project_id=GCP_PROJECT, dataset=TEST_DATASET_ID, retry=RETRY, timeout=TIMEOUT, metadata=METADATA, ) get_ds_mock.assert_has_calls( [ call(**sample_get_ds_kwargs), call(**sample_get_ds_kwargs), ] )
TestVertexAIImportDataOperator
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/external.py
{ "start": 18648, "end": 19897 }
class ____(graphene.ObjectType): event = graphene.Field(graphene.NonNull(GrapheneLocationStateChangeEvent)) class Meta: name = "LocationStateChangeSubscription" async def gen_location_state_changes(graphene_info: ResolveInfo): # This lives on the process context and is never modified/destroyed, so we can # access it directly context = graphene_info.context.process_context if not isinstance(context, WorkspaceProcessContext): return queue: asyncio.Queue[LocationStateChangeEvent] = asyncio.Queue() loop = asyncio.get_event_loop() def _enqueue(event): loop.call_soon_threadsafe(queue.put_nowait, event) token = context.add_state_subscriber(LocationStateSubscriber(_enqueue)) try: while True: event = await queue.get() yield GrapheneLocationStateChangeSubscription( event=GrapheneLocationStateChangeEvent( event_type=event.event_type, location_name=event.location_name, message=event.message, server_id=event.server_id, ), ) finally: context.rm_state_subscriber(token)
GrapheneLocationStateChangeSubscription
python
pytorch__pytorch
torch/fx/_graph_pickler.py
{ "start": 7143, "end": 8151 }
class ____: @classmethod def reduce_helper( cls, pickler: GraphPickler, obj: _SymNodeT, ) -> tuple[ Callable[[Self, _UnpickleState], _SymNodeT], tuple[Self, _UnpickleStateToken] ]: args = (cls(obj.node), pickler._unpickle_state) if isinstance(obj, torch.SymInt): # pyrefly: ignore [bad-return] return _SymNodePickleData.unpickle_sym_int, args else: raise NotImplementedError(f"Unhandled SymNode type {type(obj)}") def __init__(self, node: SymNode) -> None: self.expr = node._expr self.shape_env = node.shape_env self.pytype = node.pytype self.hint = node._hint def _to_sym_node(self) -> SymNode: assert self.shape_env is not None return SymNode(self.expr, self.shape_env, self.pytype, self.hint) def unpickle_sym_int(self, unpickle_state: _UnpickleState) -> torch.SymInt: return torch.SymInt(self._to_sym_node())
_SymNodePickleData
python
tensorflow__tensorflow
tensorflow/python/autograph/converters/return_statements.py
{ "start": 5711, "end": 5964 }
class ____(object): def __init__(self): self.do_return_var_name = None self.retval_var_name = None def __repr__(self): return 'return control: {}, return value: {}'.format( self.do_return_var_name, self.retval_var_name)
_Function