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
sympy__sympy
sympy/sets/ordinals.py
{ "start": 7045, "end": 7163 }
class ____(Ordinal): """The ordinal zero. OrdinalZero can be imported as ``ord0``. """ pass
OrdinalZero
python
networkx__networkx
networkx/linalg/tests/test_bethehessian.py
{ "start": 103, "end": 1268 }
class ____: @classmethod def setup_class(cls): deg = [3, 2, 2, 1, 0] cls.G = nx.havel_hakimi_graph(deg) cls.P = nx.path_graph(3) def test_bethe_hessian(self): "Bethe Hessian matrix" # fmt: off H = np.array([[4, -2, 0], [-2, 5, -2], [0, -2, 4]]) # fmt: on permutation = [2, 0, 1] # Bethe Hessian gives expected form np.testing.assert_equal(nx.bethe_hessian_matrix(self.P, r=2).todense(), H) # nodelist is correctly implemented np.testing.assert_equal( nx.bethe_hessian_matrix(self.P, r=2, nodelist=permutation).todense(), H[np.ix_(permutation, permutation)], ) # Equal to Laplacian matrix when r=1 np.testing.assert_equal( nx.bethe_hessian_matrix(self.G, r=1).todense(), nx.laplacian_matrix(self.G).todense(), ) # Correct default for the regularizer r np.testing.assert_equal( nx.bethe_hessian_matrix(self.G).todense(), nx.bethe_hessian_matrix(self.G, r=1.25).todense(), )
TestBetheHessian
python
PrefectHQ__prefect
src/prefect/client/base.py
{ "start": 1829, "end": 6075 }
class ____(Protocol): async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: ... @asynccontextmanager async def app_lifespan_context(app: ASGIApp) -> AsyncGenerator[None, None]: """ A context manager that calls startup/shutdown hooks for the given application. Lifespan contexts are cached per application to avoid calling the lifespan hooks more than once if the context is entered in nested code. A no-op context will be returned if the context for the given application is already being managed. This manager is robust to concurrent access within the event loop. For example, if you have concurrent contexts for the same application, it is guaranteed that startup hooks will be called before their context starts and shutdown hooks will only be called after their context exits. A reference count is used to support nested use of clients without running lifespan hooks excessively. The first client context entered will create and enter a lifespan context. Each subsequent client will increment a reference count but will not create a new lifespan context. When each client context exits, the reference count is decremented. When the last client context exits, the lifespan will be closed. In simple nested cases, the first client context will be the one to exit the lifespan. However, if client contexts are entered concurrently they may not exit in a consistent order. If the first client context was responsible for closing the lifespan, it would have to wait until all other client contexts to exit to avoid firing shutdown hooks while the application is in use. Waiting for the other clients to exit can introduce deadlocks, so, instead, the first client will exit without closing the lifespan context and reference counts will be used to ensure the lifespan is closed once all of the clients are done. """ # TODO: A deadlock has been observed during multithreaded use of clients while this # lifespan context is being used. This has only been reproduced on Python 3.7 # and while we hope to discourage using multiple event loops in threads, this # bug may emerge again. # See https://github.com/PrefectHQ/orion/pull/1696 thread_id = threading.get_ident() # The id of the application is used instead of the hash so each application instance # is managed independently even if they share the same settings. We include the # thread id since applications are managed separately per thread. key = (thread_id, id(app)) # On exception, this will be populated with exception details exc_info = (None, None, None) # Get a lock unique to this thread since anyio locks are not threadsafe lock = APP_LIFESPANS_LOCKS[thread_id] async with lock: if key in APP_LIFESPANS: # The lifespan is already being managed, just increment the reference count APP_LIFESPANS_REF_COUNTS[key] += 1 else: # Create a new lifespan manager APP_LIFESPANS[key] = context = LifespanManager( app, startup_timeout=30, shutdown_timeout=30 ) APP_LIFESPANS_REF_COUNTS[key] = 1 # Ensure we enter the context before releasing the lock so startup hooks # are complete before another client can be used await context.__aenter__() try: yield except BaseException: exc_info = sys.exc_info() raise finally: # If we do not shield against anyio cancellation, the lock will return # immediately and the code in its context will not run, leaving the lifespan # open with anyio.CancelScope(shield=True): async with lock: # After the consumer exits the context, decrement the reference count APP_LIFESPANS_REF_COUNTS[key] -= 1 # If this the last context to exit, close the lifespan if APP_LIFESPANS_REF_COUNTS[key] <= 0: APP_LIFESPANS_REF_COUNTS.pop(key) context = APP_LIFESPANS.pop(key) await context.__aexit__(*exc_info)
ASGIApp
python
sqlalchemy__sqlalchemy
test/sql/test_compare.py
{ "start": 5508, "end": 48348 }
class ____: # lambdas which return a tuple of ColumnElement objects. # must return at least two objects that should compare differently. # to test more varieties of "difference" additional objects can be added. fixtures = [ lambda: ( column("q"), column("x"), column("q", Integer), column("q", String), ), lambda: (~column("q", Boolean), ~column("p", Boolean)), lambda: ( table_a.c.a.label("foo"), table_a.c.a.label("bar"), table_a.c.b.label("foo"), ), lambda: ( _label_reference(table_a.c.a.desc()), _label_reference(table_a.c.a.asc()), ), lambda: ( TypeClause(String(50)), TypeClause(DateTime()), ), lambda: ( table_a.c.a, ElementList([table_a.c.a]), ElementList([table_a.c.a, table_a.c.b]), ), lambda: ( table_a.c.a, OrderByList([table_a.c.a]), OrderByList( [table_a.c.a, OrderByList([table_a.c.b, table_b.c.a])] ), ), lambda: (_textual_label_reference("a"), _textual_label_reference("b")), lambda: ( text("select a, b from table").columns(a=Integer, b=String), text("select a, b, c from table").columns( a=Integer, b=String, c=Integer ), text("select a, b, c from table where foo=:bar").bindparams( bindparam("bar", type_=Integer) ), text("select a, b, c from table where foo=:foo").bindparams( bindparam("foo", type_=Integer) ), text("select a, b, c from table where foo=:bar").bindparams( bindparam("bar", type_=String) ), ), lambda: ( # test #11471 text("select * from table") .columns(a=Integer()) .add_cte(table_b.select().cte()), text("select * from table") .columns(a=Integer()) .add_cte(table_b.select().where(table_b.c.a > 5).cte()), ), lambda: ( union( select(table_a).where(table_a.c.a > 1), select(table_a).where(table_a.c.a < 1), ).add_cte(select(table_b).where(table_b.c.a > 1).cte("ttt")), union( select(table_a).where(table_a.c.a > 1), select(table_a).where(table_a.c.a < 1), ).add_cte(select(table_b).where(table_b.c.a < 1).cte("ttt")), union( select(table_a).where(table_a.c.a > 1), select(table_a).where(table_a.c.a < 1), ) .add_cte(select(table_b).where(table_b.c.a > 1).cte("ttt")) ._annotate({"foo": "bar"}), ), lambda: ( union( select(table_a).where(table_a.c.a > 1), select(table_a).where(table_a.c.a < 1), ).self_group(), union( select(table_a).where(table_a.c.a > 1), select(table_a).where(table_a.c.a < 1), ) .self_group() ._annotate({"foo": "bar"}), ), lambda: ( literal(1).op("+")(literal(1)), literal(1).op("-")(literal(1)), column("q").op("-")(literal(1)), UnaryExpression(table_a.c.b, modifier=operators.neg), UnaryExpression(table_a.c.b, modifier=operators.desc_op), UnaryExpression(table_a.c.b, modifier=operators.custom_op("!")), UnaryExpression(table_a.c.b, modifier=operators.custom_op("~")), ), lambda: ( column("q") == column("x"), column("q") == column("y"), column("z") == column("x"), (column("z") == column("x")).self_group(), (column("q") == column("x")).self_group(), column("z") + column("x"), column("z").op("foo")(column("x")), column("z").op("foo")(literal(1)), column("z").op("bar")(column("x")), column("z") - column("x"), column("x") - column("z"), column("z") > column("x"), column("x").in_([5, 7]), column("x").in_([10, 7, 8]), # note these two are mathematically equivalent but for now they # are considered to be different column("z") >= column("x"), column("x") <= column("z"), column("q").between(5, 6), column("q").between(5, 6, symmetric=True), column("q").like("somstr"), column("q").like("somstr", escape="\\"), column("q").like("somstr", escape="X"), ), lambda: ( column("q").regexp_match("y", flags="ig"), column("q").regexp_match("y", flags="q"), column("q").regexp_match("y"), column("q").regexp_replace("y", "z", flags="ig"), column("q").regexp_replace("y", "z", flags="q"), column("q").regexp_replace("y", "z"), ), lambda: ( column("q", ARRAY(Integer))[3] == 5, column("q", ARRAY(Integer))[3:5] == 5, ), lambda: ( table_a.c.a, table_a.c.a._annotate({"orm": True}), table_a.c.a._annotate({"orm": True})._annotate({"bar": False}), table_a.c.a._annotate( {"orm": True, "parententity": MyEntity("a", table_a)} ), table_a.c.a._annotate( {"orm": True, "parententity": MyEntity("b", table_a)} ), table_a.c.a._annotate( {"orm": True, "parententity": MyEntity("b", select(table_a))} ), table_a.c.a._annotate( { "orm": True, "parententity": MyEntity( "b", select(table_a).where(table_a.c.a == 5) ), } ), ), lambda: ( table_a, table_a._annotate({"orm": True}), table_a._annotate({"orm": True})._annotate({"bar": False}), table_a._annotate( {"orm": True, "parententity": MyEntity("a", table_a)} ), table_a._annotate( {"orm": True, "parententity": MyEntity("b", table_a)} ), table_a._annotate( {"orm": True, "parententity": MyEntity("b", select(table_a))} ), ), lambda: ( table("a", column("x"), column("y")), table("a", column("x"), column("y"), schema="q"), table("a", column("x"), column("y"), schema="y"), table("a", column("x"), column("y"))._annotate({"orm": True}), table("b", column("x"), column("y"))._annotate({"orm": True}), ), lambda: ( cast(column("q"), Integer), cast(column("q"), Float), cast(column("p"), Integer), ), lambda: ( column("x", JSON)["key1"], column("x", JSON)["key1"].as_boolean(), column("x", JSON)["key1"].as_float(), column("x", JSON)["key1"].as_integer(), column("x", JSON)["key1"].as_string(), column("y", JSON)["key1"].as_integer(), column("y", JSON)["key1"].as_string(), ), lambda: ( bindparam("x"), bindparam("x", literal_execute=True), bindparam("y"), bindparam("x", type_=Integer), bindparam("x", type_=String), bindparam(None), ), lambda: ( DMLTargetCopy(table_a.c.a), DMLTargetCopy(table_a.c.b), ), lambda: (_OffsetLimitParam("x"), _OffsetLimitParam("y")), lambda: (func.foo(), func.foo(5), func.bar()), lambda: ( func.package1.foo(5), func.package2.foo(5), func.packge1.bar(5), func.foo(), ), lambda: (func.current_date(), func.current_time()), lambda: ( func.next_value(Sequence("q")), func.next_value(Sequence("p")), ), lambda: ( func.json_to_recordset("{foo}"), func.json_to_recordset("{foo}").table_valued("a", "b"), func.jsonb_to_recordset("{foo}").table_valued("a", "b"), func.json_to_recordset("{foo}") .table_valued("a", "b") .render_derived(), func.json_to_recordset("{foo}") .table_valued("a", with_ordinality="b") .render_derived(), func.json_to_recordset("{foo}") .table_valued("a", with_ordinality="c") .render_derived(), func.json_to_recordset("{foo}") .table_valued(column("a", Integer), column("b", String)) .render_derived(), func.json_to_recordset("{foo}") .table_valued(column("a", Integer), column("b", String)) .render_derived(with_types=True), func.json_to_recordset("{foo}") .table_valued("b", "c") .render_derived(), func.json_to_recordset("{foo}") .table_valued("a", "b") .alias("foo") .render_derived(with_types=True), func.json_to_recordset("{foo}") .table_valued("a", "b") .alias("foo"), func.json_to_recordset("{foo}").column_valued(), func.json_to_recordset("{foo}").scalar_table_valued("foo"), ), lambda: ( aggregate_order_by(column("a"), column("a")), aggregate_order_by(column("a"), column("b")), aggregate_order_by(column("a"), column("a").desc()), aggregate_order_by(column("a"), column("a").nulls_first()), aggregate_order_by(column("a"), column("a").desc().nulls_first()), aggregate_order_by(column("a", Integer), column("b")), aggregate_order_by(column("a"), column("b"), column("c")), aggregate_order_by(column("a"), column("c"), column("b")), aggregate_order_by(column("a"), column("b").desc(), column("c")), aggregate_order_by( column("a"), column("b").nulls_first(), column("c") ), aggregate_order_by( column("a"), column("b").desc().nulls_first(), column("c") ), aggregate_order_by(column("a", Integer), column("a"), column("b")), ), lambda: (table_a.table_valued(), table_b.table_valued()), lambda: (True_(), False_()), lambda: (Null(),), lambda: (ReturnTypeFromArgs("foo"), ReturnTypeFromArgs(5)), lambda: (FunctionElement(5), FunctionElement(5, 6)), lambda: (func.count(), func.not_count()), lambda: (func.char_length("abc"), func.char_length("def")), lambda: (GenericFunction("a", "b"), GenericFunction("a")), lambda: (CollationClause("foobar"), CollationClause("batbar")), lambda: ( type_coerce(column("q", Integer), String), type_coerce(column("q", Integer), Float), type_coerce(column("z", Integer), Float), ), lambda: (table_a.c.a, table_b.c.a), lambda: (tuple_(1, 2), tuple_(3, 4)), lambda: (func.array_agg([1, 2]), func.array_agg([3, 4])), lambda: ( func.aggregate_strings(table_a.c.b, ","), func.aggregate_strings(table_b_like_a.c.b, ","), ), lambda: ( func.percentile_cont(0.5).within_group(table_a.c.a), func.percentile_cont(0.5).within_group(table_a.c.b), func.percentile_cont(0.5).within_group(table_a.c.a, table_a.c.b), func.percentile_cont(0.5).within_group( table_a.c.a, table_a.c.b, column("q") ), ), lambda: ( func.is_equal("a", "b").as_comparison(1, 2), func.is_equal("a", "c").as_comparison(1, 2), func.is_equal("a", "b").as_comparison(2, 1), func.is_equal("a", "b", "c").as_comparison(1, 2), func.foobar("a", "b").as_comparison(1, 2), ), lambda: ( func.row_number().over(order_by=table_a.c.a), func.row_number().over(order_by=table_a.c.a, range_=(0, 10)), func.row_number().over(order_by=table_a.c.a, range_=(None, 10)), func.row_number().over(order_by=table_a.c.a, rows=(None, 20)), func.row_number().over(order_by=table_a.c.a, groups=(None, 20)), func.row_number().over( order_by=table_a.c.a, range_=FrameClause( 2, 3, FrameClauseType.FOLLOWING, FrameClauseType.PRECEDING, ), ), func.row_number().over( order_by=table_a.c.a, rows=FrameClause( 2, 3, FrameClauseType.FOLLOWING, FrameClauseType.PRECEDING, ), ), func.row_number().over( order_by=table_a.c.a, groups=FrameClause( 2, 3, FrameClauseType.FOLLOWING, FrameClauseType.PRECEDING, ), ), func.row_number().over(order_by=table_a.c.b), func.row_number().over( order_by=table_a.c.a, partition_by=table_a.c.b ), ), lambda: ( func.count(1).filter(table_a.c.a == 5), func.count(1).filter(table_a.c.a == 10), func.foob(1).filter(table_a.c.a == 10), ), lambda: ( and_(table_a.c.a == 5, table_a.c.b == table_b.c.a), and_(table_a.c.a == 5, table_a.c.a == table_b.c.a), or_(table_a.c.a == 5, table_a.c.b == table_b.c.a), ClauseList(table_a.c.a == 5, table_a.c.b == table_b.c.a), ClauseList(table_a.c.a == 5, table_a.c.b == table_a.c.a), ), lambda: ( case((table_a.c.a == 5, 10), (table_a.c.a == 10, 20)), case((table_a.c.a == 18, 10), (table_a.c.a == 10, 20)), case((table_a.c.a == 5, 10), (table_a.c.b == 10, 20)), case( (table_a.c.a == 5, 10), (table_a.c.b == 10, 20), (table_a.c.a == 9, 12), ), case( (table_a.c.a == 5, 10), (table_a.c.a == 10, 20), else_=30, ), case({"wendy": "W", "jack": "J"}, value=table_a.c.a, else_="E"), case({"wendy": "W", "jack": "J"}, value=table_a.c.b, else_="E"), case({"wendy_w": "W", "jack": "J"}, value=table_a.c.a, else_="E"), ), lambda: ( extract("foo", table_a.c.a), extract("foo", table_a.c.b), extract("bar", table_a.c.a), ), lambda: ( Slice(1, 2, 5), Slice(1, 5, 5), Slice(1, 5, 10), Slice(2, 10, 15), ), lambda: ( select(table_a.c.a), select(table_a.c.a, table_a.c.b), select(table_a.c.b, table_a.c.a), select(table_a.c.b, table_a.c.a).limit(5), select(table_a.c.b, table_a.c.a).limit(5).offset(10), select(table_a.c.b, table_a.c.a) .limit(literal_column("foobar")) .offset(10), select(table_a.c.b, table_a.c.a).set_label_style( LABEL_STYLE_TABLENAME_PLUS_COL ), select(table_a.c.b, table_a.c.a).set_label_style(LABEL_STYLE_NONE), select(table_a.c.a).where(table_a.c.b == 5), select(table_a.c.a) .where(table_a.c.b == 5) .where(table_a.c.a == 10), select(table_a.c.a).where(table_a.c.b == 5).with_for_update(), select(table_a.c.a) .where(table_a.c.b == 5) .with_for_update(nowait=True), select(table_a.c.a) .where(table_a.c.b == 5) .with_for_update(nowait=True, skip_locked=True), select(table_a.c.a) .where(table_a.c.b == 5) .with_for_update(nowait=True, read=True), select(table_a.c.a) .where(table_a.c.b == 5) .with_for_update(of=table_a.c.a), select(table_a.c.a) .where(table_a.c.b == 5) .with_for_update(of=table_a.c.b), select(table_a.c.a) .where(table_a.c.b == 5) .with_for_update(nowait=True, key_share=True), select(table_a.c.a).where(table_a.c.b == 5).correlate(table_b), select(table_a.c.a) .where(table_a.c.b == 5) .correlate_except(table_b), ), lambda: ( select(table_a.c.a), select(table_a.c.a).limit(2), select(table_a.c.a).limit(3), select(table_a.c.a).fetch(3), select(table_a.c.a).fetch(2), select(table_a.c.a).fetch(2, percent=True), select(table_a.c.a).fetch(2, with_ties=True), select(table_a.c.a).fetch(2, with_ties=True, percent=True), select(table_a.c.a).fetch(2, oracle_fetch_approximate=True), select(table_a.c.a).fetch(2).offset(3), select(table_a.c.a).fetch(2).offset(5), select(table_a.c.a).limit(2).offset(5), select(table_a.c.a).limit(2).offset(3), select(table_a.c.a).union(select(table_a.c.a)).limit(2).offset(3), union(select(table_a.c.a), select(table_a.c.b)).limit(2).offset(3), union(select(table_a.c.a), select(table_a.c.b)).limit(6).offset(3), union(select(table_a.c.a), select(table_a.c.b)).limit(6).offset(8), union(select(table_a.c.a), select(table_a.c.b)).fetch(2).offset(8), union(select(table_a.c.a), select(table_a.c.b)).fetch(6).offset(8), union(select(table_a.c.a), select(table_a.c.b)).fetch(6).offset(3), union(select(table_a.c.a), select(table_a.c.b)) .fetch(6, percent=True) .offset(3), union(select(table_a.c.a), select(table_a.c.b)) .fetch(6, with_ties=True) .offset(3), union(select(table_a.c.a), select(table_a.c.b)) .fetch(6, with_ties=True, percent=True) .offset(3), union(select(table_a.c.a), select(table_a.c.b)).limit(6), union(select(table_a.c.a), select(table_a.c.b)).offset(6), ), lambda: ( select(table_a.c.a), select(table_a.c.a).join(table_b, table_a.c.a == table_b.c.a), select(table_a.c.a).join_from( table_a, table_b, table_a.c.a == table_b.c.a ), select(table_a.c.a).join_from(table_a, table_b), select(table_a.c.a).join_from(table_c, table_b), select(table_a.c.a) .join(table_b, table_a.c.a == table_b.c.a) .join(table_c, table_b.c.b == table_c.c.x), select(table_a.c.a).join(table_b), select(table_a.c.a).join(table_c), select(table_a.c.a).join(table_b, table_a.c.a == table_b.c.b), select(table_a.c.a).join(table_c, table_a.c.a == table_c.c.x), ), lambda: ( select(table_a.c.a), select(table_a.c.a).add_cte(table_b.insert().cte()), table_a.insert(), table_a.delete(), table_a.update(), table_a.insert().add_cte(table_b.insert().cte()), table_a.delete().add_cte(table_b.insert().cte()), table_a.update().add_cte(table_b.insert().cte()), ), lambda: ( select(table_a.c.a).cte(), select(table_a.c.a).cte(nesting=True), select(table_a.c.a).cte(recursive=True), select(table_a.c.a).cte(name="some_cte", recursive=True), select(table_a.c.a).cte(name="some_cte"), select(table_a.c.a).cte(name="some_cte").alias("other_cte"), select(table_a.c.a) .cte(name="some_cte") .union_all(select(table_a.c.a)), select(table_a.c.a) .cte(name="some_cte") .union_all(select(table_a.c.b)), select(table_a.c.a).lateral(), select(table_a.c.a).lateral(name="bar"), table_a.tablesample(0.75), table_a.tablesample(func.bernoulli(1)), table_a.tablesample(func.bernoulli(1), seed=func.random()), table_a.tablesample(func.bernoulli(1), seed=func.other_random()), table_a.tablesample(func.hoho(1)), table_a.tablesample(func.bernoulli(1), name="bar"), table_a.tablesample( func.bernoulli(1), name="bar", seed=func.random() ), ), lambda: ( # test issue #6503 # join from table_a -> table_c, select table_b.c.a select(table_a).join(table_c).with_only_columns(table_b.c.a), # join from table_b -> table_c, select table_b.c.a select(table_b.c.a).join(table_c).with_only_columns(table_b.c.a), select(table_a).with_only_columns(table_b.c.a), ), lambda: ( table_a.insert(), table_a.insert().return_defaults(), table_a.insert().return_defaults(table_a.c.a), table_a.insert().return_defaults(table_a.c.b), table_a.insert().values({})._annotate({"nocache": True}), table_b.insert(), table_b.insert().with_dialect_options(sqlite_foo="some value"), table_b.insert().from_select(["a", "b"], select(table_a)), table_b.insert().from_select( ["a", "b"], select(table_a).where(table_a.c.a > 5) ), table_b.insert().from_select(["a", "b"], select(table_b)), table_b.insert().from_select(["c", "d"], select(table_a)), table_b.insert().returning(table_b.c.a), table_b.insert().returning(table_b.c.a, table_b.c.b), table_b.insert().inline(), table_b.insert().prefix_with("foo"), table_b.insert().with_hint("RUNFAST"), table_b.insert().values(a=5, b=10), table_b.insert().values(a=5), table_b.insert() .values({table_b.c.a: 5, "b": 10}) ._annotate({"nocache": True}), table_b.insert().values(a=7, b=10), table_b.insert().values(a=5, b=10).inline(), table_b.insert() .values([{"a": 5, "b": 10}, {"a": 8, "b": 12}]) ._annotate({"nocache": True}), table_b.insert() .values([{"a": 9, "b": 10}, {"a": 8, "b": 7}]) ._annotate({"nocache": True}), table_b.insert() .values([(5, 10), (8, 12)]) ._annotate({"nocache": True}), table_b.insert() .values([(5, 9), (5, 12)]) ._annotate({"nocache": True}), ), lambda: ( table_b.update(), table_b.update().return_defaults(), table_b.update().return_defaults(table_b.c.a), table_b.update().return_defaults(table_b.c.b), table_b.update().where(table_b.c.a == 5), table_b.update().where(table_b.c.b == 5), table_b.update() .where(table_b.c.b == 5) .with_dialect_options(mysql_limit=10), table_b.update() .where(table_b.c.b == 5) .with_dialect_options(mysql_limit=10, sqlite_foo="some value"), table_b.update().where(table_b.c.a == 5).values(a=5, b=10), table_b.update().where(table_b.c.a == 5).values(a=5, b=10, c=12), table_b.update() .where(table_b.c.b == 5) .values(a=5, b=10) ._annotate({"nocache": True}), table_b.update().values(a=5, b=10), table_b.update() .values({"a": 5, table_b.c.b: 10}) ._annotate({"nocache": True}), table_b.update().values(a=7, b=10), table_b.update().ordered_values(("a", 5), ("b", 10)), table_b.update().ordered_values(("b", 10), ("a", 5)), table_b.update().ordered_values((table_b.c.a, 5), ("b", 10)), ), lambda: ( table_b.delete(), table_b.delete().with_dialect_options(sqlite_foo="some value"), table_b.delete().where(table_b.c.a == 5), table_b.delete().where(table_b.c.b == 5), ), lambda: ( values( column("mykey", Integer), column("mytext", String), column("myint", Integer), name="myvalues", ) .data([(1, "textA", 99), (2, "textB", 88)]) ._annotate({"nocache": True}), values( column("mykey", Integer), column("mytext", String), column("myint", Integer), name="myvalues", literal_binds=True, ) .data([(1, "textA", 99), (2, "textB", 88)]) ._annotate({"nocache": True}), values( column("mykey", Integer), column("mytext", String), column("myint", Integer), name="myothervalues", ) .data([(1, "textA", 99), (2, "textB", 88)]) ._annotate({"nocache": True}), values( column("mykey", Integer), column("mytext", String), column("myint", Integer), name="myvalues", ) .data([(1, "textA", 89), (2, "textG", 88)]) ._annotate({"nocache": True}), values( column("mykey", Integer), column("mynottext", String), column("myint", Integer), name="myvalues", ) .data([(1, "textA", 99), (2, "textB", 88)]) ._annotate({"nocache": True}), # TODO: difference in type # values( # column("mykey", Integer), # column("mytext", Text), # column("myint", Integer), # name="myvalues", # ) # .data([(1, "textA", 99), (2, "textB", 88)]) # ._annotate({"nocache": True}), ), lambda: ( values( column("mykey", Integer), column("mytext", String), column("myint", Integer), name="myvalues", ) .data([(1, "textA", 99), (2, "textB", 88)]) .scalar_values() ._annotate({"nocache": True}), values( column("mykey", Integer), column("mytext", String), column("myint", Integer), name="myvalues", literal_binds=True, ) .data([(1, "textA", 99), (2, "textB", 88)]) .scalar_values() ._annotate({"nocache": True}), values( column("mykey", Integer), column("mytext", String), column("myint", Integer), name="myvalues", ) .data([(1, "textA", 89), (2, "textG", 88)]) .scalar_values() ._annotate({"nocache": True}), values( column("mykey", Integer), column("mynottext", String), column("myint", Integer), name="myvalues", ) .data([(1, "textA", 99), (2, "textB", 88)]) .scalar_values() ._annotate({"nocache": True}), # TODO: difference in type # values( # column("mykey", Integer), # column("mytext", Text), # column("myint", Integer), # name="myvalues", # ) # .data([(1, "textA", 99), (2, "textB", 88)]) # .scalar_values() # ._annotate({"nocache": True}), ), lambda: ( select(table_a.c.a), select(table_a.c.a).prefix_with("foo"), select(table_a.c.a).prefix_with("foo", dialect="mysql"), select(table_a.c.a).prefix_with("foo", dialect="postgresql"), select(table_a.c.a).prefix_with("bar"), select(table_a.c.a).suffix_with("bar"), ), lambda: ( select(table_a_2.c.a), select(table_a_2_fs.c.a), select(table_a_2_bs.c.a), ), lambda: ( select(table_a.c.a), select(table_a.c.a).with_hint(None, "some hint"), select(table_a.c.a).with_hint(None, "some other hint"), select(table_a.c.a).with_hint(table_a, "some hint"), select(table_a.c.a) .with_hint(table_a, "some hint") .with_hint(None, "some other hint"), select(table_a.c.a).with_hint(table_a, "some other hint"), select(table_a.c.a).with_hint( table_a, "some hint", dialect_name="mysql" ), select(table_a.c.a).with_hint( table_a, "some hint", dialect_name="postgresql" ), ), lambda: ( table_a.join(table_b, table_a.c.a == table_b.c.a), table_a.join( table_b, and_(table_a.c.a == table_b.c.a, table_a.c.b == 1) ), table_a.outerjoin(table_b, table_a.c.a == table_b.c.a), ), lambda: ( table_a.alias("a"), table_a.alias("b"), table_a.alias(), table_b.alias("a"), select(table_a.c.a).alias("a"), ), lambda: ( FromGrouping(table_a.alias("a")), FromGrouping(table_a.alias("b")), ), lambda: ( SelectStatementGrouping(select(table_a)), SelectStatementGrouping(select(table_b)), ), lambda: ( select(table_a.c.a).scalar_subquery(), select(table_a.c.a).where(table_a.c.b == 5).scalar_subquery(), ), lambda: ( exists().where(table_a.c.a == 5), exists().where(table_a.c.b == 5), ), lambda: ( union(select(table_a.c.a), select(table_a.c.b)), union(select(table_a.c.a), select(table_a.c.b)).order_by("a"), union_all(select(table_a.c.a), select(table_a.c.b)), union(select(table_a.c.a)), union( select(table_a.c.a), select(table_a.c.b).where(table_a.c.b > 5), ), ), lambda: ( table("a", column("x"), column("y")), table("a", column("y"), column("x")), table("b", column("x"), column("y")), table("a", column("x"), column("y"), column("z")), table("a", column("x"), column("y", Integer)), table("a", column("q"), column("y", Integer)), ), lambda: (table_a, table_b), ] type_cache_key_fixtures = [ lambda: ( column("q") == column("x"), column("q") == column("y"), column("z") == column("x"), column("z", String(50)) == column("x", String(50)), column("z", String(50)) == column("x", String(30)), column("z", String(50)) == column("x", Integer), column("z", MyType1()) == column("x", MyType2()), column("z", MyType1()) == column("x", MyType3("x")), column("z", MyType1()) == column("x", MyType3("y")), ) ] dont_compare_values_fixtures = [ lambda: ( # note the in_(...) all have different column names because # otherwise all IN expressions would compare as equivalent column("x").in_(random_choices(range(10), k=3)), column("y").in_( bindparam( "q", # note that a different cache key is created if # the value given to the bindparam is [], as the type # cannot be inferred for the empty list but can # for the non-empty list as of #6222 random_choices(range(10), k=random.randint(1, 7)), expanding=True, ) ), column("y2").in_( bindparam( "q", # for typed param, empty and not empty param will have # the same type random_choices(range(10), k=random.randint(0, 7)), type_=Integer, expanding=True, ) ), # don't include empty for untyped, will create different cache # key column("z").in_(random_choices(range(10), k=random.randint(1, 7))), # empty is fine for typed, will create the same cache key column("z2", Integer).in_( random_choices(range(10), k=random.randint(0, 7)) ), column("x") == random.randint(0, 10), ) ] def _complex_fixtures(): def one(): a1 = table_a.alias() a2 = table_b_like_a.alias() stmt = ( select(table_a.c.a, a1.c.b, a2.c.b) .where(table_a.c.b == a1.c.b) .where(a1.c.b == a2.c.b) .where(a1.c.a == 5) ) return stmt def one_diff(): a1 = table_b_like_a.alias() a2 = table_a.alias() stmt = ( select(table_a.c.a, a1.c.b, a2.c.b) .where(table_a.c.b == a1.c.b) .where(a1.c.b == a2.c.b) .where(a1.c.a == 5) ) return stmt def two(): inner = one().subquery() stmt = select(table_b.c.a, inner.c.a, inner.c.b).select_from( table_b.join(inner, table_b.c.b == inner.c.b) ) return stmt def three(): a1 = table_a.alias() a2 = table_a.alias() ex = exists().where(table_b.c.b == a1.c.a) stmt = ( select(a1.c.a, a2.c.a) .select_from(a1.join(a2, a1.c.b == a2.c.b)) .where(ex) ) return stmt def four(): stmt = select(table_a.c.a).cte(recursive=True) stmt = stmt.union(select(stmt.c.a + 1).where(stmt.c.a < 10)) return stmt def five(): stmt = select(table_a.c.a).cte(recursive=True, nesting=True) stmt = stmt.union(select(stmt.c.a + 1).where(stmt.c.a < 10)) return stmt return [one(), one_diff(), two(), three(), four(), five()] fixtures.append(_complex_fixtures) def _statements_w_context_options_fixtures(): return [ select(table_a)._add_compile_state_func(opt1, True), select(table_a)._add_compile_state_func(opt1, 5), select(table_a) ._add_compile_state_func(opt1, True) ._add_compile_state_func(opt2, True), select(table_a) ._add_compile_state_func(opt1, True) ._add_compile_state_func(opt2, 5), select(table_a)._add_compile_state_func(opt3, True), ] fixtures.append(_statements_w_context_options_fixtures) def _statements_w_anonymous_col_names(): def one(): c = column("q") l = c.label(None) # new case as of Id810f485c5f7ed971529489b84694e02a3356d6d subq = select(l).subquery() # this creates a ColumnClause as a proxy to the Label() that has # an anonymous name, so the column has one too. anon_col = subq.c[0] # then when BindParameter is created, it checks the label # and doesn't double up on the anonymous name which is uncachable return anon_col > 5 def two(): c = column("p") l = c.label(None) # new case as of Id810f485c5f7ed971529489b84694e02a3356d6d subq = select(l).subquery() # this creates a ColumnClause as a proxy to the Label() that has # an anonymous name, so the column has one too. anon_col = subq.c[0] # then when BindParameter is created, it checks the label # and doesn't double up on the anonymous name which is uncachable return anon_col > 5 def three(): l1, l2 = table_a.c.a.label(None), table_a.c.b.label(None) stmt = select(table_a.c.a, table_a.c.b, l1, l2) subq = stmt.subquery() return select(subq).where(subq.c[2] == 10) return ( one(), two(), three(), ) fixtures.append(_statements_w_anonymous_col_names) def _update_dml_w_dicts(): return ( table_b_b.update().values( { table_b_b.c.a: 5, table_b_b.c.b: 5, table_b_b.c.c: 5, table_b_b.c.d: 5, } ), # equivalent, but testing dictionary insert ordering as cache key # / compare table_b_b.update().values( { table_b_b.c.a: 5, table_b_b.c.c: 5, table_b_b.c.b: 5, table_b_b.c.d: 5, } ), table_b_b.update().values( {table_b_b.c.a: 5, table_b_b.c.b: 5, "c": 5, table_b_b.c.d: 5} ), table_b_b.update().values( { table_b_b.c.a: 5, table_b_b.c.b: 5, table_b_b.c.c: 5, table_b_b.c.d: 5, table_b_b.c.e: 10, } ), table_b_b.update() .values( { table_b_b.c.a: 5, table_b_b.c.b: 5, table_b_b.c.c: 5, table_b_b.c.d: 5, table_b_b.c.e: 10, } ) .where(table_b_b.c.c > 10), ) fixtures.append(_update_dml_w_dicts) def _lambda_fixtures(): def one(): return LambdaElement( lambda: table_a.c.a == column("q"), roles.WhereHavingRole ) def two(): r = random.randint(1, 10) q = 408 return LambdaElement( lambda: table_a.c.a + q == r, roles.WhereHavingRole ) some_value = random.randint(20, 30) def three(y): return LambdaElement( lambda: and_(table_a.c.a == some_value, table_a.c.b > y), roles.WhereHavingRole, ) def four(): return LambdaElement( lambda: and_(table_a.c.a == Foo.x), roles.WhereHavingRole ) def five(): return LambdaElement( lambda: and_(table_a.c.a == Foo.x, table_a.c.b == Foo.y), roles.WhereHavingRole, ) def six(): d = {"g": random.randint(40, 45)} return LambdaElement( lambda: and_(table_a.c.b == d["g"]), roles.WhereHavingRole, opts=LambdaOptions(track_closure_variables=False), ) def seven(): # lambda statements don't collect bindparameter objects # for fixed values, has to be in a variable value = random.randint(10, 20) return lambda_stmt(lambda: select(table_a)) + ( lambda s: s.where(table_a.c.a == value) ) from sqlalchemy.sql import lambdas def eight(): q = 5 return lambdas.DeferredLambdaElement( lambda t: t.c.a > q, roles.WhereHavingRole, lambda_args=(table_a,), ) return [ one(), two(), three(random.randint(5, 10)), four(), five(), six(), seven(), eight(), ] dont_compare_values_fixtures.append(_lambda_fixtures) def _numeric_agnostic_window_functions(): return ( func.row_number().over( order_by=table_a.c.a, range_=(random.randint(50, 60), random.randint(60, 70)), ), func.row_number().over( order_by=table_a.c.a, range_=(random.randint(-40, -20), random.randint(60, 70)), ), func.row_number().over( order_by=table_a.c.a, rows=(random.randint(-40, -20), random.randint(60, 70)), ), func.row_number().over( order_by=table_a.c.a, range_=(None, random.randint(60, 70)), ), func.row_number().over( order_by=table_a.c.a, range_=(random.randint(50, 60), None), ), func.row_number().over( order_by=table_a.c.a, groups=(random.randint(50, 60), random.randint(60, 70)), ), func.row_number().over( order_by=table_a.c.a, groups=(random.randint(-40, -20), random.randint(60, 70)), ), ) dont_compare_values_fixtures.append(_numeric_agnostic_window_functions) # like fixture but returns at least two objects that compare equally equal_fixtures = [ lambda: ( select(table_a.c.a).fetch(3), select(table_a.c.a).fetch(2).fetch(3), select(table_a.c.a).fetch(3, percent=False, with_ties=False), select(table_a.c.a).limit(2).fetch(3), select(table_a.c.a).slice(2, 4).fetch(3).offset(None), ), lambda: ( select(table_a.c.a).limit(3), select(table_a.c.a).fetch(2).limit(3), select(table_a.c.a).fetch(2).slice(0, 3).offset(None), ), ]
CoreFixtures
python
pypa__pip
src/pip/_internal/index/sources.py
{ "start": 5199, "end": 6039 }
class ____(LinkSource): """``--find-links=<url>`` or ``--[extra-]index-url=<url>``. This returns: * ``page_candidates``: Links listed on an HTML file. * ``file_candidates``: The non-HTML file. """ def __init__( self, candidates_from_page: CandidatesFromPage, page_validator: PageValidator, link: Link, ) -> None: self._candidates_from_page = candidates_from_page self._page_validator = page_validator self._link = link @property def link(self) -> Link | None: return self._link def page_candidates(self) -> FoundCandidates: if not self._page_validator(self._link): return yield from self._candidates_from_page(self._link) def file_links(self) -> FoundLinks: yield self._link
_RemoteFileSource
python
huggingface__transformers
src/transformers/models/byt5/tokenization_byt5.py
{ "start": 841, "end": 10047 }
class ____(PreTrainedTokenizer): """ Construct a ByT5 tokenizer. ByT5 simply uses raw bytes utf-8 encoding. This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. Args: eos_token (`str`, *optional*, defaults to `"</s>"`): The end of sequence token. <Tip> When building a sequence using special tokens, this is not the token that is used for the end of sequence. The token used is the `sep_token`. </Tip> unk_token (`str`, *optional*, defaults to `"<unk>"`): The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. pad_token (`str`, *optional*, defaults to `"<pad>"`): The token used for padding, for example when batching sequences of different lengths. extra_ids (`int`, *optional*, defaults to 125): Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are indexed from the end of the vocabulary up to beginning ("<extra_id_0>" is the last token in the vocabulary like in ByT5 preprocessing see [here](https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117)). additional_special_tokens (`list[str]`, *optional*): Additional special tokens used by the tokenizer. """ model_input_names = ["input_ids", "attention_mask"] def __init__( self, eos_token="</s>", unk_token="<unk>", pad_token="<pad>", extra_ids=125, additional_special_tokens=None, **kwargs, ) -> None: # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)] elif extra_ids > 0 and additional_special_tokens is not None and len(additional_special_tokens) > 0: # Check that we have the right number of extra_id special tokens extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens))) if extra_tokens != extra_ids: raise ValueError( f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are" " provided to ByT5Tokenizer. In this case the additional_special_tokens must include the" " extra_ids tokens" ) pad_token = AddedToken(pad_token, lstrip=True, rstrip=True) if isinstance(pad_token, str) else pad_token # we force left and right stripping for backward compatibility. The byt5tests depend on this. eos_token = AddedToken(eos_token, lstrip=True, rstrip=True) if isinstance(eos_token, str) else eos_token unk_token = AddedToken(unk_token, lstrip=True, rstrip=True) if isinstance(unk_token, str) else unk_token # unk token needs to be in the vocab with correct index self._added_tokens_decoder = {0: pad_token, 1: eos_token, 2: unk_token} self.offset = len(self._added_tokens_decoder) self._utf_vocab_size = 2**8 # utf is 8 bits super().__init__( eos_token=eos_token, unk_token=unk_token, pad_token=pad_token, extra_ids=0, additional_special_tokens=additional_special_tokens, # TODO extra ids are not used :sweatywmile: **kwargs, ) @property def vocab_size(self): return self._utf_vocab_size def get_vocab(self): vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.offset)} vocab.update(self.added_tokens_encoder) return vocab def get_special_tokens_mask( self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False ) -> list[int]: """ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer `prepare_for_model` method. Args: token_ids_0 (`list[int]`): List of IDs. token_ids_1 (`list[int]`, *optional*): Optional second list of IDs for sequence pairs. already_has_special_tokens (`bool`, *optional*, defaults to `False`): Whether or not the token list is already formatted with special tokens for the model. Returns: `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token. """ if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True ) # normal case: some special tokens if token_ids_1 is None: return ([0] * len(token_ids_0)) + [1] return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1] def _add_eos_if_not_present(self, token_ids: list[int]) -> list[int]: """Do not add eos again if user already added it.""" if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated" " eos tokens being added." ) return token_ids else: return token_ids + [self.eos_token_id] def create_token_type_ids_from_sequences( self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None ) -> list[int]: """ Create a mask from the two sequences passed to be used in a sequence-pair classification task. ByT5 does not make use of token type ids, therefore a list of zeros is returned. Args: token_ids_0 (`list[int]`): List of IDs. token_ids_1 (`list[int]`, *optional*): Optional second list of IDs for sequence pairs. Returns: `list[int]`: List of zeros. """ eos = [self.eos_token_id] if token_ids_1 is None: return len(token_ids_0 + eos) * [0] return len(token_ids_0 + eos + token_ids_1 + eos) * [0] def build_inputs_with_special_tokens( self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None ) -> list[int]: """ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A sequence has the following format: - single sequence: `X </s>` - pair of sequences: `A </s> B </s>` Args: token_ids_0 (`list[int]`): List of IDs to which the special tokens will be added. token_ids_1 (`list[int]`, *optional*): Optional second list of IDs for sequence pairs. Returns: `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens. """ token_ids_0 = self._add_eos_if_not_present(token_ids_0) if token_ids_1 is None: return token_ids_0 else: token_ids_1 = self._add_eos_if_not_present(token_ids_1) return token_ids_0 + token_ids_1 def _tokenize(self, text: str) -> list[str]: """Take as input a string and return a list of strings (tokens) for words/sub-words""" tokens = [chr(i) for i in text.encode("utf-8")] return tokens def _convert_token_to_id(self, token): """Converts a token (str) in an id using the vocab.""" if len(token) != 1: token_id = None else: token_id = ord(token) + self.offset return token_id def _convert_id_to_token(self, index): """Converts an index (integer) in a token (str) using the vocab.""" token = chr(index - self.offset) return token def convert_tokens_to_string(self, tokens): """Converts a sequence of tokens (string) in a single string.""" bstring = b"" for token in tokens: if token in self.added_tokens_decoder: tok_string = self.added_tokens_decoder[token].encode("utf-8") elif token in self.added_tokens_encoder: tok_string = token.encode("utf-8") else: tok_string = bytes([ord(token)]) bstring += tok_string string = bstring.decode("utf-8", errors="ignore") return string # ByT5Tokenizer has no vocab file def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]: return () __all__ = ["ByT5Tokenizer"]
ByT5Tokenizer
python
huggingface__transformers
src/transformers/models/aria/configuration_aria.py
{ "start": 1360, "end": 9676 }
class ____(PreTrainedConfig): r""" This class handles the configuration for the text component of the Aria model. Instantiating a configuration with the defaults will yield a similar configuration to that of the model of the Aria [rhymes-ai/Aria](https://huggingface.co/rhymes-ai/Aria) architecture. This class extends the LlamaConfig to include additional parameters specific to the Mixture of Experts (MoE) architecture. Args: vocab_size (`int`, *optional*, defaults to 32000): Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`LlamaModel`] hidden_size (`int`, *optional*, defaults to 4096): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 4096): The size of the MLP representations. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer decoder. num_attention_heads (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer in the Transformer decoder. num_key_value_heads (`int`, *optional*): This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details, check out [this paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `num_attention_heads`. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. max_position_embeddings (`int`, *optional*, defaults to 2048): The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens, Llama 2 up to 4096, CodeLlama up to 16384. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. rms_norm_eps (`float`, *optional*, defaults to 1e-06): The epsilon used by the rms normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. pad_token_id (`int`, *optional*, defaults to 2): Padding token id. bos_token_id (`int`, *optional*, defaults to 1): Beginning of stream token id. eos_token_id (`int`, *optional*, defaults to 2): End of stream token id. pretraining_tp (`int`, *optional*, defaults to 1): Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to understand more about it. This value is necessary to ensure exact reproducibility of the pretraining results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232). tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether to tie weight embeddings rope_parameters (`RopeParameters`, *optional*): Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE with longer `max_position_embeddings`. attention_bias (`bool`, *optional*, defaults to `False`): Whether to use a bias in the query, key, value and output projection layers during self-attention. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. mlp_bias (`bool`, *optional*, defaults to `False`): Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers. head_dim (`int`, *optional*): The attention head dimension. If None, it will default to hidden_size // num_heads moe_num_experts (`int`, *optional*, defaults to 8): The number of experts in the MoE layer. moe_topk (`int`, *optional*, defaults to 2): The number of top experts to route to for each token. moe_num_shared_experts (`int`, *optional*, defaults to 2): The number of shared experts. """ model_type = "aria_text" keys_to_ignore_at_inference = ["past_key_values"] base_model_tp_plan = { "layers.*.self_attn.q_proj": "colwise", "layers.*.self_attn.k_proj": "colwise", "layers.*.self_attn.v_proj": "colwise", "layers.*.self_attn.o_proj": "rowwise", "layers.*.mlp.shared_experts.gate_proj": "colwise", "layers.*.mlp.shared_experts.up_proj": "colwise", "layers.*.mlp.shared_experts.down_proj": "rowwise", } base_model_pp_plan = { "embed_tokens": (["input_ids"], ["inputs_embeds"]), "layers": (["hidden_states", "attention_mask"], ["hidden_states"]), "norm": (["hidden_states"], ["hidden_states"]), } base_config_key = "text_config" def __init__( self, vocab_size: Optional[int] = 32000, hidden_size: Optional[int] = 4096, intermediate_size: int = 4096, num_hidden_layers: Optional[int] = 32, num_attention_heads: Optional[int] = 32, num_key_value_heads: Optional[int] = None, hidden_act: Optional[str] = "silu", max_position_embeddings: Optional[int] = 2048, initializer_range: Optional[float] = 0.02, rms_norm_eps: Optional[int] = 1e-6, use_cache: Optional[bool] = True, pad_token_id=2, bos_token_id: Optional[int] = 1, eos_token_id: Optional[int] = 2, pretraining_tp: Optional[int] = 1, tie_word_embeddings: Optional[bool] = False, rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None, attention_bias: Optional[bool] = False, attention_dropout: Optional[float] = 0.0, mlp_bias: Optional[bool] = False, head_dim: Optional[int] = None, moe_num_experts: int = 8, moe_topk: int = 2, moe_num_shared_experts: int = 2, **kwargs, ): self.intermediate_size = intermediate_size self.moe_num_experts = moe_num_experts self.moe_topk = moe_topk self.moe_num_shared_experts = moe_num_shared_experts self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads # for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.pretraining_tp = pretraining_tp self.use_cache = use_cache self.attention_bias = attention_bias self.attention_dropout = attention_dropout self.mlp_bias = mlp_bias self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads self.rope_parameters = rope_parameters super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, )
AriaTextConfig
python
sympy__sympy
sympy/core/mul.py
{ "start": 2345, "end": 79476 }
class ____(Expr, AssocOp): """ Expression representing multiplication operation for algebraic field. .. deprecated:: 1.7 Using arguments that aren't subclasses of :class:`~.Expr` in core operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is deprecated. See :ref:`non-expr-args-deprecated` for details. Every argument of ``Mul()`` must be ``Expr``. Infix operator ``*`` on most scalar objects in SymPy calls this class. Another use of ``Mul()`` is to represent the structure of abstract multiplication so that its arguments can be substituted to return different class. Refer to examples section for this. ``Mul()`` evaluates the argument unless ``evaluate=False`` is passed. The evaluation logic includes: 1. Flattening ``Mul(x, Mul(y, z))`` -> ``Mul(x, y, z)`` 2. Identity removing ``Mul(x, 1, y)`` -> ``Mul(x, y)`` 3. Exponent collecting by ``.as_base_exp()`` ``Mul(x, x**2)`` -> ``Pow(x, 3)`` 4. Term sorting ``Mul(y, x, 2)`` -> ``Mul(2, x, y)`` Since multiplication can be vector space operation, arguments may have the different :obj:`sympy.core.kind.Kind()`. Kind of the resulting object is automatically inferred. Examples ======== >>> from sympy import Mul >>> from sympy.abc import x, y >>> Mul(x, 1) x >>> Mul(x, x) x**2 If ``evaluate=False`` is passed, result is not evaluated. >>> Mul(1, 2, evaluate=False) 1*2 >>> Mul(x, x, evaluate=False) x*x ``Mul()`` also represents the general structure of multiplication operation. >>> from sympy import MatrixSymbol >>> A = MatrixSymbol('A', 2,2) >>> expr = Mul(x,y).subs({y:A}) >>> expr x*A >>> type(expr) <class 'sympy.matrices.expressions.matmul.MatMul'> See Also ======== MatMul """ __slots__ = () is_Mul = True _args_type = Expr _kind_dispatcher = KindDispatcher("Mul_kind_dispatcher", commutative=True) identity: ClassVar[Expr] @property def kind(self): arg_kinds = (a.kind for a in self.args) return self._kind_dispatcher(*arg_kinds) if TYPE_CHECKING: def __new__(cls, *args: Expr | complex, evaluate: bool=True) -> Expr: # type: ignore ... @property def args(self) -> tuple[Expr, ...]: ... def could_extract_minus_sign(self): if self == (-self): return False # e.g. zoo*x == -zoo*x c = self.args[0] return c.is_Number and c.is_extended_negative def __neg__(self): c, args = self.as_coeff_mul() if args[0] is not S.ComplexInfinity: c = -c if c is not S.One: if args[0].is_Number: args = list(args) if c is S.NegativeOne: args[0] = -args[0] else: args[0] *= c else: args = (c,) + args return self._from_args(args, self.is_commutative) @classmethod def flatten(cls, seq): """Return commutative, noncommutative and order arguments by combining related terms. Notes ===== * In an expression like ``a*b*c``, Python process this through SymPy as ``Mul(Mul(a, b), c)``. This can have undesirable consequences. - Sometimes terms are not combined as one would like: {c.f. https://github.com/sympy/sympy/issues/4596} >>> from sympy import Mul, sqrt >>> from sympy.abc import x, y, z >>> 2*(x + 1) # this is the 2-arg Mul behavior 2*x + 2 >>> y*(x + 1)*2 2*y*(x + 1) >>> 2*(x + 1)*y # 2-arg result will be obtained first y*(2*x + 2) >>> Mul(2, x + 1, y) # all 3 args simultaneously processed 2*y*(x + 1) >>> 2*((x + 1)*y) # parentheses can control this behavior 2*y*(x + 1) Powers with compound bases may not find a single base to combine with unless all arguments are processed at once. Post-processing may be necessary in such cases. {c.f. https://github.com/sympy/sympy/issues/5728} >>> a = sqrt(x*sqrt(y)) >>> a**3 (x*sqrt(y))**(3/2) >>> Mul(a,a,a) (x*sqrt(y))**(3/2) >>> a*a*a x*sqrt(y)*sqrt(x*sqrt(y)) >>> _.subs(a.base, z).subs(z, a.base) (x*sqrt(y))**(3/2) - If more than two terms are being multiplied then all the previous terms will be re-processed for each new argument. So if each of ``a``, ``b`` and ``c`` were :class:`Mul` expression, then ``a*b*c`` (or building up the product with ``*=``) will process all the arguments of ``a`` and ``b`` twice: once when ``a*b`` is computed and again when ``c`` is multiplied. Using ``Mul(a, b, c)`` will process all arguments once. * The results of Mul are cached according to arguments, so flatten will only be called once for ``Mul(a, b, c)``. If you can structure a calculation so the arguments are most likely to be repeats then this can save time in computing the answer. For example, say you had a Mul, M, that you wished to divide by ``d[i]`` and multiply by ``n[i]`` and you suspect there are many repeats in ``n``. It would be better to compute ``M*n[i]/d[i]`` rather than ``M/d[i]*n[i]`` since every time n[i] is a repeat, the product, ``M*n[i]`` will be returned without flattening -- the cached value will be returned. If you divide by the ``d[i]`` first (and those are more unique than the ``n[i]``) then that will create a new Mul, ``M/d[i]`` the args of which will be traversed again when it is multiplied by ``n[i]``. {c.f. https://github.com/sympy/sympy/issues/5706} This consideration is moot if the cache is turned off. NB -- The validity of the above notes depends on the implementation details of Mul and flatten which may change at any time. Therefore, you should only consider them when your code is highly performance sensitive. Removal of 1 from the sequence is already handled by AssocOp.__new__. """ from sympy.calculus.accumulationbounds import AccumBounds from sympy.matrices.expressions import MatrixExpr rv = None if len(seq) == 2: a, b = seq if b.is_Rational: a, b = b, a seq = [a, b] assert a is not S.One if a.is_Rational and not a.is_zero: r, b = b.as_coeff_Mul() if b.is_Add: if r is not S.One: # 2-arg hack # leave the Mul as a Mul? ar = a*r if ar is S.One: arb = b else: arb = cls(a*r, b, evaluate=False) rv = [arb], [], None elif global_parameters.distribute and b.is_commutative: newb = Add(*[_keep_coeff(a, bi) for bi in b.args]) rv = [newb], [], None if rv: return rv # apply associativity, separate commutative part of seq c_part = [] # out: commutative factors nc_part = [] # out: non-commutative factors nc_seq = [] coeff = S.One # standalone term # e.g. 3 * ... c_powers = [] # (base,exp) n # e.g. (x,n) for x num_exp = [] # (num-base, exp) y # e.g. (3, y) for ... * 3 * ... neg1e = S.Zero # exponent on -1 extracted from Number-based Pow and I pnum_rat = {} # (num-base, Rat-exp) 1/2 # e.g. (3, 1/2) for ... * 3 * ... order_symbols = None # --- PART 1 --- # # "collect powers and coeff": # # o coeff # o c_powers # o num_exp # o neg1e # o pnum_rat # # NOTE: this is optimized for all-objects-are-commutative case for o in seq: # O(x) if o.is_Order: o, order_symbols = o.as_expr_variables(order_symbols) # Mul([...]) if o.is_Mul: if o.is_commutative: seq.extend(o.args) # XXX zerocopy? else: # NCMul can have commutative parts as well for q in o.args: if q.is_commutative: seq.append(q) else: nc_seq.append(q) # append non-commutative marker, so we don't forget to # process scheduled non-commutative objects seq.append(NC_Marker) continue # 3 elif o.is_Number: if o is S.NaN or coeff is S.ComplexInfinity and o.is_zero: # we know for sure the result will be nan return [S.NaN], [], None elif coeff.is_Number or isinstance(coeff, AccumBounds): # it could be zoo coeff *= o if coeff is S.NaN: # we know for sure the result will be nan return [S.NaN], [], None continue elif isinstance(o, AccumBounds): coeff = o.__mul__(coeff) continue elif o is S.ComplexInfinity: if not coeff: # 0 * zoo = NaN return [S.NaN], [], None coeff = S.ComplexInfinity continue elif not coeff and isinstance(o, Add) and any( _ in (S.NegativeInfinity, S.ComplexInfinity, S.Infinity) for __ in o.args for _ in Mul.make_args(__)): # e.g 0 * (x + oo) = NaN but not # 0 * (1 + Integral(x, (x, 0, oo))) which is # treated like 0 * x -> 0 return [S.NaN], [], None elif o is S.ImaginaryUnit: neg1e += S.Half continue elif o.is_commutative: # e # o = b b, e = o.as_base_exp() # y # 3 if o.is_Pow: if b.is_Number: # get all the factors with numeric base so they can be # combined below, but don't combine negatives unless # the exponent is an integer if e.is_Rational: if e.is_Integer: coeff *= Pow(b, e) # it is an unevaluated power continue elif e.is_negative: # also a sign of an unevaluated power seq.append(Pow(b, e)) continue elif b.is_negative: neg1e += e b = -b if b is not S.One: pnum_rat.setdefault(b, []).append(e) continue elif b.is_positive or e.is_integer: num_exp.append((b, e)) continue c_powers.append((b, e)) # NON-COMMUTATIVE # TODO: Make non-commutative exponents not combine automatically else: if o is not NC_Marker: nc_seq.append(o) # process nc_seq (if any) while nc_seq: o = nc_seq.pop(0) if not nc_part: nc_part.append(o) continue # b c b+c # try to combine last terms: a * a -> a o1 = nc_part.pop() b1, e1 = o1.as_base_exp() b2, e2 = o.as_base_exp() new_exp = e1 + e2 # Only allow powers to combine if the new exponent is # not an Add. This allow things like a**2*b**3 == a**5 # if a.is_commutative == False, but prohibits # a**x*a**y and x**a*x**b from combining (x,y commute). if b1 == b2 and (not new_exp.is_Add): o12 = b1 ** new_exp # now o12 could be a commutative object if o12.is_commutative: seq.append(o12) continue else: nc_seq.insert(0, o12) else: nc_part.extend([o1, o]) # We do want a combined exponent if it would not be an Add, such as # y 2y 3y # x * x -> x # We determine if two exponents have the same term by using # as_coeff_Mul. # # Unfortunately, this isn't smart enough to consider combining into # exponents that might already be adds, so things like: # z - y y # x * x will be left alone. This is because checking every possible # combination can slow things down. # gather exponents of common bases... def _gather(c_powers): common_b = {} # b:e for b, e in c_powers: co = e.as_coeff_Mul() common_b.setdefault(b, {}).setdefault( co[1], []).append(co[0]) for b, d in common_b.items(): for di, li in d.items(): d[di] = Add(*li) new_c_powers = [] for b, e in common_b.items(): new_c_powers.extend([(b, c*t) for t, c in e.items()]) return new_c_powers # in c_powers c_powers = _gather(c_powers) # and in num_exp num_exp = _gather(num_exp) # --- PART 2 --- # # o process collected powers (x**0 -> 1; x**1 -> x; otherwise Pow) # o combine collected powers (2**x * 3**x -> 6**x) # with numeric base # ................................ # now we have: # - coeff: # - c_powers: (b, e) # - num_exp: (2, e) # - pnum_rat: {(1/3, [1/3, 2/3, 1/4])} # 0 1 # x -> 1 x -> x # this should only need to run twice; if it fails because # it needs to be run more times, perhaps this should be # changed to a "while True" loop -- the only reason it # isn't such now is to allow a less-than-perfect result to # be obtained rather than raising an error or entering an # infinite loop for i in range(2): new_c_powers = [] changed = False for b, e in c_powers: if e.is_zero: # canceling out infinities yields NaN if (b.is_Add or b.is_Mul) and any(infty in b.args for infty in (S.ComplexInfinity, S.Infinity, S.NegativeInfinity)): return [S.NaN], [], None continue if e is S.One: if b.is_Number: coeff *= b continue p = b if e is not S.One: p = Pow(b, e) # check to make sure that the base doesn't change # after exponentiation; to allow for unevaluated # Pow, we only do so if b is not already a Pow if p.is_Pow and not b.is_Pow: bi = b b, e = p.as_base_exp() if b != bi: changed = True c_part.append(p) new_c_powers.append((b, e)) # there might have been a change, but unless the base # matches some other base, there is nothing to do if changed and len({ b for b, e in new_c_powers}) != len(new_c_powers): # start over again c_part = [] c_powers = _gather(new_c_powers) else: break # x x x # 2 * 3 -> 6 inv_exp_dict = {} # exp:Mul(num-bases) x x # e.g. x:6 for ... * 2 * 3 * ... for b, e in num_exp: inv_exp_dict.setdefault(e, []).append(b) for e, b in inv_exp_dict.items(): inv_exp_dict[e] = cls(*b) c_part.extend([Pow(b, e) for e, b in inv_exp_dict.items() if e]) # b, e -> e' = sum(e), b # {(1/5, [1/3]), (1/2, [1/12, 1/4]} -> {(1/3, [1/5, 1/2])} comb_e = {} for b, e in pnum_rat.items(): comb_e.setdefault(Add(*e), []).append(b) del pnum_rat # process them, reducing exponents to values less than 1 # and updating coeff if necessary else adding them to # num_rat for further processing num_rat = [] for e, b in comb_e.items(): b = cls(*b) if e.q == 1: coeff *= Pow(b, e) continue if e.p > e.q: e_i, ep = divmod(e.p, e.q) coeff *= Pow(b, e_i) e = Rational(ep, e.q) num_rat.append((b, e)) del comb_e # extract gcd of bases in num_rat # 2**(1/3)*6**(1/4) -> 2**(1/3+1/4)*3**(1/4) pnew = defaultdict(list) i = 0 # steps through num_rat which may grow while i < len(num_rat): bi, ei = num_rat[i] if bi == 1: i += 1 continue grow = [] for j in range(i + 1, len(num_rat)): bj, ej = num_rat[j] g = bi.gcd(bj) if g is not S.One: # 4**r1*6**r2 -> 2**(r1+r2) * 2**r1 * 3**r2 # this might have a gcd with something else e = ei + ej if e.q == 1: coeff *= Pow(g, e) else: if e.p > e.q: e_i, ep = divmod(e.p, e.q) # change e in place coeff *= Pow(g, e_i) e = Rational(ep, e.q) grow.append((g, e)) # update the jth item num_rat[j] = (bj/g, ej) # update bi that we are checking with bi = bi/g if bi is S.One: break if bi is not S.One: obj = Pow(bi, ei) if obj.is_Number: coeff *= obj else: # changes like sqrt(12) -> 2*sqrt(3) for obj in Mul.make_args(obj): if obj.is_Number: coeff *= obj else: assert obj.is_Pow bi, ei = obj.args pnew[ei].append(bi) num_rat.extend(grow) i += 1 # combine bases of the new powers for e, b in pnew.items(): pnew[e] = cls(*b) # handle -1 and I if neg1e: # treat I as (-1)**(1/2) and compute -1's total exponent p, q = neg1e.as_numer_denom() # if the integer part is odd, extract -1 n, p = divmod(p, q) if n % 2: coeff = -coeff # if it's a multiple of 1/2 extract I if q == 2: c_part.append(S.ImaginaryUnit) elif p: # see if there is any positive base this power of # -1 can join neg1e = Rational(p, q) for e, b in pnew.items(): if e == neg1e and b.is_positive: pnew[e] = -b break else: # keep it separate; we've already evaluated it as # much as possible so evaluate=False c_part.append(Pow(S.NegativeOne, neg1e, evaluate=False)) # add all the pnew powers c_part.extend([Pow(b, e) for e, b in pnew.items()]) # oo, -oo if coeff in (S.Infinity, S.NegativeInfinity): def _handle_for_oo(c_part, coeff_sign): new_c_part = [] for t in c_part: if t.is_extended_positive: continue if t.is_extended_negative: coeff_sign *= -1 continue new_c_part.append(t) return new_c_part, coeff_sign c_part, coeff_sign = _handle_for_oo(c_part, 1) nc_part, coeff_sign = _handle_for_oo(nc_part, coeff_sign) coeff *= coeff_sign # zoo if coeff is S.ComplexInfinity: # zoo might be # infinite_real + bounded_im # bounded_real + infinite_im # infinite_real + infinite_im # and non-zero real or imaginary will not change that status. c_part = [c for c in c_part if not (fuzzy_not(c.is_zero) and c.is_extended_real is not None)] nc_part = [c for c in nc_part if not (fuzzy_not(c.is_zero) and c.is_extended_real is not None)] # 0 elif coeff.is_zero: # we know for sure the result will be 0 except the multiplicand # is infinity or a matrix if any(isinstance(c, MatrixExpr) for c in nc_part): return [coeff], nc_part, order_symbols if any(c.is_finite == False for c in c_part): return [S.NaN], [], order_symbols return [coeff], [], order_symbols # check for straggling Numbers that were produced _new = [] for i in c_part: if i.is_Number: coeff *= i else: _new.append(i) c_part = _new # order commutative part canonically _mulsort(c_part) # current code expects coeff to be always in slot-0 if coeff is not S.One: c_part.insert(0, coeff) # we are done if (global_parameters.distribute and not nc_part and len(c_part) == 2 and c_part[0].is_Number and c_part[0].is_finite and c_part[1].is_Add): # 2*(1+a) -> 2 + 2 * a coeff = c_part[0] c_part = [Add(*[coeff*f for f in c_part[1].args])] return c_part, nc_part, order_symbols def _eval_power(self, expt): # don't break up NC terms: (A*B)**3 != A**3*B**3, it is A*B*A*B*A*B cargs, nc = self.args_cnc(split_1=False) if expt.is_Integer: return Mul(*[Pow(b, expt, evaluate=False) for b in cargs]) * \ Pow(Mul._from_args(nc), expt, evaluate=False) if expt.is_Rational and expt.q == 2: if self.is_imaginary: a = self.as_real_imag()[1] if a.is_Rational: n, d = abs(a/2).as_numer_denom() n, t = integer_nthroot(n, 2) if t: d, t = integer_nthroot(d, 2) if t: from sympy.functions.elementary.complexes import sign r = sympify(n)/d return _unevaluated_Mul(r**expt.p, (1 + sign(a)*S.ImaginaryUnit)**expt.p) p = Pow(self, expt, evaluate=False) if expt.is_Rational or expt.is_Float: return p._eval_expand_power_base() return p @classmethod def class_key(cls): return 3, 0, cls.__name__ def _eval_evalf(self, prec): c, m = self.as_coeff_Mul() if c is S.NegativeOne: if m.is_Mul: rv = -AssocOp._eval_evalf(m, prec) else: mnew = m._eval_evalf(prec) if mnew is not None: m = mnew rv = -m else: rv = AssocOp._eval_evalf(self, prec) if rv.is_number: return rv.expand() return rv @property def _mpc_(self): """ Convert self to an mpmath mpc if possible """ from .numbers import Float im_part, imag_unit = self.as_coeff_Mul() if imag_unit is not S.ImaginaryUnit: # ValueError may seem more reasonable but since it's a @property, # we need to use AttributeError to keep from confusing things like # hasattr. raise AttributeError("Cannot convert Mul to mpc. Must be of the form Number*I") return (Float(0)._mpf_, Float(im_part)._mpf_) @cacheit def as_two_terms(self): """Return head and tail of self. This is the most efficient way to get the head and tail of an expression. - if you want only the head, use self.args[0]; - if you want to process the arguments of the tail then use self.as_coef_mul() which gives the head and a tuple containing the arguments of the tail when treated as a Mul. - if you want the coefficient when self is treated as an Add then use self.as_coeff_add()[0] Examples ======== >>> from sympy.abc import x, y >>> (3*x*y).as_two_terms() (3, x*y) """ args = self.args if len(args) == 1: return S.One, self elif len(args) == 2: return args else: return args[0], self._new_rawargs(*args[1:]) @cacheit def as_coeff_mul(self, *deps, rational=True, **kwargs): if deps: l1, l2 = sift(self.args, lambda x: x.has(*deps), binary=True) return self._new_rawargs(*l2), tuple(l1) args = self.args if args[0].is_Number: if not rational or args[0].is_Rational: return args[0], args[1:] elif args[0].is_extended_negative: return S.NegativeOne, (-args[0],) + args[1:] return S.One, args @overload def as_coeff_Mul(self, rational: Literal[True]) -> tuple['Rational', Expr]: ... @overload def as_coeff_Mul(self, rational: bool = False) -> tuple['Number', Expr]: ... def as_coeff_Mul(self, rational=False) -> tuple['Number', Expr]: """ Efficiently extract the coefficient of a product. """ coeff, args = self.args[0], self.args[1:] if coeff.is_Number: if not rational or coeff.is_Rational: if len(args) == 1: return coeff, args[0] # type: ignore else: return coeff, self._new_rawargs(*args) # type: ignore elif coeff.is_extended_negative: return S.NegativeOne, self._new_rawargs(*((-coeff,) + args)) return S.One, self def as_real_imag(self, deep=True, **hints): from sympy.functions.elementary.complexes import Abs, im, re other = [] coeffr = [] coeffi = [] addterms = S.One for a in self.args: r, i = a.as_real_imag() if i.is_zero: coeffr.append(r) elif r.is_zero: coeffi.append(i*S.ImaginaryUnit) elif a.is_commutative: aconj = a.conjugate() if other else None # search for complex conjugate pairs: for i, x in enumerate(other): if x == aconj: coeffr.append(Abs(x)**2) del other[i] break else: if a.is_Add: addterms *= a else: other.append(a) else: other.append(a) m = self.func(*other) if hints.get('ignore') == m: return if len(coeffi) % 2: imco = im(coeffi.pop(0)) # all other pairs make a real factor; they will be # put into reco below else: imco = S.Zero reco = self.func(*(coeffr + coeffi)) r, i = (reco*re(m), reco*im(m)) if addterms == 1: if m == 1: if imco.is_zero: return (reco, S.Zero) else: return (S.Zero, reco*imco) if imco is S.Zero: return (r, i) return (-imco*i, imco*r) from .function import expand_mul addre, addim = expand_mul(addterms, deep=False).as_real_imag() if imco is S.Zero: return (r*addre - i*addim, i*addre + r*addim) else: r, i = -imco*i, imco*r return (r*addre - i*addim, r*addim + i*addre) @staticmethod def _expandsums(sums): """ Helper function for _eval_expand_mul. sums must be a list of instances of Basic. """ L = len(sums) if L == 1: return sums[0].args terms = [] left = Mul._expandsums(sums[:L//2]) right = Mul._expandsums(sums[L//2:]) terms = [Mul(a, b) for a in left for b in right] added = Add(*terms) return Add.make_args(added) # it may have collapsed down to one term def _eval_expand_mul(self, **hints): from sympy.simplify.radsimp import fraction # Handle things like 1/(x*(x + 1)), which are automatically converted # to 1/x*1/(x + 1) expr = self # default matches fraction's default n, d = fraction(expr, hints.get('exact', False)) if d.is_Mul: n, d = [i._eval_expand_mul(**hints) if i.is_Mul else i for i in (n, d)] expr = n/d if not expr.is_Mul: return expr plain, sums, rewrite = [], [], False for factor in expr.args: if factor.is_Add: sums.append(factor) rewrite = True else: if factor.is_commutative: plain.append(factor) else: sums.append(Basic(factor)) # Wrapper if not rewrite: return expr else: plain = self.func(*plain) if sums: deep = hints.get("deep", False) terms = self.func._expandsums(sums) args = [] for term in terms: t = self.func(plain, term) if t.is_Mul and any(a.is_Add for a in t.args) and deep: t = t._eval_expand_mul() args.append(t) return Add(*args) else: return plain @cacheit def _eval_derivative(self, s): args = list(self.args) terms = [] for i in range(len(args)): d = args[i].diff(s) if d: # Note: reduce is used in step of Mul as Mul is unable to # handle subtypes and operation priority: terms.append(reduce(lambda x, y: x*y, (args[:i] + [d] + args[i + 1:]), S.One)) return Add.fromiter(terms) @cacheit def _eval_derivative_n_times(self, s, n): from .function import AppliedUndef from .symbol import Symbol, symbols, Dummy if not isinstance(s, (AppliedUndef, Symbol)): # other types of s may not be well behaved, e.g. # (cos(x)*sin(y)).diff([[x, y, z]]) return super()._eval_derivative_n_times(s, n) from .numbers import Integer args = self.args m = len(args) if isinstance(n, (int, Integer)): # https://en.wikipedia.org/wiki/General_Leibniz_rule#More_than_two_factors terms = [] from sympy.ntheory.multinomial import multinomial_coefficients_iterator for kvals, c in multinomial_coefficients_iterator(m, n): p = Mul(*[arg.diff((s, k)) for k, arg in zip(kvals, args)]) terms.append(c * p) return Add(*terms) from sympy.concrete.summations import Sum from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.miscellaneous import Max kvals = symbols("k1:%i" % m, cls=Dummy) klast = n - sum(kvals) nfact = factorial(n) e, l = (# better to use the multinomial? nfact/prod(map(factorial, kvals))/factorial(klast)*\ Mul(*[args[t].diff((s, kvals[t])) for t in range(m-1)])*\ args[-1].diff((s, Max(0, klast))), [(k, 0, n) for k in kvals]) return Sum(e, *l) def _eval_difference_delta(self, n, step): from sympy.series.limitseq import difference_delta as dd arg0 = self.args[0] rest = Mul(*self.args[1:]) return (arg0.subs(n, n + step) * dd(rest, n, step) + dd(arg0, n, step) * rest) def _matches_simple(self, expr, repl_dict): # handle (w*3).matches('x*5') -> {w: x*5/3} coeff, terms = self.as_coeff_Mul() terms = Mul.make_args(terms) if len(terms) == 1: newexpr = self.__class__._combine_inverse(expr, coeff) return terms[0].matches(newexpr, repl_dict) return def matches(self, expr, repl_dict=None, old=False): expr = sympify(expr) if self.is_commutative and expr.is_commutative: return self._matches_commutative(expr, repl_dict, old) elif self.is_commutative is not expr.is_commutative: return None # Proceed only if both both expressions are non-commutative c1, nc1 = self.args_cnc() c2, nc2 = expr.args_cnc() c1, c2 = [c or [1] for c in [c1, c2]] # TODO: Should these be self.func? comm_mul_self = Mul(*c1) comm_mul_expr = Mul(*c2) repl_dict = comm_mul_self.matches(comm_mul_expr, repl_dict, old) # If the commutative arguments didn't match and aren't equal, then # then the expression as a whole doesn't match if not repl_dict and c1 != c2: return None # Now match the non-commutative arguments, expanding powers to # multiplications nc1 = Mul._matches_expand_pows(nc1) nc2 = Mul._matches_expand_pows(nc2) repl_dict = Mul._matches_noncomm(nc1, nc2, repl_dict) return repl_dict or None @staticmethod def _matches_expand_pows(arg_list): new_args = [] for arg in arg_list: if arg.is_Pow and arg.exp > 0: new_args.extend([arg.base] * arg.exp) else: new_args.append(arg) return new_args @staticmethod def _matches_noncomm(nodes, targets, repl_dict=None): """Non-commutative multiplication matcher. `nodes` is a list of symbols within the matcher multiplication expression, while `targets` is a list of arguments in the multiplication expression being matched against. """ if repl_dict is None: repl_dict = {} else: repl_dict = repl_dict.copy() # List of possible future states to be considered agenda = [] # The current matching state, storing index in nodes and targets state = (0, 0) node_ind, target_ind = state # Mapping between wildcard indices and the index ranges they match wildcard_dict = {} while target_ind < len(targets) and node_ind < len(nodes): node = nodes[node_ind] if node.is_Wild: Mul._matches_add_wildcard(wildcard_dict, state) states_matches = Mul._matches_new_states(wildcard_dict, state, nodes, targets) if states_matches: new_states, new_matches = states_matches agenda.extend(new_states) if new_matches: for match in new_matches: repl_dict[match] = new_matches[match] if not agenda: return None else: state = agenda.pop() node_ind, target_ind = state return repl_dict @staticmethod def _matches_add_wildcard(dictionary, state): node_ind, target_ind = state if node_ind in dictionary: begin, end = dictionary[node_ind] dictionary[node_ind] = (begin, target_ind) else: dictionary[node_ind] = (target_ind, target_ind) @staticmethod def _matches_new_states(dictionary, state, nodes, targets): node_ind, target_ind = state node = nodes[node_ind] target = targets[target_ind] # Don't advance at all if we've exhausted the targets but not the nodes if target_ind >= len(targets) - 1 and node_ind < len(nodes) - 1: return None if node.is_Wild: match_attempt = Mul._matches_match_wilds(dictionary, node_ind, nodes, targets) if match_attempt: # If the same node has been matched before, don't return # anything if the current match is diverging from the previous # match other_node_inds = Mul._matches_get_other_nodes(dictionary, nodes, node_ind) for ind in other_node_inds: other_begin, other_end = dictionary[ind] curr_begin, curr_end = dictionary[node_ind] other_targets = targets[other_begin:other_end + 1] current_targets = targets[curr_begin:curr_end + 1] for curr, other in zip(current_targets, other_targets): if curr != other: return None # A wildcard node can match more than one target, so only the # target index is advanced new_state = [(node_ind, target_ind + 1)] # Only move on to the next node if there is one if node_ind < len(nodes) - 1: new_state.append((node_ind + 1, target_ind + 1)) return new_state, match_attempt else: # If we're not at a wildcard, then make sure we haven't exhausted # nodes but not targets, since in this case one node can only match # one target if node_ind >= len(nodes) - 1 and target_ind < len(targets) - 1: return None match_attempt = node.matches(target) if match_attempt: return [(node_ind + 1, target_ind + 1)], match_attempt elif node == target: return [(node_ind + 1, target_ind + 1)], None else: return None @staticmethod def _matches_match_wilds(dictionary, wildcard_ind, nodes, targets): """Determine matches of a wildcard with sub-expression in `target`.""" wildcard = nodes[wildcard_ind] begin, end = dictionary[wildcard_ind] terms = targets[begin:end + 1] # TODO: Should this be self.func? mult = Mul(*terms) if len(terms) > 1 else terms[0] return wildcard.matches(mult) @staticmethod def _matches_get_other_nodes(dictionary, nodes, node_ind): """Find other wildcards that may have already been matched.""" ind_node = nodes[node_ind] return [ind for ind in dictionary if nodes[ind] == ind_node] @staticmethod def _combine_inverse(lhs, rhs): """ Returns lhs/rhs, but treats arguments like symbols, so things like oo/oo return 1 (instead of a nan) and ``I`` behaves like a symbol instead of sqrt(-1). """ from sympy.simplify.simplify import signsimp from .symbol import Dummy if lhs == rhs: return S.One def check(l, r): if l.is_Float and r.is_comparable: # if both objects are added to 0 they will share the same "normalization" # and are more likely to compare the same. Since Add(foo, 0) will not allow # the 0 to pass, we use __add__ directly. return l.__add__(0) == r.evalf().__add__(0) return False if check(lhs, rhs) or check(rhs, lhs): return S.One if any(i.is_Pow or i.is_Mul for i in (lhs, rhs)): # gruntz and limit wants a literal I to not combine # with a power of -1 d = Dummy('I') _i = {S.ImaginaryUnit: d} i_ = {d: S.ImaginaryUnit} a = lhs.xreplace(_i).as_powers_dict() b = rhs.xreplace(_i).as_powers_dict() blen = len(b) for bi in tuple(b.keys()): if bi in a: a[bi] -= b.pop(bi) if not a[bi]: a.pop(bi) if len(b) != blen: lhs = Mul(*[k**v for k, v in a.items()]).xreplace(i_) rhs = Mul(*[k**v for k, v in b.items()]).xreplace(i_) rv = lhs/rhs srv = signsimp(rv) return srv if srv.is_Number else rv def as_powers_dict(self): d = defaultdict(int) for term in self.args: for b, e in term.as_powers_dict().items(): d[b] += e return d def as_numer_denom(self): # don't use _from_args to rebuild the numerators and denominators # as the order is not guaranteed to be the same once they have # been separated from each other numers, denoms = list(zip(*[f.as_numer_denom() for f in self.args])) return self.func(*numers), self.func(*denoms) def as_base_exp(self): e1 = None bases = [] nc = 0 for m in self.args: b, e = m.as_base_exp() if not b.is_commutative: nc += 1 if e1 is None: e1 = e elif e != e1 or nc > 1 or not e.is_Integer: return self, S.One bases.append(b) return self.func(*bases), e1 def _eval_is_polynomial(self, syms): return all(term._eval_is_polynomial(syms) for term in self.args) def _eval_is_rational_function(self, syms): return all(term._eval_is_rational_function(syms) for term in self.args) def _eval_is_meromorphic(self, x, a): return _fuzzy_group((arg.is_meromorphic(x, a) for arg in self.args), quick_exit=True) def _eval_is_algebraic_expr(self, syms): return all(term._eval_is_algebraic_expr(syms) for term in self.args) _eval_is_commutative = lambda self: _fuzzy_group( a.is_commutative for a in self.args) def _eval_is_complex(self): comp = _fuzzy_group(a.is_complex for a in self.args) if comp is False: if any(a.is_infinite for a in self.args): if any(a.is_zero is not False for a in self.args): return None return False return comp def _eval_is_zero_infinite_helper(self): # # Helper used by _eval_is_zero and _eval_is_infinite. # # Three-valued logic is tricky so let us reason this carefully. It # would be nice to say that we just check is_zero/is_infinite in all # args but we need to be careful about the case that one arg is zero # and another is infinite like Mul(0, oo) or more importantly a case # where it is not known if the arguments are zero or infinite like # Mul(y, 1/x). If either y or x could be zero then there is a # *possibility* that we have Mul(0, oo) which should give None for both # is_zero and is_infinite. # # We keep track of whether we have seen a zero or infinity but we also # need to keep track of whether we have *possibly* seen one which # would be indicated by None. # # For each argument there is the possibility that is_zero might give # True, False or None and likewise that is_infinite might give True, # False or None, giving 9 combinations. The True cases for is_zero and # is_infinite are mutually exclusive though so there are 3 main cases: # # - is_zero = True # - is_infinite = True # - is_zero and is_infinite are both either False or None # # At the end seen_zero and seen_infinite can be any of 9 combinations # of True/False/None. Unless one is False though we cannot return # anything except None: # # - is_zero=True needs seen_zero=True and seen_infinite=False # - is_zero=False needs seen_zero=False # - is_infinite=True needs seen_infinite=True and seen_zero=False # - is_infinite=False needs seen_infinite=False # - anything else gives both is_zero=None and is_infinite=None # # The loop only sets the flags to True or None and never back to False. # Hence as soon as neither flag is False we exit early returning None. # In particular as soon as we encounter a single arg that has # is_zero=is_infinite=None we exit. This is a common case since it is # the default assumptions for a Symbol and also the case for most # expressions containing such a symbol. The early exit gives a big # speedup for something like Mul(*symbols('x:1000')).is_zero. # seen_zero = seen_infinite = False for a in self.args: if a.is_zero: if seen_infinite is not False: return None, None seen_zero = True elif a.is_infinite: if seen_zero is not False: return None, None seen_infinite = True else: if seen_zero is False and a.is_zero is None: if seen_infinite is not False: return None, None seen_zero = None if seen_infinite is False and a.is_infinite is None: if seen_zero is not False: return None, None seen_infinite = None return seen_zero, seen_infinite def _eval_is_zero(self): # True iff any arg is zero and no arg is infinite but need to handle # three valued logic carefully. seen_zero, seen_infinite = self._eval_is_zero_infinite_helper() if seen_zero is False: return False elif seen_zero is True and seen_infinite is False: return True else: return None def _eval_is_infinite(self): # True iff any arg is infinite and no arg is zero but need to handle # three valued logic carefully. seen_zero, seen_infinite = self._eval_is_zero_infinite_helper() if seen_infinite is True and seen_zero is False: return True elif seen_infinite is False: return False else: return None # We do not need to implement _eval_is_finite because the assumptions # system can infer it from finite = not infinite. def _eval_is_rational(self): r = _fuzzy_group((a.is_rational for a in self.args), quick_exit=True) if r: return r elif r is False: # All args except one are rational if all(a.is_zero is False for a in self.args): return False def _eval_is_algebraic(self): r = _fuzzy_group((a.is_algebraic for a in self.args), quick_exit=True) if r: return r elif r is False: # All args except one are algebraic if all(a.is_zero is False for a in self.args): return False # without involving odd/even checks this code would suffice: #_eval_is_integer = lambda self: _fuzzy_group( # (a.is_integer for a in self.args), quick_exit=True) def _eval_is_integer(self): is_rational = self._eval_is_rational() if is_rational is False: return False numerators = [] denominators = [] unknown = False for a in self.args: hit = False if a.is_integer: if abs(a) is not S.One: numerators.append(a) elif a.is_Rational: n, d = a.as_numer_denom() if abs(n) is not S.One: numerators.append(n) if d is not S.One: denominators.append(d) elif a.is_Pow: b, e = a.as_base_exp() if not b.is_integer or not e.is_integer: hit = unknown = True if e.is_negative: denominators.append(2 if a is S.Half else Pow(a, S.NegativeOne)) elif not hit: # int b and pos int e: a = b**e is integer assert not e.is_positive # for rational self and e equal to zero: a = b**e is 1 assert not e.is_zero return # sign of e unknown -> self.is_integer unknown else: # x**2, 2**x, or x**y with x and y int-unknown -> unknown return else: return if not denominators and not unknown: return True allodd = lambda x: all(i.is_odd for i in x) alleven = lambda x: all(i.is_even for i in x) anyeven = lambda x: any(i.is_even for i in x) from .relational import is_gt if not numerators and denominators and all( is_gt(_, S.One) for _ in denominators): return False elif unknown: return elif allodd(numerators) and anyeven(denominators): return False elif anyeven(numerators) and denominators == [2]: return True elif alleven(numerators) and allodd(denominators ) and (Mul(*denominators, evaluate=False) - 1 ).is_positive: return False if len(denominators) == 1: d = denominators[0] if d.is_Integer: is_power_of_two = d.p & (d.p - 1) == 0 # if minimal power of 2 in num vs den is not # negative then we have an integer if is_power_of_two and (Add(*[i.as_base_exp()[1] for i in numerators if i.is_even]) - trailing(d.p) ).is_nonnegative: return True if len(numerators) == 1: n = numerators[0] if n.is_Integer and n.is_even: # if minimal power of 2 in den vs num is positive # then we have have a non-integer if (Add(*[i.as_base_exp()[1] for i in denominators if i.is_even]) - trailing(n.p) ).is_positive: return False def _eval_is_polar(self): has_polar = any(arg.is_polar for arg in self.args) return has_polar and \ all(arg.is_polar or arg.is_positive for arg in self.args) def _eval_is_extended_real(self): return self._eval_real_imag(True) def _eval_real_imag(self, real): zero = False t_not_re_im = None for t in self.args: if (t.is_complex or t.is_infinite) is False and t.is_extended_real is False: return False elif t.is_imaginary: # I real = not real elif t.is_extended_real: # 2 if not zero: z = t.is_zero if not z and zero is False: zero = z elif z: if all(a.is_finite for a in self.args): return True return elif t.is_extended_real is False: # symbolic or literal like `2 + I` or symbolic imaginary if t_not_re_im: return # complex terms might cancel t_not_re_im = t elif t.is_imaginary is False: # symbolic like `2` or `2 + I` if t_not_re_im: return # complex terms might cancel t_not_re_im = t else: return if t_not_re_im: if t_not_re_im.is_extended_real is False: if real: # like 3 return zero # 3*(smthng like 2 + I or i) is not real if t_not_re_im.is_imaginary is False: # symbolic 2 or 2 + I if not real: # like I return zero # I*(smthng like 2 or 2 + I) is not real elif zero is False: return real # can't be trumped by 0 elif real: return real # doesn't matter what zero is def _eval_is_imaginary(self): if all(a.is_zero is False and a.is_finite for a in self.args): return self._eval_real_imag(False) def _eval_is_hermitian(self): return self._eval_herm_antiherm(True) def _eval_is_antihermitian(self): return self._eval_herm_antiherm(False) def _eval_herm_antiherm(self, herm): for t in self.args: if t.is_hermitian is None or t.is_antihermitian is None: return if t.is_hermitian: continue elif t.is_antihermitian: herm = not herm else: return if herm is not False: return herm is_zero = self._eval_is_zero() if is_zero: return True elif is_zero is False: return herm def _eval_is_irrational(self): for t in self.args: a = t.is_irrational if a: others = list(self.args) others.remove(t) if all((x.is_rational and fuzzy_not(x.is_zero)) is True for x in others): return True return if a is None: return if all(x.is_real for x in self.args): return False def _eval_is_extended_positive(self): """Return True if self is positive, False if not, and None if it cannot be determined. Explanation =========== This algorithm is non-recursive and works by keeping track of the sign which changes when a negative or nonpositive is encountered. Whether a nonpositive or nonnegative is seen is also tracked since the presence of these makes it impossible to return True, but possible to return False if the end result is nonpositive. e.g. pos * neg * nonpositive -> pos or zero -> None is returned pos * neg * nonnegative -> neg or zero -> False is returned """ return self._eval_pos_neg(1) def _eval_pos_neg(self, sign): saw_NON = saw_NOT = False for t in self.args: if t.is_extended_positive: continue elif t.is_extended_negative: sign = -sign elif t.is_zero: if all(a.is_finite for a in self.args): return False return elif t.is_extended_nonpositive: sign = -sign saw_NON = True elif t.is_extended_nonnegative: saw_NON = True # FIXME: is_positive/is_negative is False doesn't take account of # Symbol('x', infinite=True, extended_real=True) which has # e.g. is_positive is False but has uncertain sign. elif t.is_positive is False: sign = -sign if saw_NOT: return saw_NOT = True elif t.is_negative is False: if saw_NOT: return saw_NOT = True else: return if sign == 1 and saw_NON is False and saw_NOT is False: return True if sign < 0: return False def _eval_is_extended_negative(self): return self._eval_pos_neg(-1) def _eval_is_odd(self): is_integer = self._eval_is_integer() if is_integer is not True: return is_integer from sympy.simplify.radsimp import fraction n, d = fraction(self) if d.is_Integer and d.is_even: # if minimal power of 2 in num vs den is # positive then we have an even number if (Add(*[i.as_base_exp()[1] for i in Mul.make_args(n) if i.is_even]) - trailing(d.p) ).is_positive: return False return r, acc = True, 1 for t in self.args: if abs(t) is S.One: continue if t.is_even: return False if r is False: pass elif acc != 1 and (acc + t).is_odd: r = False elif t.is_even is None: r = None acc = t return r def _eval_is_even(self): from sympy.simplify.radsimp import fraction n, d = fraction(self, exact=True) if n.is_Integer and n.is_even: # if minimal power of 2 in den vs num is not # negative then this is not an integer and # can't be even if (Add(*[i.as_base_exp()[1] for i in Mul.make_args(d) if i.is_even]) - trailing(n.p) ).is_nonnegative: return False def _eval_is_composite(self): """ Here we count the number of arguments that have a minimum value greater than two. If there are more than one of such a symbol then the result is composite. Else, the result cannot be determined. """ number_of_args = 0 # count of symbols with minimum value greater than one for arg in self.args: if not (arg.is_integer and arg.is_positive): return None if (arg-1).is_positive: number_of_args += 1 if number_of_args > 1: return True def _eval_subs(self, old, new): from sympy.functions.elementary.complexes import sign from sympy.ntheory.factor_ import multiplicity from sympy.simplify.powsimp import powdenest from sympy.simplify.radsimp import fraction if not old.is_Mul: return None # try keep replacement literal so -2*x doesn't replace 4*x if old.args[0].is_Number and old.args[0] < 0: if self.args[0].is_Number: if self.args[0] < 0: return self._subs(-old, -new) return None def base_exp(a): # if I and -1 are in a Mul, they get both end up with # a -1 base (see issue 6421); all we want here are the # true Pow or exp separated into base and exponent from sympy.functions.elementary.exponential import exp if a.is_Pow or isinstance(a, exp): return a.as_base_exp() return a, S.One def breakup(eq): """break up powers of eq when treated as a Mul: b**(Rational*e) -> b**e, Rational commutatives come back as a dictionary {b**e: Rational} noncommutatives come back as a list [(b**e, Rational)] """ (c, nc) = (defaultdict(int), []) for a in Mul.make_args(eq): a = powdenest(a) (b, e) = base_exp(a) if e is not S.One: (co, _) = e.as_coeff_mul() b = Pow(b, e/co) e = co if a.is_commutative: c[b] += e else: nc.append([b, e]) return (c, nc) def rejoin(b, co): """ Put rational back with exponent; in general this is not ok, but since we took it from the exponent for analysis, it's ok to put it back. """ (b, e) = base_exp(b) return Pow(b, e*co) def ndiv(a, b): """if b divides a in an extractive way (like 1/4 divides 1/2 but not vice versa, and 2/5 does not divide 1/3) then return the integer number of times it divides, else return 0. """ if not b.q % a.q or not a.q % b.q: return int(a/b) return 0 # give Muls in the denominator a chance to be changed (see issue 5651) # rv will be the default return value rv = None n, d = fraction(self) self2 = self if d is not S.One: self2 = n._subs(old, new)/d._subs(old, new) if not self2.is_Mul: return self2._subs(old, new) if self2 != self: rv = self2 # Now continue with regular substitution. # handle the leading coefficient and use it to decide if anything # should even be started; we always know where to find the Rational # so it's a quick test co_self = self2.args[0] co_old = old.args[0] co_xmul = None if co_old.is_Rational and co_self.is_Rational: # if coeffs are the same there will be no updating to do # below after breakup() step; so skip (and keep co_xmul=None) if co_old != co_self: co_xmul = co_self.extract_multiplicatively(co_old) elif co_old.is_Rational: return rv # break self and old into factors (c, nc) = breakup(self2) (old_c, old_nc) = breakup(old) # update the coefficients if we had an extraction # e.g. if co_self were 2*(3/35*x)**2 and co_old = 3/5 # then co_self in c is replaced by (3/5)**2 and co_residual # is 2*(1/7)**2 if co_xmul and co_xmul.is_Rational and abs(co_old) != 1: mult = S(multiplicity(abs(co_old), co_self)) c.pop(co_self) if co_old in c: c[co_old] += mult else: c[co_old] = mult co_residual = co_self/co_old**mult else: co_residual = 1 # do quick tests to see if we can't succeed ok = True if len(old_nc) > len(nc): # more non-commutative terms ok = False elif len(old_c) > len(c): # more commutative terms ok = False elif {i[0] for i in old_nc}.difference({i[0] for i in nc}): # unmatched non-commutative bases ok = False elif set(old_c).difference(set(c)): # unmatched commutative terms ok = False elif any(sign(c[b]) != sign(old_c[b]) for b in old_c): # differences in sign ok = False if not ok: return rv if not old_c: cdid = None else: rat = [] for (b, old_e) in old_c.items(): c_e = c[b] rat.append(ndiv(c_e, old_e)) if not rat[-1]: return rv cdid = min(rat) if not old_nc: ncdid = None for i in range(len(nc)): nc[i] = rejoin(*nc[i]) else: ncdid = 0 # number of nc replacements we did take = len(old_nc) # how much to look at each time limit = cdid or S.Infinity # max number that we can take failed = [] # failed terms will need subs if other terms pass i = 0 while limit and i + take <= len(nc): hit = False # the bases must be equivalent in succession, and # the powers must be extractively compatible on the # first and last factor but equal in between. rat = [] for j in range(take): if nc[i + j][0] != old_nc[j][0]: break elif j == 0 or j == take - 1: rat.append(ndiv(nc[i + j][1], old_nc[j][1])) elif nc[i + j][1] != old_nc[j][1]: break else: rat.append(1) else: ndo = min(rat) if ndo: if take == 1: if cdid: ndo = min(cdid, ndo) nc[i] = Pow(new, ndo)*rejoin(nc[i][0], nc[i][1] - ndo*old_nc[0][1]) else: ndo = 1 # the left residual l = rejoin(nc[i][0], nc[i][1] - ndo* old_nc[0][1]) # eliminate all middle terms mid = new # the right residual (which may be the same as the middle if take == 2) ir = i + take - 1 r = (nc[ir][0], nc[ir][1] - ndo* old_nc[-1][1]) if r[1]: if i + take < len(nc): nc[i:i + take] = [l*mid, r] else: r = rejoin(*r) nc[i:i + take] = [l*mid*r] else: # there was nothing left on the right nc[i:i + take] = [l*mid] limit -= ndo ncdid += ndo hit = True if not hit: # do the subs on this failing factor failed.append(i) i += 1 else: if not ncdid: return rv # although we didn't fail, certain nc terms may have # failed so we rebuild them after attempting a partial # subs on them failed.extend(range(i, len(nc))) for i in failed: nc[i] = rejoin(*nc[i]).subs(old, new) # rebuild the expression if cdid is None: do = ncdid elif ncdid is None: do = cdid else: do = min(ncdid, cdid) margs = [] for b in c: if b in old_c: # calculate the new exponent e = c[b] - old_c[b]*do margs.append(rejoin(b, e)) else: margs.append(rejoin(b.subs(old, new), c[b])) if cdid and not ncdid: # in case we are replacing commutative with non-commutative, # we want the new term to come at the front just like the # rest of this routine margs = [Pow(new, cdid)] + margs return co_residual*self2.func(*margs)*self2.func(*nc) def _eval_nseries(self, x, n, logx, cdir=0): from .function import PoleError from sympy.functions.elementary.integers import ceiling from sympy.series.order import Order def coeff_exp(term, x): lt = term.as_coeff_exponent(x) if lt[0].has(x): try: lt = term.leadterm(x) except ValueError: return term, S.Zero return lt ords = [] try: for t in self.args: coeff, exp = t.leadterm(x) if not coeff.has(x): ords.append((t, exp)) else: raise ValueError n0 = sum(t[1] for t in ords if t[1].is_number) facs = [] for t, m in ords: n1 = ceiling(n - n0 + (m if m.is_number else 0)) s = t.nseries(x, n=n1, logx=logx, cdir=cdir) ns = s.getn() if ns is not None: if ns < n1: # less than expected n -= n1 - ns # reduce n facs.append(s) except (ValueError, NotImplementedError, TypeError, PoleError): # XXX: Catching so many generic exceptions around a large block of # code will mask bugs. Whatever purpose catching these exceptions # serves should be handled in a different way. n0 = sympify(sum(t[1] for t in ords if t[1].is_number)) if n0.is_nonnegative: n0 = S.Zero facs = [t.nseries(x, n=ceiling(n-n0), logx=logx, cdir=cdir) for t in self.args] from sympy.simplify.powsimp import powsimp res = powsimp(self.func(*facs).expand(), combine='exp', deep=True) if res.has(Order): res += Order(x**n, x) return res res = S.Zero ords2 = [Add.make_args(factor) for factor in facs] for fac in product(*ords2): ords3 = [coeff_exp(term, x) for term in fac] coeffs, powers = zip(*ords3) power = sum(powers) if (power - n).is_negative: res += Mul(*coeffs)*(x**power) def max_degree(e, x): if e is x: return S.One if e.is_Atom: return S.Zero if e.is_Add: return max(max_degree(a, x) for a in e.args) if e.is_Mul: return Add(*[max_degree(a, x) for a in e.args]) if e.is_Pow: return max_degree(e.base, x)*e.exp return S.Zero if self.is_polynomial(x): from sympy.polys.polyerrors import PolynomialError from sympy.polys.polytools import degree try: if max_degree(self, x) >= n or degree(self, x) != degree(res, x): res += Order(x**n, x) except PolynomialError: pass else: return res if res != self: if (self - res).subs(x, 0) == S.Zero and n > 0: lt = self._eval_as_leading_term(x, logx=logx, cdir=cdir) if lt == S.Zero: return res res += Order(x**n, x) return res def _eval_as_leading_term(self, x, logx, cdir): return self.func(*[t.as_leading_term(x, logx=logx, cdir=cdir) for t in self.args]) def _eval_conjugate(self): return self.func(*[t.conjugate() for t in self.args]) def _eval_transpose(self): return self.func(*[t.transpose() for t in self.args[::-1]]) def _eval_adjoint(self): return self.func(*[t.adjoint() for t in self.args[::-1]]) def as_content_primitive(self, radical=False, clear=True): """Return the tuple (R, self/R) where R is the positive Rational extracted from self. Examples ======== >>> from sympy import sqrt >>> (-3*sqrt(2)*(2 - 2*sqrt(2))).as_content_primitive() (6, -sqrt(2)*(1 - sqrt(2))) See docstring of Expr.as_content_primitive for more examples. """ coef = S.One args = [] for a in self.args: c, p = a.as_content_primitive(radical=radical, clear=clear) coef *= c if p is not S.One: args.append(p) # don't use self._from_args here to reconstruct args # since there may be identical args now that should be combined # e.g. (2+2*x)*(3+3*x) should be (6, (1 + x)**2) not (6, (1+x)*(1+x)) return coef, self.func(*args) def as_ordered_factors(self, order=None): """Transform an expression into an ordered list of factors. Examples ======== >>> from sympy import sin, cos >>> from sympy.abc import x, y >>> (2*x*y*sin(x)*cos(x)).as_ordered_factors() [2, x, y, sin(x), cos(x)] """ cpart, ncpart = self.args_cnc() cpart.sort(key=lambda expr: expr.sort_key(order=order)) return cpart + ncpart @property def _sorted_args(self): return tuple(self.as_ordered_factors()) mul = AssocOpDispatcher('mul') def prod(a, start=1): """Return product of elements of a. Start with int 1 so if only ints are included then an int result is returned. Examples ======== >>> from sympy import prod, S >>> prod(range(3)) 0 >>> type(_) is int True >>> prod([S(2), 3]) 6 >>> _.is_Integer True You can start the product at something other than 1: >>> prod([1, 2], 3) 6 """ return reduce(operator.mul, a, start) def _keep_coeff(coeff, factors, clear=True, sign=False): """Return ``coeff*factors`` unevaluated if necessary. If ``clear`` is False, do not keep the coefficient as a factor if it can be distributed on a single factor such that one or more terms will still have integer coefficients. If ``sign`` is True, allow a coefficient of -1 to remain factored out. Examples ======== >>> from sympy.core.mul import _keep_coeff >>> from sympy.abc import x, y >>> from sympy import S >>> _keep_coeff(S.Half, x + 2) (x + 2)/2 >>> _keep_coeff(S.Half, x + 2, clear=False) x/2 + 1 >>> _keep_coeff(S.Half, (x + 2)*y, clear=False) y*(x + 2)/2 >>> _keep_coeff(S(-1), x + y) -x - y >>> _keep_coeff(S(-1), x + y, sign=True) -(x + y) """ if not coeff.is_Number: if factors.is_Number: factors, coeff = coeff, factors else: return coeff*factors if factors is S.One: return coeff if coeff is S.One: return factors elif coeff is S.NegativeOne and not sign: return -factors elif factors.is_Add: if not clear and coeff.is_Rational and coeff.q != 1: args = [i.as_coeff_Mul() for i in factors.args] args = [(_keep_coeff(c, coeff), m) for c, m in args] if any(c.is_Integer for c, _ in args): return Add._from_args([Mul._from_args( i[1:] if i[0] == 1 else i) for i in args]) return Mul(coeff, factors, evaluate=False) elif factors.is_Mul: margs = list(factors.args) if margs[0].is_Number: margs[0] *= coeff if margs[0] == 1: margs.pop(0) else: margs.insert(0, coeff) return Mul._from_args(margs) else: m = coeff*factors if m.is_Number and not factors.is_Number: m = Mul._from_args((coeff, factors)) return m def expand_2arg(e): def do(e): if e.is_Mul: c, r = e.as_coeff_Mul() if c.is_Number and r.is_Add: return _unevaluated_Add(*[c*ri for ri in r.args]) return e return bottom_up(e, do) from .numbers import Rational from .power import Pow from .add import Add, _unevaluated_Add
Mul
python
django__django
django/contrib/postgres/indexes.py
{ "start": 1326, "end": 2890 }
class ____(PostgresIndex): suffix = "bloom" def __init__(self, *expressions, length=None, columns=(), **kwargs): super().__init__(*expressions, **kwargs) if len(self.fields) > 32: raise ValueError("Bloom indexes support a maximum of 32 fields.") if not isinstance(columns, (list, tuple)): raise ValueError("BloomIndex.columns must be a list or tuple.") if len(columns) > len(self.fields): raise ValueError("BloomIndex.columns cannot have more values than fields.") if not all(0 < col <= 4095 for col in columns): raise ValueError( "BloomIndex.columns must contain integers from 1 to 4095.", ) if length is not None and not 0 < length <= 4096: raise ValueError( "BloomIndex.length must be None or an integer from 1 to 4096.", ) self.length = length self.columns = columns def deconstruct(self): path, args, kwargs = super().deconstruct() if self.length is not None: kwargs["length"] = self.length if self.columns: kwargs["columns"] = self.columns return path, args, kwargs def get_with_params(self): with_params = [] if self.length is not None: with_params.append("length = %d" % self.length) if self.columns: with_params.extend( "col%d = %d" % (i, v) for i, v in enumerate(self.columns, start=1) ) return with_params
BloomIndex
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B006_B008.py
{ "start": 1109, "end": 5849 }
class ____: @staticmethod def this_is_also_wrong_and_more_indented(value={}): pass def multiline_arg_wrong(value={ }): ... def single_line_func_wrong(value = {}): ... def and_this(value=set()): ... def this_too(value=collections.OrderedDict()): ... async def async_this_too(value=collections.defaultdict()): ... def dont_forget_me(value=collections.deque()): ... # N.B. we're also flagging the function call in the comprehension def list_comprehension_also_not_okay(default=[i**2 for i in range(3)]): pass def dict_comprehension_also_not_okay(default={i: i**2 for i in range(3)}): pass def set_comprehension_also_not_okay(default={i**2 for i in range(3)}): pass def kwonlyargs_mutable(*, value=[]): ... # Recommended approach for mutable defaults def do_this_instead(value=None): if value is None: value = set() # B008 # Flag function calls as default args (including if they are part of a sub-expression) def in_fact_all_calls_are_wrong(value=time.time()): ... def f(when=dt.datetime.now() + dt.timedelta(days=7)): pass def can_even_catch_lambdas(a=(lambda x: x)()): ... # Recommended approach for function calls as default args LOGGER = logging.getLogger(__name__) def do_this_instead_of_calls_in_defaults(logger=LOGGER): # That makes it more obvious that this one value is reused. ... # Handle inf/infinity/nan special case def float_inf_okay(value=float("inf")): pass def float_infinity_okay(value=float("infinity")): pass def float_plus_infinity_okay(value=float("+infinity")): pass def float_minus_inf_okay(value=float("-inf")): pass def float_nan_okay(value=float("nan")): pass def float_minus_NaN_okay(value=float("-NaN")): pass def float_infinity_literal(value=float("1e999")): pass # Allow standard floats def float_int_okay(value=float(3)): pass def float_str_not_inf_or_nan_okay(value=float("3.14")): pass # Allow immutable str() value def str_okay(value=str("foo")): pass # Allow immutable bool() value def bool_okay(value=bool("bar")): pass # Allow immutable bytes() value def bytes_okay(value=bytes(1)): pass # Allow immutable int() value def int_okay(value=int("12")): pass # Allow immutable complex() value def complex_okay(value=complex(1,2)): pass # Allow immutable Fraction() value def fraction_okay(value=Fraction(1,2)): pass # Allow decimals def decimal_okay(value=Decimal("0.1")): pass # Allow dates def date_okay(value=dt.date(2023, 3, 27)): pass # Allow datetimes def datetime_okay(value=dt.datetime(2023, 3, 27, 13, 51, 59)): pass # Allow timedeltas def timedelta_okay(value=dt.timedelta(hours=1)): pass # Allow paths def path_okay(value=Path(".")): pass # B008 allow arbitrary call with immutable annotation def immutable_annotation_call(value: Sequence[int] = foo()): pass # B006 and B008 # We should handle arbitrary nesting of these B008. def nested_combo(a=[float(3), dt.datetime.now()]): pass # Don't flag nested B006 since we can't guarantee that # it isn't made mutable by the outer operation. def no_nested_b006(a=map(lambda s: s.upper(), ["a", "b", "c"])): pass # B008-ception. def nested_b008(a=random.randint(0, dt.datetime.now().year)): pass # Ignore lambda contents since they are evaluated at call time. def foo(f=lambda x: print(x)): f(1) from collections import abc from typing import Annotated, Dict, Optional, Sequence, Union, Set import typing_extensions def immutable_annotations( a: Sequence[int] | None = [], b: Optional[abc.Mapping[int, int]] = {}, c: Annotated[Union[abc.Set[str], abc.Sized], "annotation"] = set(), d: typing_extensions.Annotated[ Union[abc.Set[str], abc.Sized], "annotation" ] = set(), ): pass def mutable_annotations( a: list[int] | None = [], b: Optional[Dict[int, int]] = {}, c: Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), d: typing_extensions.Annotated[Union[Set[str], abc.Sized], "annotation"] = set(), ): pass def single_line_func_wrong(value: dict[str, str] = {}): """Docstring""" def single_line_func_wrong(value: dict[str, str] = {}): """Docstring""" ... def single_line_func_wrong(value: dict[str, str] = {}): """Docstring"""; ... def single_line_func_wrong(value: dict[str, str] = {}): """Docstring"""; \ ... def single_line_func_wrong(value: dict[str, str] = { # This is a comment }): """Docstring""" def single_line_func_wrong(value: dict[str, str] = {}) \ : \ """Docstring""" def single_line_func_wrong(value: dict[str, str] = {}): """Docstring without newline"""
Foo
python
kubernetes-client__python
kubernetes/client/models/v1alpha3_device_taint.py
{ "start": 383, "end": 6720 }
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 = { 'effect': 'str', 'key': 'str', 'time_added': 'datetime', 'value': 'str' } attribute_map = { 'effect': 'effect', 'key': 'key', 'time_added': 'timeAdded', 'value': 'value' } def __init__(self, effect=None, key=None, time_added=None, value=None, local_vars_configuration=None): # noqa: E501 """V1alpha3DeviceTaint - 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._effect = None self._key = None self._time_added = None self._value = None self.discriminator = None self.effect = effect self.key = key if time_added is not None: self.time_added = time_added if value is not None: self.value = value @property def effect(self): """Gets the effect of this V1alpha3DeviceTaint. # noqa: E501 The effect of the taint on claims that do not tolerate the taint and through such claims on the pods using them. Valid effects are NoSchedule and NoExecute. PreferNoSchedule as used for nodes is not valid here. # noqa: E501 :return: The effect of this V1alpha3DeviceTaint. # noqa: E501 :rtype: str """ return self._effect @effect.setter def effect(self, effect): """Sets the effect of this V1alpha3DeviceTaint. The effect of the taint on claims that do not tolerate the taint and through such claims on the pods using them. Valid effects are NoSchedule and NoExecute. PreferNoSchedule as used for nodes is not valid here. # noqa: E501 :param effect: The effect of this V1alpha3DeviceTaint. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and effect is None: # noqa: E501 raise ValueError("Invalid value for `effect`, must not be `None`") # noqa: E501 self._effect = effect @property def key(self): """Gets the key of this V1alpha3DeviceTaint. # noqa: E501 The taint key to be applied to a device. Must be a label name. # noqa: E501 :return: The key of this V1alpha3DeviceTaint. # noqa: E501 :rtype: str """ return self._key @key.setter def key(self, key): """Sets the key of this V1alpha3DeviceTaint. The taint key to be applied to a device. Must be a label name. # noqa: E501 :param key: The key of this V1alpha3DeviceTaint. # noqa: E501 :type: str """ if self.local_vars_configuration.client_side_validation and key is None: # noqa: E501 raise ValueError("Invalid value for `key`, must not be `None`") # noqa: E501 self._key = key @property def time_added(self): """Gets the time_added of this V1alpha3DeviceTaint. # noqa: E501 TimeAdded represents the time at which the taint was added. Added automatically during create or update if not set. # noqa: E501 :return: The time_added of this V1alpha3DeviceTaint. # noqa: E501 :rtype: datetime """ return self._time_added @time_added.setter def time_added(self, time_added): """Sets the time_added of this V1alpha3DeviceTaint. TimeAdded represents the time at which the taint was added. Added automatically during create or update if not set. # noqa: E501 :param time_added: The time_added of this V1alpha3DeviceTaint. # noqa: E501 :type: datetime """ self._time_added = time_added @property def value(self): """Gets the value of this V1alpha3DeviceTaint. # noqa: E501 The taint value corresponding to the taint key. Must be a label value. # noqa: E501 :return: The value of this V1alpha3DeviceTaint. # noqa: E501 :rtype: str """ return self._value @value.setter def value(self, value): """Sets the value of this V1alpha3DeviceTaint. The taint value corresponding to the taint key. Must be a label value. # noqa: E501 :param value: The value of this V1alpha3DeviceTaint. # noqa: E501 :type: str """ self._value = value 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, V1alpha3DeviceTaint): 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, V1alpha3DeviceTaint): return True return self.to_dict() != other.to_dict()
V1alpha3DeviceTaint
python
pennersr__django-allauth
allauth/idp/oidc/views.py
{ "start": 11027, "end": 13273 }
class ____(View): def dispatch(self, request, *args, **kwargs): if "code" in request.GET: form = ConfirmCodeForm(request.GET) if form.is_valid(): return self._dispatch_authorization( request, form.cleaned_data["code"], form.device_code, form.client, ) else: form = ConfirmCodeForm() context = { "form": form, "autorization_url": reverse("idp:oidc:device_authorization"), } return render( request, "idp/oidc/device_authorization_code_form." + account_settings.TEMPLATE_EXTENSION, context, ) def _dispatch_authorization( self, request, user_code: str, device_code: str, client: Client ): context = {"user_code": user_code, "client": client} if request.method == "POST": form = DeviceAuthorizationForm(request.POST) if form.is_valid(): confirm = form.cleaned_data["action"] == "confirm" device_codes.confirm_or_deny_device_code( request.user, device_code, confirm=confirm ) if confirm: template_name = "idp/oidc/device_authorization_confirmed." else: template_name = "idp/oidc/device_authorization_denied." return render( request, template_name + account_settings.TEMPLATE_EXTENSION, context, ) else: form = DeviceAuthorizationForm() context["autorization_url"] = ( reverse("idp:oidc:device_authorization") + "?" + urlencode({"code": user_code}) ) return render( request, "idp/oidc/device_authorization_confirm_form." + account_settings.TEMPLATE_EXTENSION, context, ) device_authorization = DeviceAuthorizationView.as_view() @method_decorator(csrf_exempt, name="dispatch") @method_decorator(login_not_required, name="dispatch")
DeviceAuthorizationView
python
pennersr__django-allauth
allauth/mfa/migrations/0002_authenticator_timestamps.py
{ "start": 122, "end": 597 }
class ____(migrations.Migration): dependencies = [ ("mfa", "0001_initial"), ] operations = [ migrations.AddField( model_name="authenticator", name="created_at", field=models.DateTimeField(default=django.utils.timezone.now), ), migrations.AddField( model_name="authenticator", name="last_used_at", field=models.DateTimeField(null=True), ), ]
Migration
python
scipy__scipy
scipy/optimize/_trustregion_constr/tr_interior_point.py
{ "start": 742, "end": 14395 }
class ____: """ Barrier optimization problem: minimize fun(x) - barrier_parameter*sum(log(s)) subject to: constr_eq(x) = 0 constr_ineq(x) + s = 0 """ def __init__(self, x0, s0, fun, grad, lagr_hess, n_vars, n_ineq, n_eq, constr, jac, barrier_parameter, tolerance, enforce_feasibility, global_stop_criteria, xtol, fun0, grad0, constr_ineq0, jac_ineq0, constr_eq0, jac_eq0, finite_diff_bounds): # Store parameters self.n_vars = n_vars self.x0 = x0 self.s0 = s0 self.fun = fun self.grad = grad self.lagr_hess = lagr_hess self.constr = constr self.jac = jac self.barrier_parameter = barrier_parameter self.tolerance = tolerance self.n_eq = n_eq self.n_ineq = n_ineq self.enforce_feasibility = enforce_feasibility self.global_stop_criteria = global_stop_criteria self.xtol = xtol self.fun0 = self._compute_function(fun0, constr_ineq0, s0) self.grad0 = self._compute_gradient(grad0) self.constr0 = self._compute_constr(constr_ineq0, constr_eq0, s0) self.jac0 = self._compute_jacobian(jac_eq0, jac_ineq0, s0) self.terminate = False self.lb = finite_diff_bounds[0] self.ub = finite_diff_bounds[1] def update(self, barrier_parameter, tolerance): self.barrier_parameter = barrier_parameter self.tolerance = tolerance def get_slack(self, z): return z[self.n_vars:self.n_vars+self.n_ineq] def get_variables(self, z): return z[:self.n_vars] def function_and_constraints(self, z): """Returns barrier function and constraints at given point. For z = [x, s], returns barrier function: function(z) = fun(x) - barrier_parameter*sum(log(s)) and barrier constraints: constraints(z) = [ constr_eq(x) ] [ constr_ineq(x) + s ] """ # Get variables and slack variables x = self.get_variables(z) s = self.get_slack(z) # Compute function and constraints, # making sure x is within any strict bounds if np.any((x < self.lb) | (x > self.ub)): # If x is out of the strict bounds, set f = inf, # and just set both equality and inequality # constraints to 0 since we can't evaluate # them separately. f = np.inf c_eq = np.full(self.n_eq, 0.) c_ineq = np.full(self.n_ineq, 0.) else: f = self.fun(x) c_eq, c_ineq = self.constr(x) # Return objective function and constraints return (self._compute_function(f, c_ineq, s), self._compute_constr(c_ineq, c_eq, s)) def _compute_function(self, f, c_ineq, s): # Use technique from Nocedal and Wright book, ref [3]_, p.576, # to guarantee constraints from `enforce_feasibility` # stay feasible along iterations. s[self.enforce_feasibility] = -c_ineq[self.enforce_feasibility] log_s = [np.log(s_i) if s_i > 0 else -np.inf for s_i in s] # Compute barrier objective function return f - self.barrier_parameter*np.sum(log_s) def _compute_constr(self, c_ineq, c_eq, s): # Compute barrier constraint return np.hstack((c_eq, c_ineq + s)) def scaling(self, z): """Returns scaling vector. Given by: scaling = [ones(n_vars), s] """ s = self.get_slack(z) diag_elements = np.hstack((np.ones(self.n_vars), s)) # Diagonal matrix def matvec(vec): return diag_elements*vec return LinearOperator((self.n_vars+self.n_ineq, self.n_vars+self.n_ineq), matvec) def gradient_and_jacobian(self, z): """Returns scaled gradient. Return scaled gradient: gradient = [ grad(x) ] [ -barrier_parameter*ones(n_ineq) ] and scaled Jacobian matrix: jacobian = [ jac_eq(x) 0 ] [ jac_ineq(x) S ] Both of them scaled by the previously defined scaling factor. """ # Get variables and slack variables x = self.get_variables(z) s = self.get_slack(z) # Compute first derivatives g = self.grad(x) J_eq, J_ineq = self.jac(x) # Return gradient and Jacobian return (self._compute_gradient(g), self._compute_jacobian(J_eq, J_ineq, s)) def _compute_gradient(self, g): return np.hstack((g, -self.barrier_parameter*np.ones(self.n_ineq))) def _compute_jacobian(self, J_eq, J_ineq, s): if self.n_ineq == 0: return J_eq else: if sps.issparse(J_eq) or sps.issparse(J_ineq): # It is expected that J_eq and J_ineq # are already `csr_array` because of # the way ``BoxConstraint``, ``NonlinearConstraint`` # and ``LinearConstraint`` are defined. J_eq = sps.csr_array(J_eq) J_ineq = sps.csr_array(J_ineq) return self._assemble_sparse_jacobian(J_eq, J_ineq, s) else: S = np.diag(s) zeros = np.zeros((self.n_eq, self.n_ineq)) # Convert to matrix if sps.issparse(J_ineq): J_ineq = J_ineq.toarray() if sps.issparse(J_eq): J_eq = J_eq.toarray() # Concatenate matrices return np.block([[J_eq, zeros], [J_ineq, S]]) def _assemble_sparse_jacobian(self, J_eq, J_ineq, s): """Assemble sparse Jacobian given its components. Given ``J_eq``, ``J_ineq`` and ``s`` returns: jacobian = [ J_eq, 0 ] [ J_ineq, diag(s) ] It is equivalent to: sps.bmat([[ J_eq, None ], [ J_ineq, diag(s) ]], "csr") but significantly more efficient for this given structure. """ n_vars, n_ineq, n_eq = self.n_vars, self.n_ineq, self.n_eq J_aux = sps.vstack([J_eq, J_ineq], "csr") indptr, indices, data = J_aux.indptr, J_aux.indices, J_aux.data new_indptr = indptr + np.hstack((np.zeros(n_eq, dtype=int), np.arange(n_ineq+1, dtype=int))) size = indices.size+n_ineq new_indices = np.empty(size) new_data = np.empty(size) mask = np.full(size, False, bool) mask[new_indptr[-n_ineq:]-1] = True new_indices[mask] = n_vars+np.arange(n_ineq) new_indices[~mask] = indices new_data[mask] = s new_data[~mask] = data J = sps.csr_array((new_data, new_indices, new_indptr), (n_eq + n_ineq, n_vars + n_ineq)) return J def lagrangian_hessian_x(self, z, v): """Returns Lagrangian Hessian (in relation to `x`) -> Hx""" x = self.get_variables(z) # Get lagrange multipliers related to nonlinear equality constraints v_eq = v[:self.n_eq] # Get lagrange multipliers related to nonlinear ineq. constraints v_ineq = v[self.n_eq:self.n_eq+self.n_ineq] lagr_hess = self.lagr_hess return lagr_hess(x, v_eq, v_ineq) def lagrangian_hessian_s(self, z, v): """Returns scaled Lagrangian Hessian (in relation to`s`) -> S Hs S""" s = self.get_slack(z) # Using the primal formulation: # S Hs S = diag(s)*diag(barrier_parameter/s**2)*diag(s). # Reference [1]_ p. 882, formula (3.1) primal = self.barrier_parameter # Using the primal-dual formulation # S Hs S = diag(s)*diag(v/s)*diag(s) # Reference [1]_ p. 883, formula (3.11) primal_dual = v[-self.n_ineq:]*s # Uses the primal-dual formulation for # positives values of v_ineq, and primal # formulation for the remaining ones. return np.where(v[-self.n_ineq:] > 0, primal_dual, primal) def lagrangian_hessian(self, z, v): """Returns scaled Lagrangian Hessian""" # Compute Hessian in relation to x and s Hx = self.lagrangian_hessian_x(z, v) if self.n_ineq > 0: S_Hs_S = self.lagrangian_hessian_s(z, v) # The scaled Lagragian Hessian is: # [ Hx 0 ] # [ 0 S Hs S ] def matvec(vec): vec_x = self.get_variables(vec) vec_s = self.get_slack(vec) if self.n_ineq > 0: return np.hstack((Hx.dot(vec_x), S_Hs_S*vec_s)) else: return Hx.dot(vec_x) return LinearOperator((self.n_vars+self.n_ineq, self.n_vars+self.n_ineq), matvec) def stop_criteria(self, state, z, last_iteration_failed, optimality, constr_violation, trust_radius, penalty, cg_info): """Stop criteria to the barrier problem. The criteria here proposed is similar to formula (2.3) from [1]_, p.879. """ x = self.get_variables(z) if self.global_stop_criteria(state, x, last_iteration_failed, trust_radius, penalty, cg_info, self.barrier_parameter, self.tolerance): self.terminate = True return True else: g_cond = (optimality < self.tolerance and constr_violation < self.tolerance) x_cond = trust_radius < self.xtol return g_cond or x_cond def tr_interior_point(fun, grad, lagr_hess, n_vars, n_ineq, n_eq, constr, jac, x0, fun0, grad0, constr_ineq0, jac_ineq0, constr_eq0, jac_eq0, stop_criteria, enforce_feasibility, xtol, state, initial_barrier_parameter, initial_tolerance, initial_penalty, initial_trust_radius, factorization_method, finite_diff_bounds): """Trust-region interior points method. Solve problem: minimize fun(x) subject to: constr_ineq(x) <= 0 constr_eq(x) = 0 using trust-region interior point method described in [1]_. """ # BOUNDARY_PARAMETER controls the decrease on the slack # variables. Represents ``tau`` from [1]_ p.885, formula (3.18). BOUNDARY_PARAMETER = 0.995 # BARRIER_DECAY_RATIO controls the decay of the barrier parameter # and of the subproblem tolerance. Represents ``theta`` from [1]_ p.879. BARRIER_DECAY_RATIO = 0.2 # TRUST_ENLARGEMENT controls the enlargement on trust radius # after each iteration TRUST_ENLARGEMENT = 5 # Default enforce_feasibility if enforce_feasibility is None: enforce_feasibility = np.zeros(n_ineq, bool) # Initial Values barrier_parameter = initial_barrier_parameter tolerance = initial_tolerance trust_radius = initial_trust_radius # Define initial value for the slack variables s0 = np.maximum(-1.5*constr_ineq0, np.ones(n_ineq)) # Define barrier subproblem subprob = BarrierSubproblem( x0, s0, fun, grad, lagr_hess, n_vars, n_ineq, n_eq, constr, jac, barrier_parameter, tolerance, enforce_feasibility, stop_criteria, xtol, fun0, grad0, constr_ineq0, jac_ineq0, constr_eq0, jac_eq0, finite_diff_bounds) # Define initial parameter for the first iteration. z = np.hstack((x0, s0)) fun0_subprob, constr0_subprob = subprob.fun0, subprob.constr0 grad0_subprob, jac0_subprob = subprob.grad0, subprob.jac0 # Define trust region bounds trust_lb = np.hstack((np.full(subprob.n_vars, -np.inf), np.full(subprob.n_ineq, -BOUNDARY_PARAMETER))) trust_ub = np.full(subprob.n_vars+subprob.n_ineq, np.inf) # Solves a sequence of barrier problems while True: # Solve SQP subproblem z, state = equality_constrained_sqp( subprob.function_and_constraints, subprob.gradient_and_jacobian, subprob.lagrangian_hessian, z, fun0_subprob, grad0_subprob, constr0_subprob, jac0_subprob, subprob.stop_criteria, state, initial_penalty, trust_radius, factorization_method, trust_lb, trust_ub, subprob.scaling) if subprob.terminate: break # Update parameters trust_radius = max(initial_trust_radius, TRUST_ENLARGEMENT*state.tr_radius) # TODO: Use more advanced strategies from [2]_ # to update this parameters. barrier_parameter *= BARRIER_DECAY_RATIO tolerance *= BARRIER_DECAY_RATIO # Update Barrier Problem subprob.update(barrier_parameter, tolerance) # Compute initial values for next iteration fun0_subprob, constr0_subprob = subprob.function_and_constraints(z) grad0_subprob, jac0_subprob = subprob.gradient_and_jacobian(z) # Get x and s x = subprob.get_variables(z) return x, state
BarrierSubproblem
python
tensorflow__tensorflow
tensorflow/lite/python/lite_test.py
{ "start": 94455, "end": 112697 }
class ____(TestModels, parameterized.TestCase): def setUp(self): super(FromKerasFile, self).setUp() self._keras_file = None self._custom_objects = None if not context.executing_eagerly(): keras.backend.clear_session() def tearDown(self): if self._keras_file: os.remove(self._keras_file) super(FromKerasFile, self).tearDown() def _getSequentialModel(self, include_custom_layer=False): model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_shape=(3,))) if include_custom_layer: model.add(MyAddLayer(1.0)) model.add(keras.layers.RepeatVector(3)) model.add(keras.layers.TimeDistributed(keras.layers.Dense(3))) model.compile( loss=keras.losses.MSE, optimizer='sgd', metrics=[keras.metrics.categorical_accuracy], sample_weight_mode='temporal') x = np.random.random((1, 3)) y = np.random.random((1, 3, 3)) model.train_on_batch(x, y) model.predict(x) try: fd, self._keras_file = tempfile.mkstemp('.h5') keras.models.save_model(model, self._keras_file) finally: os.close(fd) if include_custom_layer: self._custom_objects = {'MyAddLayer': MyAddLayer} @parameterized.named_parameters(('_graph', context.graph_mode), ('_eager', context.eager_mode)) def testSequentialModel(self, test_context): """Test a Sequential tf.keras model with default inputs.""" with test_context(): self._getSequentialModel() converter = lite.TFLiteConverter.from_keras_model_file(self._keras_file) tflite_model = converter.convert() self.assertIsNotNone(tflite_model) # Check tensor details of converted model. interpreter = Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details() self.assertLen(input_details, 1) self.assertEndsWith(input_details[0]['name'], 'dense_input') self.assertEqual(np.float32, input_details[0]['dtype']) self.assertAllEqual([1, 3], input_details[0]['shape']) self.assertEqual((0., 0.), input_details[0]['quantization']) output_details = interpreter.get_output_details() self.assertLen(output_details, 1) self.assertEqual(np.float32, output_details[0]['dtype']) self.assertAllEqual([1, 3, 3], output_details[0]['shape']) self.assertEqual((0., 0.), output_details[0]['quantization']) # Check inference of converted model. input_data = np.array([[1, 2, 3]], dtype=np.float32) interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() tflite_result = interpreter.get_tensor(output_details[0]['index']) keras_model = keras.models.load_model(self._keras_file) keras_result = keras_model.predict(input_data) np.testing.assert_almost_equal(tflite_result, keras_result, 5) @parameterized.named_parameters(('_graph', context.graph_mode), ('_eager', context.eager_mode)) def testCustomLayer(self, test_context): """Test a Sequential tf.keras model with default inputs.""" with test_context(): self._getSequentialModel(include_custom_layer=True) converter = lite.TFLiteConverter.from_keras_model_file( self._keras_file, custom_objects=self._custom_objects) tflite_model = converter.convert() self.assertIsNotNone(tflite_model) # Check tensor details of converted model. interpreter = Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() # Check inference of converted model. input_data = np.array([[1, 2, 3]], dtype=np.float32) interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() tflite_result = interpreter.get_tensor(output_details[0]['index']) keras_model = keras.models.load_model( self._keras_file, custom_objects=self._custom_objects) keras_result = keras_model.predict(input_data) np.testing.assert_almost_equal(tflite_result, keras_result, 5) def testSequentialModelInputArray(self): """Test a Sequential tf.keras model testing input arrays argument.""" ops.disable_eager_execution() self._getSequentialModel() # Invalid input array raises error. with self.assertRaises(ValueError) as error: lite.TFLiteConverter.from_keras_model_file( self._keras_file, input_arrays=['invalid-input']) self.assertEqual("Invalid tensors 'invalid-input' were found.", str(error.exception)) # Valid input array. converter = lite.TFLiteConverter.from_keras_model_file( self._keras_file, input_arrays=['dense_input']) tflite_model = converter.convert() self.assertIsNotNone(tflite_model) def testSequentialModelInputShape(self): """Test a Sequential tf.keras model testing input shapes argument.""" self._getSequentialModel() # Passing in shape of invalid input array raises error. with self.assertRaises(ValueError) as error: converter = lite.TFLiteConverter.from_keras_model_file( self._keras_file, input_shapes={'invalid-input': [2, 3]}) self.assertEqual( "Invalid tensor 'invalid-input' found in tensor shapes map.", str(error.exception)) # Passing in shape of valid input array. converter = lite.TFLiteConverter.from_keras_model_file( self._keras_file, input_shapes={'dense_input': [2, 3]}) tflite_model = converter.convert() self.assertIsNotNone(tflite_model) # Check input shape from converted model. interpreter = Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details() self.assertLen(input_details, 1) self.assertEndsWith(input_details[0]['name'], 'dense_input') self.assertAllEqual([2, 3], input_details[0]['shape']) def testSequentialModelOutputArray(self): """Test a Sequential tf.keras model testing output arrays argument.""" ops.disable_eager_execution() self._getSequentialModel() # Invalid output array raises error. with self.assertRaises(ValueError) as error: lite.TFLiteConverter.from_keras_model_file( self._keras_file, output_arrays=['invalid-output']) self.assertEqual("Invalid tensors 'invalid-output' were found.", str(error.exception)) # Valid output array. converter = lite.TFLiteConverter.from_keras_model_file( self._keras_file, output_arrays=['time_distributed/Reshape_1']) tflite_model = converter.convert() self.assertIsNotNone(tflite_model) @parameterized.named_parameters(('_graph', context.graph_mode), ('_eager', context.eager_mode)) def testFunctionalModel(self, test_context): """Test a Functional tf.keras model with default inputs.""" with test_context(): inputs = keras.layers.Input(shape=(3,), name='input') x = keras.layers.Dense(2)(inputs) output = keras.layers.Dense(3)(x) model = keras.models.Model(inputs, output) model.compile( loss=keras.losses.MSE, optimizer='sgd', metrics=[keras.metrics.categorical_accuracy]) x = np.random.random((1, 3)) y = np.random.random((1, 3)) model.train_on_batch(x, y) model.predict(x) fd, self._keras_file = tempfile.mkstemp('.h5') try: keras.models.save_model(model, self._keras_file) finally: os.close(fd) # Convert to TFLite model. converter = lite.TFLiteConverter.from_keras_model_file(self._keras_file) tflite_model = converter.convert() self.assertIsNotNone(tflite_model) # Check tensor details of converted model. interpreter = Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details() self.assertLen(input_details, 1) self.assertEqual('input', input_details[0]['name']) self.assertEqual(np.float32, input_details[0]['dtype']) self.assertAllEqual([1, 3], input_details[0]['shape']) self.assertEqual((0., 0.), input_details[0]['quantization']) output_details = interpreter.get_output_details() self.assertLen(output_details, 1) self.assertEqual(np.float32, output_details[0]['dtype']) self.assertAllEqual([1, 3], output_details[0]['shape']) self.assertEqual((0., 0.), output_details[0]['quantization']) # Check inference of converted model. input_data = np.array([[1, 2, 3]], dtype=np.float32) interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() tflite_result = interpreter.get_tensor(output_details[0]['index']) keras_model = keras.models.load_model(self._keras_file) keras_result = keras_model.predict(input_data) np.testing.assert_almost_equal(tflite_result, keras_result, 5) def _getFunctionalModelMultipleInputs(self): a = keras.layers.Input(shape=(3,), name='input_a') b = keras.layers.Input(shape=(3,), name='input_b') dense = keras.layers.Dense(4, name='dense') c = dense(a) d = dense(b) e = keras.layers.Dropout(0.5, name='dropout')(c) model = keras.models.Model([a, b], [d, e]) model.compile( loss=keras.losses.MSE, optimizer='sgd', metrics=[keras.metrics.mae], loss_weights=[1., 0.5]) input_a_np = np.random.random((10, 3)) input_b_np = np.random.random((10, 3)) output_d_np = np.random.random((10, 4)) output_e_np = np.random.random((10, 4)) model.train_on_batch([input_a_np, input_b_np], [output_d_np, output_e_np]) model.predict([input_a_np, input_b_np], batch_size=5) fd, self._keras_file = tempfile.mkstemp('.h5') try: keras.models.save_model(model, self._keras_file) finally: os.close(fd) def testFunctionalModelMultipleInputs(self): """Test a Functional tf.keras model with multiple inputs and outputs.""" self._getFunctionalModelMultipleInputs() # Convert to TFLite model. converter = lite.TFLiteConverter.from_keras_model_file(self._keras_file) tflite_model = converter.convert() self.assertIsNotNone(tflite_model) # Check values from converted model. interpreter = Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details() self.assertLen(input_details, 2) self.assertEndsWith(input_details[0]['name'], 'input_a') self.assertEqual(np.float32, input_details[0]['dtype']) self.assertAllEqual([1, 3], input_details[0]['shape']) self.assertEqual((0., 0.), input_details[0]['quantization']) self.assertEndsWith(input_details[1]['name'], 'input_b') self.assertEqual(np.float32, input_details[1]['dtype']) self.assertAllEqual([1, 3], input_details[1]['shape']) self.assertEqual((0., 0.), input_details[1]['quantization']) output_details = interpreter.get_output_details() self.assertLen(output_details, 2) self.assertEqual(np.float32, output_details[0]['dtype']) self.assertAllEqual([1, 4], output_details[0]['shape']) self.assertEqual((0., 0.), output_details[0]['quantization']) self.assertEqual(np.float32, output_details[1]['dtype']) self.assertAllEqual([1, 4], output_details[1]['shape']) self.assertEqual((0., 0.), output_details[1]['quantization']) def testShapeOverriding(self): """Test a Functional tf.keras model with input shape overriding.""" self._getFunctionalModelMultipleInputs() # Convert to TFLite model. converter = lite.TFLiteConverter.from_keras_model_file( self._keras_file, input_shapes={ 'input_a': {2, 3}, 'input_b': {2, 3} }) tflite_model = converter.convert() self.assertIsNotNone(tflite_model) # Check values from converted model. interpreter = Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details() self.assertLen(input_details, 2) self.assertEndsWith(input_details[0]['name'], 'input_a') self.assertEqual(np.float32, input_details[0]['dtype']) self.assertAllEqual([2, 3], input_details[0]['shape']) self.assertEqual((0., 0.), input_details[0]['quantization']) self.assertEndsWith(input_details[1]['name'], 'input_b') self.assertEqual(np.float32, input_details[1]['dtype']) self.assertAllEqual([2, 3], input_details[1]['shape']) self.assertEqual((0., 0.), input_details[1]['quantization']) output_details = interpreter.get_output_details() self.assertLen(output_details, 2) self.assertEqual(np.float32, output_details[0]['dtype']) self.assertAllEqual([2, 4], output_details[0]['shape']) self.assertEqual((0., 0.), output_details[0]['quantization']) self.assertEqual(np.float32, output_details[1]['dtype']) self.assertAllEqual([2, 4], output_details[1]['shape']) self.assertEqual((0., 0.), output_details[1]['quantization']) def testPartialShapeOverriding(self): """Test a Functional tf.keras model with partial input shape overriding.""" self._getFunctionalModelMultipleInputs() # Convert to TFLite model. converter = lite.TFLiteConverter.from_keras_model_file( self._keras_file, input_shapes={'input_a': {2, 3}}) tflite_model = converter.convert() self.assertIsNotNone(tflite_model) # Check values from converted model. interpreter = Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details() self.assertLen(input_details, 2) self.assertEndsWith(input_details[0]['name'], 'input_a') self.assertEqual(np.float32, input_details[0]['dtype']) self.assertAllEqual([2, 3], input_details[0]['shape']) self.assertEqual((0., 0.), input_details[0]['quantization']) self.assertEndsWith(input_details[1]['name'], 'input_b') self.assertEqual(np.float32, input_details[1]['dtype']) self.assertAllEqual([1, 3], input_details[1]['shape']) self.assertEqual((0., 0.), input_details[1]['quantization']) output_details = interpreter.get_output_details() self.assertLen(output_details, 2) self.assertEqual(np.float32, output_details[0]['dtype']) self.assertAllEqual([1, 4], output_details[0]['shape']) self.assertEqual((0., 0.), output_details[0]['quantization']) self.assertEqual(np.float32, output_details[1]['dtype']) self.assertAllEqual([2, 4], output_details[1]['shape']) self.assertEqual((0., 0.), output_details[1]['quantization']) def testWrongShapeOverriding(self): """Test a Functional tf.keras model with wrong input shape overriding.""" self._getFunctionalModelMultipleInputs() # Convert to TFLite model. with self.assertRaises(ValueError): lite.TFLiteConverter.from_keras_model_file( self._keras_file, input_shapes={'wrong_input': {2, 3}}) def testFunctionalSequentialModel(self): """Test a Functional tf.keras model containing a Sequential model.""" model = keras.models.Sequential() model.add(keras.layers.Dense(2, input_shape=(3,))) model.add(keras.layers.RepeatVector(3)) model.add(keras.layers.TimeDistributed(keras.layers.Dense(3))) model = keras.models.Model(model.input, model.output) model.compile( loss=keras.losses.MSE, optimizer='sgd', metrics=[keras.metrics.categorical_accuracy], sample_weight_mode='temporal') x = np.random.random((1, 3)) y = np.random.random((1, 3, 3)) model.train_on_batch(x, y) model.predict(x) model.predict(x) fd, self._keras_file = tempfile.mkstemp('.h5') try: keras.models.save_model(model, self._keras_file) finally: os.close(fd) # Convert to TFLite model. converter = lite.TFLiteConverter.from_keras_model_file(self._keras_file) tflite_model = converter.convert() self.assertIsNotNone(tflite_model) # Check tensor details of converted model. interpreter = Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details() self.assertLen(input_details, 1) self.assertEndsWith(input_details[0]['name'], 'dense_input') self.assertEqual(np.float32, input_details[0]['dtype']) self.assertAllEqual([1, 3], input_details[0]['shape']) self.assertEqual((0., 0.), input_details[0]['quantization']) output_details = interpreter.get_output_details() self.assertLen(output_details, 1) self.assertEqual(np.float32, output_details[0]['dtype']) self.assertAllEqual([1, 3, 3], output_details[0]['shape']) self.assertEqual((0., 0.), output_details[0]['quantization']) # Check inference of converted model. input_data = np.array([[1, 2, 3]], dtype=np.float32) interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() tflite_result = interpreter.get_tensor(output_details[0]['index']) keras_model = keras.models.load_model(self._keras_file) keras_result = keras_model.predict(input_data) np.testing.assert_almost_equal(tflite_result, keras_result, 5) def testSequentialModelTocoConverter(self): """Test a Sequential tf.keras model with deprecated TocoConverter.""" self._getSequentialModel() converter = lite.TocoConverter.from_keras_model_file(self._keras_file) tflite_model = converter.convert() self.assertIsNotNone(tflite_model) # Ensure the model is able to load. interpreter = Interpreter(model_content=tflite_model) interpreter.allocate_tensors() @parameterized.named_parameters(('_graph', context.graph_mode), ('_eager', context.eager_mode)) def testGraphDebugInfo(self, test_context): """Test a Sequential tf.keras model has debug info captured.""" self.skipTest('TODO(b/291005679): will not be able to fix on OSS') with test_context(): self._getSequentialModel() converter = lite.TFLiteConverter.from_keras_model_file(self._keras_file) converter.convert() self.assertValidDebugInfo(converter._debug_info)
FromKerasFile
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/strategy_options.py
{ "start": 33184, "end": 45935 }
class ____(_AbstractLoad): """Represents loader options which modify the state of a ORM-enabled :class:`_sql.Select` or a legacy :class:`_query.Query` in order to affect how various mapped attributes are loaded. The :class:`_orm.Load` object is in most cases used implicitly behind the scenes when one makes use of a query option like :func:`_orm.joinedload`, :func:`_orm.defer`, or similar. It typically is not instantiated directly except for in some very specific cases. .. seealso:: :ref:`orm_queryguide_relationship_per_entity_wildcard` - illustrates an example where direct use of :class:`_orm.Load` may be useful """ __slots__ = ( "path", "context", "additional_source_entities", ) _traverse_internals = [ ("path", visitors.ExtendedInternalTraversal.dp_has_cache_key), ( "context", visitors.InternalTraversal.dp_has_cache_key_list, ), ("propagate_to_loaders", visitors.InternalTraversal.dp_boolean), ( "additional_source_entities", visitors.InternalTraversal.dp_has_cache_key_list, ), ] _cache_key_traversal = None path: PathRegistry context: Tuple[_LoadElement, ...] additional_source_entities: Tuple[_InternalEntityType[Any], ...] def __init__(self, entity: _EntityType[Any]): insp = cast("Union[Mapper[Any], AliasedInsp[Any]]", inspect(entity)) insp._post_inspect self.path = insp._path_registry self.context = () self.propagate_to_loaders = False self.additional_source_entities = () def __str__(self) -> str: return f"Load({self.path[0]})" @classmethod def _construct_for_existing_path( cls, path: _AbstractEntityRegistry ) -> Load: load = cls.__new__(cls) load.path = path load.context = () load.propagate_to_loaders = False load.additional_source_entities = () return load def _adapt_cached_option_to_uncached_option( self, context: QueryContext, uncached_opt: ORMOption ) -> ORMOption: if uncached_opt is self: return self return self._adjust_for_extra_criteria(context) def _prepend_path(self, path: PathRegistry) -> Load: cloned = self._clone() cloned.context = tuple( element._prepend_path(path) for element in self.context ) return cloned def _adjust_for_extra_criteria(self, context: QueryContext) -> Load: """Apply the current bound parameters in a QueryContext to all occurrences "extra_criteria" stored within this ``Load`` object, returning a new instance of this ``Load`` object. """ # avoid generating cache keys for the queries if we don't # actually have any extra_criteria options, which is the # common case for value in self.context: if value._extra_criteria: break else: return self replacement_cache_key = context.user_passed_query._generate_cache_key() if replacement_cache_key is None: return self orig_query = context.compile_state.select_statement orig_cache_key = orig_query._generate_cache_key() assert orig_cache_key is not None def process( opt: _LoadElement, replacement_cache_key: CacheKey, orig_cache_key: CacheKey, ) -> _LoadElement: cloned_opt = opt._clone() cloned_opt._extra_criteria = tuple( replacement_cache_key._apply_params_to_element( orig_cache_key, crit ) for crit in cloned_opt._extra_criteria ) return cloned_opt cloned = self._clone() cloned.context = tuple( ( process(value, replacement_cache_key, orig_cache_key) if value._extra_criteria else value ) for value in self.context ) return cloned def _reconcile_query_entities_with_us(self, mapper_entities, raiseerr): """called at process time to allow adjustment of the root entity inside of _LoadElement objects. """ path = self.path for ent in mapper_entities: ezero = ent.entity_zero if ezero and orm_util._entity_corresponds_to( # technically this can be a token also, but this is # safe to pass to _entity_corresponds_to() ezero, cast("_InternalEntityType[Any]", path[0]), ): return ezero return None def _process( self, compile_state: _ORMCompileState, mapper_entities: Sequence[_MapperEntity], raiseerr: bool, ) -> None: reconciled_lead_entity = self._reconcile_query_entities_with_us( mapper_entities, raiseerr ) # if the context has a current path, this is a lazy load has_current_path = bool(compile_state.compile_options._current_path) for loader in self.context: # issue #11292 # historically, propagate_to_loaders was only considered at # object loading time, whether or not to carry along options # onto an object's loaded state where it would be used by lazyload. # however, the defaultload() option needs to propagate in case # its sub-options propagate_to_loaders, but its sub-options # that dont propagate should not be applied for lazy loaders. # so we check again if has_current_path and not loader.propagate_to_loaders: continue loader.process_compile_state( self, compile_state, mapper_entities, reconciled_lead_entity, raiseerr, ) def _apply_to_parent(self, parent: Load) -> None: """apply this :class:`_orm.Load` object as a sub-option of another :class:`_orm.Load` object. This method is used by the :meth:`_orm.Load.options` method. """ cloned = self._generate() assert cloned.propagate_to_loaders == self.propagate_to_loaders if not any( orm_util._entity_corresponds_to_use_path_impl( elem, cloned.path.odd_element(0) ) for elem in (parent.path.odd_element(-1),) + parent.additional_source_entities ): if len(cloned.path) > 1: attrname = cloned.path[1] parent_entity = cloned.path[0] else: attrname = cloned.path[0] parent_entity = cloned.path[0] _raise_for_does_not_link(parent.path, attrname, parent_entity) cloned.path = PathRegistry.coerce(parent.path[0:-1] + cloned.path[:]) if self.context: cloned.context = tuple( value._prepend_path_from(parent) for value in self.context ) if cloned.context: parent.context += cloned.context parent.additional_source_entities += ( cloned.additional_source_entities ) @_generative def options(self, *opts: _AbstractLoad) -> Self: r"""Apply a series of options as sub-options to this :class:`_orm.Load` object. E.g.:: query = session.query(Author) query = query.options( joinedload(Author.book).options( load_only(Book.summary, Book.excerpt), joinedload(Book.citations).options(joinedload(Citation.author)), ) ) :param \*opts: A series of loader option objects (ultimately :class:`_orm.Load` objects) which should be applied to the path specified by this :class:`_orm.Load` object. .. seealso:: :func:`.defaultload` :ref:`orm_queryguide_relationship_sub_options` """ for opt in opts: try: opt._apply_to_parent(self) except AttributeError as ae: if not isinstance(opt, _AbstractLoad): raise sa_exc.ArgumentError( f"Loader option {opt} is not compatible with the " "Load.options() method." ) from ae else: raise return self def _clone_for_bind_strategy( self, attrs: Optional[Tuple[_AttrType, ...]], strategy: Optional[_StrategyKey], wildcard_key: Optional[_WildcardKeyType], opts: Optional[_OptsType] = None, attr_group: Optional[_AttrGroupType] = None, propagate_to_loaders: bool = True, reconcile_to_other: Optional[bool] = None, extra_criteria: Optional[Tuple[Any, ...]] = None, ) -> Self: # for individual strategy that needs to propagate, set the whole # Load container to also propagate, so that it shows up in # InstanceState.load_options if propagate_to_loaders: self.propagate_to_loaders = True if self.path.is_token: raise sa_exc.ArgumentError( "Wildcard token cannot be followed by another entity" ) elif path_is_property(self.path): # re-use the lookup which will raise a nicely formatted # LoaderStrategyException if strategy: self.path.prop._strategy_lookup(self.path.prop, strategy[0]) else: raise sa_exc.ArgumentError( f"Mapped attribute '{self.path.prop}' does not " "refer to a mapped entity" ) if attrs is None: load_element = _ClassStrategyLoad.create( self.path, None, strategy, wildcard_key, opts, propagate_to_loaders, attr_group=attr_group, reconcile_to_other=reconcile_to_other, extra_criteria=extra_criteria, ) if load_element: self.context += (load_element,) assert opts is not None self.additional_source_entities += cast( "Tuple[_InternalEntityType[Any]]", opts["entities"] ) else: for attr in attrs: if isinstance(attr, str): load_element = _TokenStrategyLoad.create( self.path, attr, strategy, wildcard_key, opts, propagate_to_loaders, attr_group=attr_group, reconcile_to_other=reconcile_to_other, extra_criteria=extra_criteria, ) else: load_element = _AttributeStrategyLoad.create( self.path, attr, strategy, wildcard_key, opts, propagate_to_loaders, attr_group=attr_group, reconcile_to_other=reconcile_to_other, extra_criteria=extra_criteria, ) if load_element: # for relationship options, update self.path on this Load # object with the latest path. if wildcard_key is _RELATIONSHIP_TOKEN: self.path = load_element.path self.context += (load_element,) # this seems to be effective for selectinloader, # giving the extra match to one more level deep. # but does not work for immediateloader, which still # must add additional options at load time if load_element.local_opts.get("recursion_depth", False): r1 = load_element._recurse() self.context += (r1,) return self def __getstate__(self): d = self._shallow_to_dict() d["path"] = self.path.serialize() return d def __setstate__(self, state): state["path"] = PathRegistry.deserialize(state["path"]) self._shallow_from_dict(state)
Load
python
apache__airflow
providers/cncf/kubernetes/tests/unit/cncf/kubernetes/executors/test_kubernetes_executor.py
{ "start": 10702, "end": 67616 }
class ____: """ Tests if an ApiException from the Kube Client will cause the task to be rescheduled. """ def setup_method(self) -> None: self.kubernetes_executor = KubernetesExecutor() self.kubernetes_executor.job_id = 5 @pytest.mark.skipif( AirflowKubernetesScheduler is None, reason="kubernetes python package is not installed" ) @pytest.mark.parametrize( ("response", "task_publish_max_retries", "should_requeue", "task_expected_state"), [ pytest.param( HTTPResponse(body='{"message": "any message"}', status=400), 0, False, State.FAILED, id="400 BadRequest", ), pytest.param( HTTPResponse(body='{"message": "any message"}', status=400), 1, False, State.FAILED, id="400 BadRequest (task_publish_max_retries=1)", ), pytest.param( HTTPResponse(body='{"message": "any message"}', status=403), 0, False, State.FAILED, id="403 Forbidden (permission denied)", ), pytest.param( HTTPResponse(body='{"message": "any message"}', status=403), 1, False, State.FAILED, id="403 Forbidden (permission denied) (task_publish_max_retries=1)", ), pytest.param( HTTPResponse( body='{"message": "pods pod1 is forbidden: exceeded quota: ' "resouece-quota, requested: pods=1, used: pods=10, " 'limited: pods=10"}', status=403, ), 0, False, State.FAILED, id="403 Forbidden (exceeded quota)", ), pytest.param( HTTPResponse( body='{"message": "pods pod1 is forbidden: exceeded quota: ' "resouece-quota, requested: pods=1, used: pods=10, " 'limited: pods=10"}', status=403, ), 1, True, State.SUCCESS, id="403 Forbidden (exceeded quota) (task_publish_max_retries=1) (retry succeeded)", ), pytest.param( HTTPResponse( body='{"message": "pods pod1 is forbidden: exceeded quota: ' "resouece-quota, requested: pods=1, used: pods=10, " 'limited: pods=10"}', status=403, ), 1, True, State.FAILED, id="403 Forbidden (exceeded quota) (task_publish_max_retries=1) (retry failed)", ), pytest.param( HTTPResponse(body='{"message": "any message"}', status=404), 0, False, State.FAILED, id="404 Not Found", ), pytest.param( HTTPResponse(body='{"message": "any message"}', status=404), 1, False, State.FAILED, id="404 Not Found (task_publish_max_retries=1)", ), pytest.param( HTTPResponse(body='{"message": "any message"}', status=422), 0, False, State.FAILED, id="422 Unprocessable Entity", ), pytest.param( HTTPResponse(body='{"message": "any message"}', status=422), 1, False, State.FAILED, id="422 Unprocessable Entity (task_publish_max_retries=1)", ), pytest.param( HTTPResponse(body='{"message": "any message"}', status=12345), 0, False, State.FAILED, id="12345 fake-unhandled-reason", ), pytest.param( HTTPResponse(body='{"message": "any message"}', status=12345), 1, False, State.FAILED, id="12345 fake-unhandled-reason (task_publish_max_retries=1) (retry succeeded)", ), pytest.param( HTTPResponse(body='{"message": "any message"}', status=12345), 1, False, State.FAILED, id="12345 fake-unhandled-reason (task_publish_max_retries=1) (retry failed)", ), pytest.param( HTTPResponse( body='{"message": "the object has been modified; please apply your changes to the latest version and try again"}', status=409, ), 1, True, State.SUCCESS, id="409 conflict", ), pytest.param( HTTPResponse(body="Too many requests, please try again later.", status=429), 0, False, State.FAILED, id="429 Too Many Requests (non-JSON body)", ), pytest.param( HTTPResponse(body="Too many requests, please try again later.", status=429), 1, False, State.FAILED, id="429 Too Many Requests (non-JSON body) (task_publish_max_retries=1)", ), pytest.param( HTTPResponse(body="", status=429), 0, False, State.FAILED, id="429 Too Many Requests (empty body)", ), pytest.param( HTTPResponse( body='{"message": "Internal error occurred: failed calling webhook \\"mutation.azure-workload-identity.io\\": failed to call webhook: Post \\"https://azure-wi-webhook-webhook-service.kube-system.svc:443/mutate-v1-pod?timeout=10s\\""}', status=500, ), 1, True, State.SUCCESS, id="500 Internal Server Error (webhook failure)", ), pytest.param( HTTPResponse( body='{"message": "Internal error occurred: failed calling webhook"}', status=500, ), 1, True, State.FAILED, id="500 Internal Server Error (webhook failure) (retry failed)", ), ], ) @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.KubernetesJobWatcher") @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") def test_run_next_exception_requeue( self, mock_get_kube_client, mock_kubernetes_job_watcher, response, task_publish_max_retries, should_requeue, task_expected_state, data_file, ): """ When pod scheduling fails with any reason not yet handled in the relevant try-except block and task publish retries not exhausted, the task should stay in the ``task_queue`` and be attempted on a subsequent executor sync. When reason is 'Unprocessable Entity' or 'BadRequest' or task publish retries exhausted, the task should be failed without being re-queued. Note on error scenarios: - 400 BadRequest will returns in scenarios like - your request parameters are invalid e.g. asking for cpu=100ABC123. - 403 Forbidden will returns in scenarios like - your request exceeds the namespace quota - scheduler role doesn't have permission to launch the pod - 404 Not Found will returns in scenarios like - your requested namespace doesn't exists - 422 Unprocessable Entity will returns in scenarios like - your request parameters are valid but unsupported e.g. limits lower than requests. - 500 Internal Server Error will returns in scenarios like - failed calling webhook - typically transient API server or webhook service issues - should be retried if task_publish_max_retries > 0 """ template_file = data_file("pods/generator_base_with_secrets.yaml").as_posix() # A mock kube_client that throws errors when making a pod mock_kube_client = mock.patch("kubernetes.client.CoreV1Api", autospec=True) mock_kube_client.create_namespaced_pod = mock.MagicMock(side_effect=ApiException(http_resp=response)) mock_get_kube_client.return_value = mock_kube_client mock_api_client = mock.MagicMock() mock_api_client.sanitize_for_serialization.return_value = {} mock_kube_client.api_client = mock_api_client config = { ("kubernetes_executor", "pod_template_file"): template_file, } with conf_vars(config): kubernetes_executor = self.kubernetes_executor kubernetes_executor.task_publish_max_retries = task_publish_max_retries kubernetes_executor.start() try: # Execute a task while the Api Throws errors try_number = 1 task_instance_key = TaskInstanceKey("dag", "task", "run_id", try_number) kubernetes_executor.execute_async( key=task_instance_key, queue=None, command=["airflow", "tasks", "run", "true", "some_parameter"], ) kubernetes_executor.sync() assert mock_kube_client.create_namespaced_pod.call_count == 1 if should_requeue: assert not kubernetes_executor.task_queue.empty() # Disable the ApiException if task_expected_state == State.SUCCESS: mock_kube_client.create_namespaced_pod.side_effect = None # Execute the task without errors should empty the queue mock_kube_client.create_namespaced_pod.reset_mock() kubernetes_executor.sync() assert mock_kube_client.create_namespaced_pod.called assert kubernetes_executor.task_queue.empty() if task_expected_state != State.SUCCESS: assert kubernetes_executor.event_buffer[task_instance_key][0] == task_expected_state else: assert kubernetes_executor.task_queue.empty() assert kubernetes_executor.event_buffer[task_instance_key][0] == task_expected_state finally: kubernetes_executor.end() @pytest.mark.skipif( AirflowKubernetesScheduler is None, reason="kubernetes python package is not installed" ) @mock.patch("airflow.settings.pod_mutation_hook") @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") def test_run_next_pmh_error(self, mock_get_kube_client, mock_pmh): """ Exception during Pod Mutation Hook execution should be handled gracefully. """ exception_in_pmh = Exception("Purposely generate error for test") mock_pmh.side_effect = exception_in_pmh mock_kube_client = mock.patch("kubernetes.client.CoreV1Api", autospec=True) mock_kube_client.create_namespaced_pod = mock.MagicMock() mock_get_kube_client.return_value = mock_kube_client kubernetes_executor = self.kubernetes_executor kubernetes_executor.start() try: try_number = 1 task_instance_key = TaskInstanceKey("dag", "task", "run_id", try_number) kubernetes_executor.execute_async( key=task_instance_key, queue=None, command=["airflow", "tasks", "run", "true", "some_parameter"], ) kubernetes_executor.sync() # The pod_mutation_hook should have been called once. assert mock_pmh.call_count == 1 # There should be no pod creation request sent assert mock_kube_client.create_namespaced_pod.call_count == 0 # The task is not re-queued and there is the failed record in event_buffer assert kubernetes_executor.task_queue.empty() assert kubernetes_executor.event_buffer[task_instance_key][0] == State.FAILED assert kubernetes_executor.event_buffer[task_instance_key][1].__cause__ == exception_in_pmh finally: kubernetes_executor.end() @pytest.mark.skipif( AirflowKubernetesScheduler is None, reason="kubernetes python package is not installed" ) @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.KubernetesJobWatcher") @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") def test_run_next_pod_reconciliation_error( self, mock_get_kube_client, mock_kubernetes_job_watcher, data_file ): """ When construct_pod raises PodReconciliationError, we should fail the task. """ template_file = data_file("pods/generator_base_with_secrets.yaml").as_posix() mock_kube_client = mock.patch("kubernetes.client.CoreV1Api", autospec=True) fail_msg = "test message" mock_kube_client.create_namespaced_pod = mock.MagicMock(side_effect=PodReconciliationError(fail_msg)) mock_get_kube_client.return_value = mock_kube_client mock_api_client = mock.MagicMock() mock_api_client.sanitize_for_serialization.return_value = {} mock_kube_client.api_client = mock_api_client config = {("kubernetes_executor", "pod_template_file"): template_file} with conf_vars(config): kubernetes_executor = self.kubernetes_executor kubernetes_executor.start() try: # Execute a task while the Api Throws errors try_number = 1 task_instance_key = TaskInstanceKey("dag", "task", "run_id", try_number) kubernetes_executor.execute_async( key=task_instance_key, queue=None, command=["airflow", "tasks", "run", "true", "some_parameter"], ) kubernetes_executor.sync() assert kubernetes_executor.task_queue.empty() assert kubernetes_executor.event_buffer[task_instance_key][0] == State.FAILED assert kubernetes_executor.event_buffer[task_instance_key][1].args[0] == fail_msg finally: kubernetes_executor.end() @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor.KubeConfig") @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor.KubernetesExecutor.sync") @mock.patch("airflow.executors.base_executor.BaseExecutor.trigger_tasks") @mock.patch("airflow.executors.base_executor.Stats.gauge") def test_gauge_executor_metrics(self, mock_stats_gauge, mock_trigger_tasks, mock_sync, mock_kube_config): executor = self.kubernetes_executor executor.heartbeat() calls = [ mock.call( "executor.open_slots", value=mock.ANY, tags={"status": "open", "name": "KubernetesExecutor"} ), mock.call( "executor.queued_tasks", value=mock.ANY, tags={"status": "queued", "name": "KubernetesExecutor"}, ), mock.call( "executor.running_tasks", value=mock.ANY, tags={"status": "running", "name": "KubernetesExecutor"}, ), ] mock_stats_gauge.assert_has_calls(calls) @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.KubernetesJobWatcher") @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") def test_invalid_executor_config(self, mock_get_kube_client, mock_kubernetes_job_watcher): executor = self.kubernetes_executor executor.start() try: assert executor.event_buffer == {} executor.execute_async( key=("dag", "task", timezone.utcnow(), 1), queue=None, command=["airflow", "tasks", "run", "true", "some_parameter"], executor_config=k8s.V1Pod( spec=k8s.V1PodSpec( containers=[k8s.V1Container(name="base", image="myimage", image_pull_policy="Always")] ) ), ) assert next(iter(executor.event_buffer.values()))[1] == "Invalid executor_config passed" finally: executor.end() @pytest.mark.execution_timeout(10) @pytest.mark.skipif( AirflowKubernetesScheduler is None, reason="kubernetes python package is not installed" ) @mock.patch( "airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.AirflowKubernetesScheduler.run_pod_async" ) @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") def test_pod_template_file_override_in_executor_config( self, mock_get_kube_client, mock_run_pod_async, data_file ): executor_template_file = data_file("executor/basic_template.yaml") mock_kube_client = mock.patch("kubernetes.client.CoreV1Api", autospec=True) mock_get_kube_client.return_value = mock_kube_client with conf_vars({("kubernetes_executor", "pod_template_file"): None}): executor = self.kubernetes_executor executor.start() try: assert executor.event_buffer == {} assert executor.task_queue.empty() executor.execute_async( key=TaskInstanceKey("dag", "task", "run_id", 1), queue=None, command=["airflow", "tasks", "run", "true", "some_parameter"], executor_config={ "pod_template_file": executor_template_file, "pod_override": k8s.V1Pod( metadata=k8s.V1ObjectMeta(labels={"release": "stable"}), spec=k8s.V1PodSpec( containers=[k8s.V1Container(name="base", image="airflow:3.6")], ), ), }, ) assert not executor.task_queue.empty() task = executor.task_queue.get_nowait() _, _, expected_executor_config, expected_pod_template_file = task executor.task_queue.task_done() # Test that the correct values have been put to queue assert expected_executor_config.metadata.labels == {"release": "stable"} assert expected_pod_template_file == executor_template_file self.kubernetes_executor.kube_scheduler.run_next(task) mock_run_pod_async.assert_called_once_with( k8s.V1Pod( api_version="v1", kind="Pod", metadata=k8s.V1ObjectMeta( name=mock.ANY, namespace="default", annotations={ "dag_id": "dag", "run_id": "run_id", "task_id": "task", "try_number": "1", }, labels={ "airflow-worker": "5", "airflow_version": mock.ANY, "dag_id": "dag", "run_id": "run_id", "kubernetes_executor": "True", "mylabel": "foo", "release": "stable", "task_id": "task", "try_number": "1", }, ), spec=k8s.V1PodSpec( containers=[ k8s.V1Container( name="base", image="airflow:3.6", args=["airflow", "tasks", "run", "true", "some_parameter"], env=[k8s.V1EnvVar(name="AIRFLOW_IS_K8S_EXECUTOR_POD", value="True")], ) ], image_pull_secrets=[ k8s.V1LocalObjectReference(name="all-right-then-keep-your-secrets") ], scheduler_name="default-scheduler", security_context=k8s.V1PodSecurityContext(fs_group=50000, run_as_user=50001), ), ) ) finally: executor.end() @pytest.mark.db_test @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.KubernetesJobWatcher") @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") def test_change_state_running(self, mock_get_kube_client, mock_kubernetes_job_watcher): executor = self.kubernetes_executor executor.start() try: key = TaskInstanceKey(dag_id="dag_id", task_id="task_id", run_id="run_id", try_number=1) executor.running = {key} results = KubernetesResults(key, State.RUNNING, "pod_name", "default", "resource_version", None) executor._change_state(results) assert executor.event_buffer[key][0] == State.RUNNING assert executor.running == {key} finally: executor.end() @pytest.mark.db_test @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.KubernetesJobWatcher") @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") @mock.patch( "airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.AirflowKubernetesScheduler.delete_pod" ) def test_change_state_success(self, mock_delete_pod, mock_get_kube_client, mock_kubernetes_job_watcher): executor = self.kubernetes_executor executor.start() try: key = TaskInstanceKey(dag_id="dag_id", task_id="task_id", run_id="run_id", try_number=2) executor.running = {key} results = KubernetesResults(key, State.SUCCESS, "pod_name", "default", "resource_version", None) executor._change_state(results) assert executor.event_buffer[key][0] == State.SUCCESS assert executor.running == set() mock_delete_pod.assert_called_once_with(pod_name="pod_name", namespace="default") finally: executor.end() @pytest.mark.db_test @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.KubernetesJobWatcher") @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") @mock.patch( "airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.AirflowKubernetesScheduler" ) def test_change_state_failed_no_deletion( self, mock_kubescheduler, mock_get_kube_client, mock_kubernetes_job_watcher ): mock_delete_pod = mock_kubescheduler.return_value.delete_pod mock_patch_pod = mock_kubescheduler.return_value.patch_pod_executor_done executor = self.kubernetes_executor executor.kube_config.delete_worker_pods = False executor.kube_config.delete_worker_pods_on_failure = False executor.start() try: key = TaskInstanceKey(dag_id="dag_id", task_id="task_id", run_id="run_id", try_number=3) executor.running = {key} results = KubernetesResults( key, State.FAILED, "pod_id", "test-namespace", "resource_version", None ) executor._change_state(results) assert executor.event_buffer[key][0] == State.FAILED assert executor.running == set() mock_delete_pod.assert_not_called() mock_patch_pod.assert_called_once_with(pod_name="pod_id", namespace="test-namespace") finally: executor.end() @pytest.mark.db_test @pytest.mark.parametrize( "ti_state", [TaskInstanceState.SUCCESS, TaskInstanceState.FAILED, TaskInstanceState.DEFERRED] ) @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.KubernetesJobWatcher") @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") @mock.patch( "airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.AirflowKubernetesScheduler.delete_pod" ) def test_change_state_none( self, mock_delete_pod, mock_get_kube_client, mock_kubernetes_job_watcher, ti_state, create_task_instance, ): """Ensure that when change_state gets state=None, it looks up the TI state from the db""" executor = self.kubernetes_executor executor.start() try: ti = create_task_instance(state=ti_state) key = ti.key executor.running = {key} results = KubernetesResults(key, None, "pod_name", "default", "resource_version", None) executor._change_state(results) assert executor.event_buffer[key][0] == ti_state assert executor.running == set() mock_delete_pod.assert_called_once_with(pod_name="pod_name", namespace="default") finally: executor.end() @pytest.mark.db_test @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.KubernetesJobWatcher") @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") @mock.patch( "airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.AirflowKubernetesScheduler.delete_pod" ) def test_change_state_adopted(self, mock_delete_pod, mock_get_kube_client, mock_kubernetes_job_watcher): executor = self.kubernetes_executor executor.start() try: key = TaskInstanceKey(dag_id="dag_id", task_id="task_id", run_id="run_id", try_number=2) executor.running = {key} results = KubernetesResults(key, ADOPTED, "pod_name", "default", "resource_version", None) executor._change_state(results) assert len(executor.event_buffer) == 0 assert len(executor.running) == 0 mock_delete_pod.assert_not_called() finally: executor.end() @pytest.mark.db_test @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.KubernetesJobWatcher") @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") def test_change_state_key_not_in_running(self, mock_get_kube_client, mock_kubernetes_job_watcher): executor = self.kubernetes_executor executor.start() try: key = TaskInstanceKey(dag_id="dag_id", task_id="task_id", run_id="run_id", try_number=1) executor.running = set() results = KubernetesResults(key, State.SUCCESS, "pod_name", "default", "resource_version", None) executor._change_state(results) assert executor.event_buffer.get(key) is None assert executor.running == set() finally: executor.end() @pytest.mark.parametrize( ("multi_namespace_mode_namespace_list", "watchers_keys"), [ pytest.param(["A", "B", "C"], ["A", "B", "C"]), pytest.param(None, ["ALL_NAMESPACES"]), ], ) @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") def test_watchers_under_multi_namespace_mode( self, mock_get_kube_client, multi_namespace_mode_namespace_list, watchers_keys ): executor = self.kubernetes_executor executor.kube_config.multi_namespace_mode = True executor.kube_config.multi_namespace_mode_namespace_list = multi_namespace_mode_namespace_list executor.start() try: assert list(executor.kube_scheduler.kube_watchers.keys()) == watchers_keys assert all( isinstance(v, KubernetesJobWatcher) for v in executor.kube_scheduler.kube_watchers.values() ) finally: executor.end() @pytest.mark.db_test @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.KubernetesJobWatcher") @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") @mock.patch( "airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.AirflowKubernetesScheduler" ) def test_change_state_skip_pod_deletion( self, mock_kubescheduler, mock_get_kube_client, mock_kubernetes_job_watcher ): mock_delete_pod = mock_kubescheduler.return_value.delete_pod mock_patch_pod = mock_kubescheduler.return_value.patch_pod_executor_done executor = self.kubernetes_executor executor.kube_config.delete_worker_pods = False executor.kube_config.delete_worker_pods_on_failure = False executor.start() try: key = TaskInstanceKey(dag_id="dag_id", task_id="task_id", run_id="run_id", try_number=2) executor.running = {key} results = KubernetesResults( key, State.SUCCESS, "pod_name", "test-namespace", "resource_version", None ) executor._change_state(results) assert executor.event_buffer[key][0] == State.SUCCESS assert executor.running == set() mock_delete_pod.assert_not_called() mock_patch_pod.assert_called_once_with(pod_name="pod_name", namespace="test-namespace") finally: executor.end() @pytest.mark.db_test @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.KubernetesJobWatcher") @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") @mock.patch( "airflow.providers.cncf.kubernetes.executors.kubernetes_executor_utils.AirflowKubernetesScheduler" ) def test_change_state_failed_pod_deletion( self, mock_kubescheduler, mock_get_kube_client, mock_kubernetes_job_watcher ): mock_delete_pod = mock_kubescheduler.return_value.delete_pod mock_patch_pod = mock_kubescheduler.return_value.patch_pod_executor_done executor = self.kubernetes_executor executor.kube_config.delete_worker_pods_on_failure = True executor.start() try: key = TaskInstanceKey(dag_id="dag_id", task_id="task_id", run_id="run_id", try_number=2) executor.running = {key} results = KubernetesResults( key, State.FAILED, "pod_name", "test-namespace", "resource_version", None ) executor._change_state(results) assert executor.event_buffer[key][0] == State.FAILED assert executor.running == set() mock_delete_pod.assert_called_once_with(pod_name="pod_name", namespace="test-namespace") mock_patch_pod.assert_not_called() finally: executor.end() @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor.DynamicClient") @mock.patch( "airflow.providers.cncf.kubernetes.executors.kubernetes_executor.KubernetesExecutor.adopt_launched_task" ) @mock.patch( "airflow.providers.cncf.kubernetes.executors.kubernetes_executor.KubernetesExecutor._adopt_completed_pods" ) def test_try_adopt_task_instances( self, mock_adopt_completed_pods, mock_adopt_launched_task, mock_kube_dynamic_client ): executor = self.kubernetes_executor executor.scheduler_job_id = "10" ti_key = annotations_to_key( { "dag_id": "dag", "run_id": "run_id", "task_id": "task", "try_number": "1", } ) mock_ti = mock.MagicMock(queued_by_job_id="1", external_executor_id="1", key=ti_key) pod = k8s.V1Pod(metadata=k8s.V1ObjectMeta(name="foo")) mock_kube_client = mock.MagicMock() executor.kube_client = mock_kube_client mock_kube_dynamic_client.return_value = mock.MagicMock() mock_pod_resource = mock.MagicMock() mock_kube_dynamic_client.return_value.resources.get.return_value = mock_pod_resource mock_kube_dynamic_client.return_value.get.return_value.items = [pod] # First adoption reset_tis = executor.try_adopt_task_instances([mock_ti]) mock_kube_dynamic_client.return_value.get.assert_called_once_with( resource=mock_pod_resource, namespace="default", field_selector="status.phase!=Succeeded", label_selector="kubernetes_executor=True,airflow-worker=1,airflow_executor_done!=True", header_params={"Accept": "application/json;as=PartialObjectMetadataList;v=v1;g=meta.k8s.io"}, ) mock_adopt_launched_task.assert_called_once_with(mock_kube_client, pod, {ti_key: mock_ti}) mock_adopt_completed_pods.assert_called_once() assert reset_tis == [mock_ti] # assume failure adopting when checking return # Second adoption (queued_by_job_id and external_executor_id no longer match) mock_kube_dynamic_client.return_value.reset_mock() mock_adopt_launched_task.reset_mock() mock_adopt_completed_pods.reset_mock() mock_ti.queued_by_job_id = "10" # scheduler_job would have updated this after the first adoption executor.scheduler_job_id = "20" # assume success adopting, `adopt_launched_task` pops `ti_key` from `tis_to_flush_by_key` mock_adopt_launched_task.side_effect = ( lambda client, pod, tis_to_flush_by_key: tis_to_flush_by_key.pop(ti_key) ) reset_tis = executor.try_adopt_task_instances([mock_ti]) mock_kube_dynamic_client.return_value.get.assert_called_once_with( resource=mock_pod_resource, namespace="default", field_selector="status.phase!=Succeeded", label_selector="kubernetes_executor=True,airflow-worker=10,airflow_executor_done!=True", header_params={"Accept": "application/json;as=PartialObjectMetadataList;v=v1;g=meta.k8s.io"}, ) mock_adopt_launched_task.assert_called_once() # Won't check args this time around as they get mutated mock_adopt_completed_pods.assert_called_once() assert reset_tis == [] # This time our return is empty - no TIs to reset @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor.DynamicClient") @mock.patch( "airflow.providers.cncf.kubernetes.executors.kubernetes_executor.KubernetesExecutor._adopt_completed_pods" ) def test_try_adopt_task_instances_multiple_scheduler_ids( self, mock_adopt_completed_pods, mock_kube_dynamic_client ): """We try to find pods only once per scheduler id""" executor = self.kubernetes_executor mock_kube_client = mock.MagicMock() executor.kube_client = mock_kube_client mock_kube_dynamic_client.return_value = mock.MagicMock() mock_pod_resource = mock.MagicMock() mock_kube_dynamic_client.return_value.resources.get.return_value = mock_pod_resource mock_tis = [ mock.MagicMock(queued_by_job_id="10", external_executor_id="1", dag_id="dag", task_id="task"), mock.MagicMock(queued_by_job_id="40", external_executor_id="1", dag_id="dag", task_id="task2"), mock.MagicMock(queued_by_job_id="40", external_executor_id="1", dag_id="dag", task_id="task3"), ] executor.try_adopt_task_instances(mock_tis) assert mock_kube_dynamic_client.return_value.get.call_count == 2 mock_kube_dynamic_client.return_value.get.assert_has_calls( [ mock.call( resource=mock_pod_resource, namespace="default", field_selector="status.phase!=Succeeded", label_selector="kubernetes_executor=True,airflow-worker=10,airflow_executor_done!=True", header_params={ "Accept": "application/json;as=PartialObjectMetadataList;v=v1;g=meta.k8s.io" }, ), mock.call( resource=mock_pod_resource, namespace="default", field_selector="status.phase!=Succeeded", label_selector="kubernetes_executor=True,airflow-worker=40,airflow_executor_done!=True", header_params={ "Accept": "application/json;as=PartialObjectMetadataList;v=v1;g=meta.k8s.io" }, ), ], any_order=True, ) @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor.DynamicClient") @mock.patch( "airflow.providers.cncf.kubernetes.executors.kubernetes_executor.KubernetesExecutor.adopt_launched_task" ) @mock.patch( "airflow.providers.cncf.kubernetes.executors.kubernetes_executor.KubernetesExecutor._adopt_completed_pods" ) def test_try_adopt_task_instances_no_matching_pods( self, mock_adopt_completed_pods, mock_adopt_launched_task, mock_kube_dynamic_client ): executor = self.kubernetes_executor mock_ti = mock.MagicMock(queued_by_job_id="1", external_executor_id="1", dag_id="dag", task_id="task") mock_kube_client = mock.MagicMock() executor.kube_client = mock_kube_client mock_kube_dynamic_client.return_value = mock.MagicMock() mock_kube_dynamic_client.return_value.get.return_value.items = [] tis_to_flush = executor.try_adopt_task_instances([mock_ti]) assert tis_to_flush == [mock_ti] assert executor.running == set() mock_adopt_launched_task.assert_not_called() mock_adopt_completed_pods.assert_called_once() @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor.DynamicClient") @mock.patch( "airflow.providers.cncf.kubernetes.executors.kubernetes_executor.KubernetesExecutor.adopt_launched_task" ) @mock.patch( "airflow.providers.cncf.kubernetes.executors.kubernetes_executor.KubernetesExecutor._adopt_completed_pods" ) def test_try_adopt_already_adopted_task_instances( self, mock_adopt_completed_pods, mock_adopt_launched_task, mock_kube_dynamic_client ): """For TIs that are already adopted, we should not flush them""" mock_kube_dynamic_client.return_value = mock.MagicMock() mock_kube_dynamic_client.return_value.get.return_value.items = [] mock_kube_client = mock.MagicMock() executor = self.kubernetes_executor executor.kube_client = mock_kube_client ti_key = TaskInstanceKey("dag", "task", "run_id", 1) mock_ti = mock.MagicMock(queued_by_job_id="1", external_executor_id="1", key=ti_key) executor.running = {ti_key} tis_to_flush = executor.try_adopt_task_instances([mock_ti]) mock_adopt_launched_task.assert_not_called() mock_adopt_completed_pods.assert_called_once() assert tis_to_flush == [] assert executor.running == {ti_key} @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") def test_adopt_launched_task(self, mock_kube_client): executor = self.kubernetes_executor executor.scheduler_job_id = "modified" annotations = { "dag_id": "dag", "run_id": "run_id", "task_id": "task", "try_number": "1", } ti_key = annotations_to_key(annotations) pod = k8s.V1Pod( metadata=k8s.V1ObjectMeta(name="foo", labels={"airflow-worker": "bar"}, annotations=annotations) ) tis_to_flush_by_key = {ti_key: {}} executor.adopt_launched_task(mock_kube_client, pod=pod, tis_to_flush_by_key=tis_to_flush_by_key) mock_kube_client.patch_namespaced_pod.assert_called_once_with( body={"metadata": {"labels": {"airflow-worker": "modified"}}}, name="foo", namespace=None, ) assert tis_to_flush_by_key == {} assert executor.running == {ti_key} @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") def test_adopt_launched_task_api_exception(self, mock_kube_client): """We shouldn't think we are running the task if aren't able to patch the pod""" executor = self.kubernetes_executor executor.scheduler_job_id = "modified" annotations = { "dag_id": "dag", "run_id": "run_id", "task_id": "task", "try_number": "1", } ti_key = annotations_to_key(annotations) pod = k8s.V1Pod(metadata=k8s.V1ObjectMeta(name="foo", annotations=annotations)) tis_to_flush_by_key = {ti_key: {}} mock_kube_client.patch_namespaced_pod.side_effect = ApiException(status=400) executor.adopt_launched_task(mock_kube_client, pod=pod, tis_to_flush_by_key=tis_to_flush_by_key) mock_kube_client.patch_namespaced_pod.assert_called_once_with( body={"metadata": {"labels": {"airflow-worker": "modified"}}}, name="foo", namespace=None, ) assert tis_to_flush_by_key == {ti_key: {}} assert executor.running == set() @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor.DynamicClient") @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") def test_adopt_completed_pods(self, mock_kube_client, mock_kube_dynamic_client): """We should adopt all completed pods from other schedulers""" executor = self.kubernetes_executor executor.scheduler_job_id = "modified" executor.kube_client = mock_kube_client mock_kube_dynamic_client.return_value = mock.MagicMock() mock_pod_resource = mock.MagicMock() mock_kube_dynamic_client.return_value.resources.get.return_value = mock_pod_resource mock_kube_dynamic_client.return_value.get.return_value.items = [] executor.kube_config.kube_namespace = "somens" pod_names = ["one", "two"] def get_annotations(pod_name): return { "dag_id": "dag", "run_id": "run_id", "task_id": pod_name, "try_number": "1", } mock_kube_dynamic_client.return_value.get.return_value.items = [ k8s.V1Pod( metadata=k8s.V1ObjectMeta( name=pod_name, labels={"airflow-worker": pod_name}, annotations=get_annotations(pod_name), namespace="somens", ) ) for pod_name in pod_names ] expected_running_ti_keys = {annotations_to_key(get_annotations(pod_name)) for pod_name in pod_names} executor._adopt_completed_pods(mock_kube_client) mock_kube_dynamic_client.return_value.get.assert_called_once_with( resource=mock_pod_resource, namespace="somens", field_selector="status.phase=Succeeded", label_selector="kubernetes_executor=True,airflow-worker!=modified,airflow_executor_done!=True", header_params={"Accept": "application/json;as=PartialObjectMetadataList;v=v1;g=meta.k8s.io"}, ) assert len(pod_names) == mock_kube_client.patch_namespaced_pod.call_count mock_kube_client.patch_namespaced_pod.assert_has_calls( [ mock.call( body={"metadata": {"labels": {"airflow-worker": "modified"}}}, name=pod_name, namespace="somens", ) for pod_name in pod_names ], any_order=True, ) assert {k8s_res.key for k8s_res in executor.completed} == expected_running_ti_keys @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor.DynamicClient") @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") def test_adopt_completed_pods_api_exception(self, mock_kube_client, mock_kube_dynamic_client): """We should gracefully handle exceptions when adopting completed pods from other schedulers""" executor = self.kubernetes_executor executor.scheduler_job_id = "modified" executor.kube_client = mock_kube_client executor.kube_config.kube_namespace = "somens" pod_names = ["one", "two"] def get_annotations(pod_name): return { "dag_id": "dag", "run_id": "run_id", "task_id": pod_name, "try_number": "1", } mock_kube_dynamic_client.return_value.get.return_value.items = [ k8s.V1Pod( metadata=k8s.V1ObjectMeta( name=pod_name, labels={"airflow-worker": pod_name}, annotations=get_annotations(pod_name), namespace="somens", ) ) for pod_name in pod_names ] mock_kube_client.patch_namespaced_pod.side_effect = ApiException(status=400) executor._adopt_completed_pods(mock_kube_client) assert len(pod_names) == mock_kube_client.patch_namespaced_pod.call_count assert executor.running == set() @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") def test_not_adopt_unassigned_task(self, mock_kube_client): """ We should not adopt any tasks that were not assigned by the scheduler. This ensures that there is no contention over pod management. """ executor = self.kubernetes_executor executor.scheduler_job_id = "modified" tis_to_flush_by_key = {"foobar": {}} pod = k8s.V1Pod( metadata=k8s.V1ObjectMeta( name="foo", labels={"airflow-worker": "bar"}, annotations={ "dag_id": "dag", "run_id": "run_id", "task_id": "task", "try_number": "1", }, ) ) executor.adopt_launched_task(mock_kube_client, pod=pod, tis_to_flush_by_key=tis_to_flush_by_key) assert not mock_kube_client.patch_namespaced_pod.called assert tis_to_flush_by_key == {"foobar": {}} @pytest.mark.db_test @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor.DynamicClient") def test_cleanup_stuck_queued_tasks(self, mock_kube_dynamic_client, dag_maker, create_dummy_dag, session): """ This verifies legacy behavior. Remove when removing ``cleanup_stuck_queued_tasks``. It's expected that method, ``cleanup_stuck_queued_tasks`` will patch the pod such that it is ignored by watcher, delete the pod, remove from running set, and fail the task. """ mock_kube_client = mock.MagicMock() mock_kube_dynamic_client.return_value = mock.MagicMock() mock_pod_resource = mock.MagicMock() mock_kube_dynamic_client.return_value.resources.get.return_value = mock_pod_resource mock_kube_dynamic_client.return_value.get.return_value = k8s.V1PodList( items=[ k8s.V1Pod( metadata=k8s.V1ObjectMeta( annotations={ "dag_id": "test_cleanup_stuck_queued_tasks", "task_id": "bash", "run_id": "test", "try_number": 0, }, labels={ "role": "airflow-worker", "dag_id": "test_cleanup_stuck_queued_tasks", "task_id": "bash", "airflow-worker": 123, "run_id": "test", "try_number": 0, }, ), status=k8s.V1PodStatus(phase="Pending"), ) ] ) create_dummy_dag(dag_id="test_cleanup_stuck_queued_tasks", task_id="bash", with_dagrun_type=None) dag_run = dag_maker.create_dagrun() ti = dag_run.task_instances[0] ti.state = State.QUEUED ti.queued_by_job_id = 123 session.flush() executor = self.kubernetes_executor executor.job_id = 123 executor.kube_client = mock_kube_client executor.kube_scheduler = mock.MagicMock() ti.refresh_from_db() tis = [ti] with pytest.warns(DeprecationWarning, match="cleanup_stuck_queued_tasks"): executor.cleanup_stuck_queued_tasks(tis=tis) executor.kube_scheduler.delete_pod.assert_called_once() assert executor.running == set() @pytest.mark.db_test @mock.patch("airflow.providers.cncf.kubernetes.executors.kubernetes_executor.DynamicClient") def test_revoke_task(self, mock_kube_dynamic_client, dag_maker, create_dummy_dag, session): """ It's expected that ``revoke_tasks`` will patch the pod such that it is ignored by watcher, delete the pod and remove from running set. """ mock_kube_client = mock.MagicMock() mock_kube_dynamic_client.return_value = mock.MagicMock() mock_pod_resource = mock.MagicMock() mock_kube_dynamic_client.return_value.resources.get.return_value = mock_pod_resource mock_kube_dynamic_client.return_value.get.return_value = k8s.V1PodList( items=[ k8s.V1Pod( metadata=k8s.V1ObjectMeta( annotations={ "dag_id": "test_cleanup_stuck_queued_tasks", "task_id": "bash", "run_id": "test", "try_number": 0, }, labels={ "role": "airflow-worker", "dag_id": "test_cleanup_stuck_queued_tasks", "task_id": "bash", "airflow-worker": 123, "run_id": "test", "try_number": 0, }, ), status=k8s.V1PodStatus(phase="Pending"), ) ] ) create_dummy_dag(dag_id="test_cleanup_stuck_queued_tasks", task_id="bash", with_dagrun_type=None) dag_run = dag_maker.create_dagrun() ti = dag_run.task_instances[0] ti.state = State.QUEUED ti.queued_by_job_id = 123 session.flush() executor = self.kubernetes_executor executor.job_id = 123 executor.kube_client = mock_kube_client executor.kube_scheduler = mock.MagicMock() ti.refresh_from_db() executor.running.add(ti.key) # so we can verify it gets removed after revoke assert executor.has_task(task_instance=ti) executor.revoke_task(ti=ti) assert not executor.has_task(task_instance=ti) executor.kube_scheduler.patch_pod_revoked.assert_called_once() executor.kube_scheduler.delete_pod.assert_called_once() mock_kube_client.patch_namespaced_pod.calls[0] == [] assert executor.running == set() @pytest.mark.parametrize( ("raw_multi_namespace_mode", "raw_value_namespace_list", "expected_value_in_kube_config"), [ pytest.param("true", "A,B,C", ["A", "B", "C"]), pytest.param("true", "", None), pytest.param("false", "A,B,C", None), pytest.param("false", "", None), ], ) def test_kube_config_get_namespace_list( self, raw_multi_namespace_mode, raw_value_namespace_list, expected_value_in_kube_config ): config = { ("kubernetes_executor", "multi_namespace_mode"): raw_multi_namespace_mode, ("kubernetes_executor", "multi_namespace_mode_namespace_list"): raw_value_namespace_list, } with conf_vars(config): executor = KubernetesExecutor() assert executor.kube_config.multi_namespace_mode_namespace_list == expected_value_in_kube_config @pytest.mark.db_test @mock.patch("airflow.providers.cncf.kubernetes.kube_client.get_kube_client") def test_get_task_log(self, mock_get_kube_client, create_task_instance_of_operator): """fetch task log from pod""" mock_kube_client = mock_get_kube_client.return_value mock_kube_client.read_namespaced_pod_log.return_value = [b"a_", b"b_", b"c_"] mock_pod = mock.Mock() mock_pod.metadata.name = "x" mock_kube_client.list_namespaced_pod.return_value.items = [mock_pod] ti = create_task_instance_of_operator(EmptyOperator, dag_id="test_k8s_log_dag", task_id="test_task") executor = KubernetesExecutor() messages, logs = executor.get_task_log(ti=ti, try_number=1) mock_kube_client.read_namespaced_pod_log.assert_called_once() assert messages == [ "Attempting to fetch logs from pod through kube API", "Found logs through kube API", ] assert logs[0] == "a_\nb_\nc_" mock_kube_client.reset_mock() mock_kube_client.read_namespaced_pod_log.side_effect = Exception("error_fetching_pod_log") messages, logs = executor.get_task_log(ti=ti, try_number=1) assert logs == [""] assert messages == [ "Attempting to fetch logs from pod through kube API", "Reading from k8s pod logs failed: error_fetching_pod_log", ] @pytest.mark.skipif(not AIRFLOW_V_3_2_PLUS, reason="Airflow 3.2+ prefers new configuration") def test_sentry_integration(self): assert not KubernetesExecutor.sentry_integration @pytest.mark.skipif(AIRFLOW_V_3_2_PLUS, reason="Test only for Airflow < 3.2") def test_supports_sentry(self): assert not KubernetesExecutor.supports_sentry def test_cli_commands_vended(self): assert KubernetesExecutor.get_cli_commands() def test_annotations_for_logging_task_metadata(self): annotations_test = { "dag_id": "dag", "run_id": "run_id", "task_id": "task", "try_number": "1", } get_logs_task_metadata.cache_clear() try: with conf_vars({("kubernetes_executor", "logs_task_metadata"): "True"}): expected_annotations = { "dag_id": "dag", "run_id": "run_id", "task_id": "task", "try_number": "1", } annotations_actual = annotations_for_logging_task_metadata(annotations_test) assert annotations_actual == expected_annotations finally: get_logs_task_metadata.cache_clear() def test_annotations_for_logging_task_metadata_fallback(self): annotations_test = { "dag_id": "dag", "run_id": "run_id", "task_id": "task", "try_number": "1", } get_logs_task_metadata.cache_clear() try: with conf_vars({("kubernetes_executor", "logs_task_metadata"): "False"}): expected_annotations = "<omitted>" annotations_actual = annotations_for_logging_task_metadata(annotations_test) assert annotations_actual == expected_annotations finally: get_logs_task_metadata.cache_clear()
TestKubernetesExecutor
python
openai__openai-python
src/openai/types/realtime/session_created_event.py
{ "start": 519, "end": 770 }
class ____(BaseModel): event_id: str """The unique ID of the server event.""" session: Session """The session configuration.""" type: Literal["session.created"] """The event type, must be `session.created`."""
SessionCreatedEvent
python
falconry__falcon
tests/test_middleware.py
{ "start": 3211, "end": 3277 }
class ____(ExecutedFirstMiddleware): pass
ExecutedLastMiddleware
python
huggingface__transformers
tests/models/gemma/test_modeling_gemma.py
{ "start": 1518, "end": 2226 }
class ____(CausalLMModelTest, unittest.TestCase): model_tester_class = GemmaModelTester # used in `test_torch_compile_for_training` _torch_compile_train_cls = GemmaForCausalLM if is_torch_available() else None # TODO (ydshieh): Check this. See https://app.circleci.com/pipelines/github/huggingface/transformers/79245/workflows/9490ef58-79c2-410d-8f51-e3495156cf9c/jobs/1012146 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, ): return True @slow @require_torch_accelerator
GemmaModelTest
python
dagster-io__dagster
python_modules/automation/automation_tests/dagster_docs_tests/test_public_api_validator.py
{ "start": 487, "end": 14795 }
class ____: """Test suite for public API validation.""" @pytest.fixture def validator(self): """Create a validator instance for testing.""" dagster_root = Path(__file__).parent.parent.parent.parent.parent return PublicApiValidator(dagster_root) @pytest.fixture def public_symbols(self, validator): """Load all @public decorated symbols.""" return validator.find_public_symbols(exclude_modules=EXCLUDE_MODULES_FROM_PUBLIC_SCAN) @pytest.fixture def rst_symbols(self, validator): """Load all RST documented symbols.""" return validator.find_rst_documented_symbols(exclude_files=EXCLUDE_RST_FILES) def test_find_public_symbols(self, validator): """Test that we can find @public decorated symbols.""" symbols = validator.find_public_symbols() # Should find some symbols assert len(symbols) > 0 # Check structure of returned symbols for symbol in symbols[:5]: # Check first few assert isinstance(symbol, PublicSymbol) assert symbol.module_path assert symbol.symbol_name assert symbol.symbol_type in ["class", "function"] assert isinstance(symbol.is_exported, bool) assert symbol.source_file def test_find_rst_documented_symbols(self, validator): """Test that we can extract symbols from RST files.""" symbols = validator.find_rst_documented_symbols() # Should find some symbols assert len(symbols) > 0 # Check structure of returned symbols for symbol in symbols[:5]: # Check first few assert isinstance(symbol, RstSymbol) assert symbol.module_path assert symbol.symbol_name assert symbol.rst_directive in ["autoclass", "autofunction", "autodecorator"] assert symbol.rst_file def test_validate_public_in_rst_no_excludes(self, validator, public_symbols, rst_symbols): """Test validation that @public symbols are in RST (without excludes).""" issues = validator.validate_public_in_rst(public_symbols, rst_symbols) # This will likely find issues since we're not using excludes # The test validates the mechanism works assert isinstance(issues, list) for issue in issues: assert isinstance(issue, ValidationIssue) assert issue.issue_type in ["missing_rst", "missing_export"] assert issue.symbol_name assert issue.module_path assert issue.details def test_validate_public_in_rst_with_excludes(self, validator, public_symbols, rst_symbols): """Test validation with exclude lists to handle existing inconsistencies.""" issues = validator.validate_public_in_rst( public_symbols, rst_symbols, exclude_symbols=EXCLUDE_MISSING_RST.union(EXCLUDE_MISSING_EXPORT), ) # With proper excludes, should have minimal/no issues # Print issues for manual review if issues: print(f"\nFound {len(issues)} @public->RST validation issues:") # noqa: T201 for issue in issues[:10]: # Show first 10 print(f" {issue.issue_type}: {issue.module_path}.{issue.symbol_name}") # noqa: T201 print(f" {issue.details}") # noqa: T201 def test_validate_rst_has_public_no_excludes(self, validator, rst_symbols, public_symbols): """Test validation that RST symbols have @public (without excludes).""" issues = validator.validate_rst_has_public(rst_symbols, public_symbols) # This will likely find issues since we're not using excludes assert isinstance(issues, list) for issue in issues: assert isinstance(issue, ValidationIssue) assert issue.issue_type == "missing_public" assert issue.symbol_name assert issue.module_path assert issue.details def test_validate_rst_has_public_with_excludes(self, validator, rst_symbols, public_symbols): """Test validation with exclude lists to handle existing inconsistencies.""" issues = validator.validate_rst_has_public( rst_symbols, public_symbols, exclude_symbols=EXCLUDE_MISSING_PUBLIC ) # With proper excludes, should have minimal/no issues # Print issues for manual review if issues: print(f"\nFound {len(issues)} RST->@public validation issues:") # noqa: T201 for issue in issues[:10]: # Show first 10 print(f" {issue.issue_type}: {issue.module_path}.{issue.symbol_name}") # noqa: T201 print(f" {issue.details}") # noqa: T201 def test_full_bidirectional_validation(self, validator): """Test complete bidirectional validation with all exclude lists.""" # Load symbols with excludes public_symbols = validator.find_public_symbols( exclude_modules=EXCLUDE_MODULES_FROM_PUBLIC_SCAN ) rst_symbols = validator.find_rst_documented_symbols(exclude_files=EXCLUDE_RST_FILES) # Validate both directions public_to_rst_issues = validator.validate_public_in_rst( public_symbols, rst_symbols, exclude_symbols=EXCLUDE_MISSING_RST.union(EXCLUDE_MISSING_EXPORT), ) rst_to_public_issues = validator.validate_rst_has_public( rst_symbols, public_symbols, exclude_symbols=EXCLUDE_MISSING_PUBLIC ) # Report any remaining issues total_issues = len(public_to_rst_issues) + len(rst_to_public_issues) if total_issues > 0: print("\n=== FULL VALIDATION REPORT ===") # noqa: T201 print(f"Total issues found: {total_issues}") # noqa: T201 if public_to_rst_issues: print(f"\n@public->RST issues ({len(public_to_rst_issues)}):") # noqa: T201 for issue in public_to_rst_issues[:10]: print(f" {issue.issue_type}: {issue.module_path}.{issue.symbol_name}") # noqa: T201 if rst_to_public_issues: print(f"\nRST->@public issues ({len(rst_to_public_issues)}):") # noqa: T201 for issue in rst_to_public_issues[:10]: print(f" {issue.issue_type}: {issue.module_path}.{issue.symbol_name}") # noqa: T201 print("\nTo fix these issues:") # noqa: T201 print("1. Add missing @public decorators to RST-documented symbols") # noqa: T201 print("2. Add missing RST documentation for @public symbols") # noqa: T201 print("3. Add missing top-level exports for @public symbols") # noqa: T201 print("4. Or add entries to exclude lists for items that should not be validated") # noqa: T201 # For now, don't fail the test - this is informational # In the future when issues are resolved, this could assert total_issues == 0 def test_no_new_public_api_inconsistencies(self, validator): """Enforce that no new @public API inconsistencies are introduced. This test ensures that the number of issues doesn't grow beyond what's already captured in the exclude lists. Any new issues should be either: 1. Fixed immediately by adding proper @public decorators or RST docs 2. Added to the appropriate exclude list with justification """ # Load symbols with excludes public_symbols = validator.find_public_symbols( exclude_modules=EXCLUDE_MODULES_FROM_PUBLIC_SCAN ) rst_symbols = validator.find_rst_documented_symbols(exclude_files=EXCLUDE_RST_FILES) # Validate both directions with exclude lists public_to_rst_issues = validator.validate_public_in_rst( public_symbols, rst_symbols, exclude_symbols=EXCLUDE_MISSING_RST.union(EXCLUDE_MISSING_EXPORT), ) rst_to_public_issues = validator.validate_rst_has_public( rst_symbols, public_symbols, exclude_symbols=EXCLUDE_MISSING_PUBLIC ) # Should have zero issues after applying exclude lists total_issues = len(public_to_rst_issues) + len(rst_to_public_issues) if total_issues > 0: print(f"\n❌ NEW PUBLIC API INCONSISTENCIES DETECTED: {total_issues}") # noqa: T201 if public_to_rst_issues: print(f"\nNew @public->RST issues ({len(public_to_rst_issues)}):") # noqa: T201 for issue in public_to_rst_issues: print(f" {issue.issue_type}: {issue.module_path}.{issue.symbol_name}") # noqa: T201 if rst_to_public_issues: print(f"\nNew RST->@public issues ({len(rst_to_public_issues)}):") # noqa: T201 for issue in rst_to_public_issues: print(f" {issue.issue_type}: {issue.module_path}.{issue.symbol_name}") # noqa: T201 print("\nTo fix these issues:") # noqa: T201 print("1. Add missing @public decorators to RST-documented symbols") # noqa: T201 print("2. Add missing RST documentation for @public symbols") # noqa: T201 print("3. Add missing top-level exports for @public symbols") # noqa: T201 print("4. Or add entries to exclude lists with proper justification") # noqa: T201 # FAIL the test if there are any unexcluded issues if total_issues > 0: # Build detailed error message with specific symbols error_details = [] if public_to_rst_issues: error_details.append( f"@public->RST issues: {[f'{issue.module_path}.{issue.symbol_name}' for issue in public_to_rst_issues]}" ) if rst_to_public_issues: error_details.append( f"RST->@public issues: {[f'{issue.module_path}.{issue.symbol_name}' for issue in rst_to_public_issues]}" ) detailed_message = ( f"Found {total_issues} new @public API inconsistencies. " + "; ".join(error_details) ) assert total_issues == 0, detailed_message def test_error_cases(self, validator): """Test error handling and edge cases.""" # Test with empty lists issues = validator.validate_public_in_rst([], []) assert issues == [] issues = validator.validate_rst_has_public([], []) assert issues == [] # Test with non-existent paths should not crash bad_validator = PublicApiValidator(Path("/nonexistent")) symbols = bad_validator.find_public_symbols() assert isinstance(symbols, list) # Should return empty list, not crash def test_specific_known_symbols(self, validator): """Test specific known symbols to ensure detection works.""" public_symbols = validator.find_public_symbols() rst_symbols = validator.find_rst_documented_symbols() # Look for some symbols we know should exist public_names = {(sym.module_path, sym.symbol_name) for sym in public_symbols} rst_names = {(sym.module_path, sym.symbol_name) for sym in rst_symbols} # These should exist based on our earlier exploration expected_public = [ ("dagster", "asset"), # @asset decorator ("dagster", "AssetKey"), # AssetKey class ] expected_rst = [ ("dagster", "asset"), ("dagster", "AssetKey"), ] for module, name in expected_public: if (module, name) in public_names: print(f"✓ Found expected @public symbol: {module}.{name}") # noqa: T201 else: print(f"✗ Missing expected @public symbol: {module}.{name}") # noqa: T201 for module, name in expected_rst: if (module, name) in rst_names: print(f"✓ Found expected RST symbol: {module}.{name}") # noqa: T201 else: print(f"✗ Missing expected RST symbol: {module}.{name}") # noqa: T201 def test_catch_missing_rst_documentation(): """Test case that should catch when @public symbols lack RST documentation.""" # This test demonstrates how the validator catches issues validator = PublicApiValidator(Path(__file__).parent.parent.parent.parent.parent) # Create mock data to simulate the issue public_symbols = [ PublicSymbol( module_path="dagster.test", symbol_name="MissingFromRst", symbol_type="class", is_exported=True, source_file="/fake/path.py", ) ] rst_symbols = [ RstSymbol( module_path="dagster.test", symbol_name="DocumentedInRst", rst_directive="autoclass", rst_file="/fake/doc.rst", ) ] issues = validator.validate_public_in_rst(public_symbols, rst_symbols) # Should catch the missing RST documentation assert len(issues) == 1 assert issues[0].issue_type == "missing_rst" assert issues[0].symbol_name == "MissingFromRst" def test_catch_missing_public_decorator(): """Test case that should catch when RST symbols lack @public decorator.""" validator = PublicApiValidator(Path(__file__).parent.parent.parent.parent.parent) # Create mock data to simulate the issue rst_symbols = [ RstSymbol( module_path="dagster.test", symbol_name="MissingPublicDecorator", rst_directive="autoclass", rst_file="/fake/doc.rst", ) ] public_symbols = [ PublicSymbol( module_path="dagster.test", symbol_name="HasPublicDecorator", symbol_type="class", is_exported=True, source_file="/fake/path.py", ) ] issues = validator.validate_rst_has_public(rst_symbols, public_symbols) # Should catch the missing @public decorator assert len(issues) == 1 assert issues[0].issue_type == "missing_public" assert issues[0].symbol_name == "MissingPublicDecorator" if __name__ == "__main__": # Allow running tests directly pytest.main([__file__, "-v"])
TestPublicApiValidator
python
pytorch__pytorch
torch/_inductor/codegen/wrapper.py
{ "start": 15724, "end": 16174 }
class ____(WrapperLine): wrapper: PythonWrapperCodegen def __post_init__(self) -> None: self.wrapper.computed_sizes = self.wrapper.pop_computed_sizes() def codegen(self, code: IndentedBuffer) -> None: self.wrapper.pop_codegened_graph() code.do_unindent() def codegen_fx(self, converter: FxConverter) -> FxConversionFunc: return converter._generate_exit_subgraph @dataclasses.dataclass
ExitSubgraphLine
python
pypa__pip
src/pip/_internal/commands/debug.py
{ "start": 5190, "end": 6805 }
class ____(Command): """ Display debug information. """ usage = """ %prog <options>""" ignore_require_venv = True def add_options(self) -> None: cmdoptions.add_target_python_options(self.cmd_opts) self.parser.insert_option_group(0, self.cmd_opts) self.parser.config.load() def run(self, options: Values, args: list[str]) -> int: logger.warning( "This command is only meant for debugging. " "Do not use this with automation for parsing and getting these " "details, since the output and options of this command may " "change without notice." ) show_value("pip version", get_pip_version()) show_value("sys.version", sys.version) show_value("sys.executable", sys.executable) show_value("sys.getdefaultencoding", sys.getdefaultencoding()) show_value("sys.getfilesystemencoding", sys.getfilesystemencoding()) show_value( "locale.getpreferredencoding", locale.getpreferredencoding(), ) show_value("sys.platform", sys.platform) show_sys_implementation() show_value("'cert' config value", ca_bundle_info(self.parser.config)) show_value("REQUESTS_CA_BUNDLE", os.environ.get("REQUESTS_CA_BUNDLE")) show_value("CURL_CA_BUNDLE", os.environ.get("CURL_CA_BUNDLE")) show_value("pip._vendor.certifi.where()", where()) show_value("pip._vendor.DEBUNDLED", pip._vendor.DEBUNDLED) show_vendor_versions() show_tags(options) return SUCCESS
DebugCommand
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/initsubclass2.py
{ "start": 135, "end": 228 }
class ____: def __init_subclass__(cls, param_a: int): super().__init_subclass__()
A
python
numba__numba
numba/core/rewrites/registry.py
{ "start": 666, "end": 3651 }
class ____(object): '''Defines a registry for Numba rewrites. ''' _kinds = frozenset(['before-inference', 'after-inference']) def __init__(self): '''Constructor for the rewrite registry. Initializes the rewrites member to an empty list. ''' self.rewrites = defaultdict(list) def register(self, kind): """ Decorator adding a subclass of Rewrite to the registry for the given *kind*. """ if kind not in self._kinds: raise KeyError("invalid kind %r" % (kind,)) def do_register(rewrite_cls): if not issubclass(rewrite_cls, Rewrite): raise TypeError('{0} is not a subclass of Rewrite'.format( rewrite_cls)) self.rewrites[kind].append(rewrite_cls) return rewrite_cls return do_register def apply(self, kind, state): '''Given a pipeline and a dictionary of basic blocks, exhaustively attempt to apply all registered rewrites to all basic blocks. ''' assert kind in self._kinds blocks = state.func_ir.blocks old_blocks = blocks.copy() for rewrite_cls in self.rewrites[kind]: # Exhaustively apply a rewrite until it stops matching. rewrite = rewrite_cls(state) work_list = list(blocks.items()) while work_list: key, block = work_list.pop() matches = rewrite.match(state.func_ir, block, state.typemap, state.calltypes) if matches: if config.DEBUG or config.DUMP_IR: print("_" * 70) print("REWRITING (%s):" % rewrite_cls.__name__) block.dump() print("_" * 60) new_block = rewrite.apply() blocks[key] = new_block work_list.append((key, new_block)) if config.DEBUG or config.DUMP_IR: new_block.dump() print("_" * 70) # If any blocks were changed, perform a sanity check. for key, block in blocks.items(): if block != old_blocks[key]: block.verify() # Some passes, e.g. _inline_const_arraycall are known to occasionally # do invalid things WRT ir.Del, others, e.g. RewriteArrayExprs do valid # things with ir.Del, but the placement is not optimal. The lines below # fix-up the IR so that ref counts are valid and optimally placed, # see #4093 for context. This has to be run here opposed to in # apply() as the CFG needs computing so full IR is needed. from numba.core import postproc post_proc = postproc.PostProcessor(state.func_ir) post_proc.run() rewrite_registry = RewriteRegistry() register_rewrite = rewrite_registry.register
RewriteRegistry
python
Textualize__textual
src/textual/widgets/_markdown.py
{ "start": 22647, "end": 23119 }
class ____(Widget): """A bullet widget.""" DEFAULT_CSS = """ MarkdownBullet { width: auto; color: $text-primary; &:light { color: $text-secondary; } } """ symbol = reactive("\u25cf") """The symbol for the bullet.""" def get_selection(self, _selection) -> tuple[str, str] | None: return self.symbol, " " def render(self) -> Content: return Content(self.symbol)
MarkdownBullet
python
pytorch__pytorch
test/ao/sparsity/test_data_sparsifier.py
{ "start": 814, "end": 10898 }
class ____(TestCase): r"""This helper test class takes in any supported type of and runs some tests. The user is required to pass in the data that needs to sparsified and the runner will run some tests that needs to be passed in order for the data type to be supported. TODO: Change the structure by creating a separate test case class for each member function """ def run_all_checks(self, data_list, data_with_config, defaults): self.check_constructor(data_list, data_with_config, defaults) self.check_squash_mask(data_list, data_with_config, defaults) self.check_add_data(data_list, data_with_config, defaults) self.check_step(data_list, data_with_config, defaults) self.check_state_dict(data_list, data_with_config, defaults) self.check_memory_reference(data_list, data_with_config, defaults) @staticmethod def _get_name_data_config(some_data, defaults=None): if isinstance(some_data, tuple): # dealing with data_list name, data = some_data config = defaults else: # dealing with data_with_config name, data, config = ( some_data["name"], some_data["data"], some_data["config"], ) return name, data, config @staticmethod def _make_sparsifier( data_list, data_with_config, defaults, sparsifier_type=None, sparsifier_kwargs=None, ): if sparsifier_type is None: sparsifier = ImplementedSparsifier(data_list=data_list, **defaults) else: kwargs = copy.deepcopy(defaults) kwargs.update(sparsifier_kwargs) kwargs["data_list"] = data_list sparsifier = sparsifier_type(**kwargs) assert len(sparsifier.data_groups) == len(data_list) for data_config_dict in data_with_config: name, data, config = ( data_config_dict["name"], data_config_dict["data"], data_config_dict["config"], ) sparsifier.add_data(name=name, data=data, **config) return sparsifier def check_constructor(self, data_list, data_with_config, defaults, **kwargs): sparsifier = self._make_sparsifier( data_list, data_with_config, defaults=defaults, **kwargs ) self.assertEqual( len(sparsifier.data_groups), len(data_list) + len(data_with_config), msg="Sparsifier data groups don't match the input " f"({len(sparsifier.data_groups)} vs. " f"{len(data_list) + len(data_with_config)}).", ) all_data = data_list + data_with_config for some_data in all_data: name, _, config = self._get_name_data_config(some_data, defaults=defaults) self.assertIn(name, sparsifier.data_groups) self.assertEqual(sparsifier.data_groups[name], config) def check_step(self, data_list, data_with_config, defaults, **kwargs): sparsifier = self._make_sparsifier( data_list, data_with_config, defaults=defaults, **kwargs ) all_data = data_list + data_with_config # Check data and mask before doing the step for some_data in all_data: name, data, _ = self._get_name_data_config(some_data) data = sparsifier._extract_weight(data) sparsified_data = sparsifier.get_data(name=name, return_original=False) original_data = sparsifier.get_data(name=name, return_original=True) mask = sparsifier.get_mask(name=name) self.assertEqual(sparsified_data, data) self.assertEqual(original_data, data) self.assertEqualBroadcasting(mask[0], 1) step_count = 3 for _ in range(step_count): sparsifier.step() for some_data in all_data: name, data, _ = self._get_name_data_config(some_data) data = sparsifier._extract_weight(data) sparsified_data = sparsifier.get_data(name=name, return_original=False) original_data = sparsifier.get_data(name=name, return_original=True) mask = sparsifier.get_mask(name=name) self.assertEqualBroadcasting(sparsified_data[0], 0) self.assertEqual(original_data, data) self.assertEqualBroadcasting(mask[0], 0) assert "step_count" in sparsifier.state[name] assert sparsifier.state[name]["step_count"] == 3 def check_squash_mask(self, data_list, data_with_config, defaults, **kwargs): sparsifier = self._make_sparsifier( data_list, data_with_config, defaults=defaults, **kwargs ) all_data = data_list + data_with_config for some_data in all_data: name, _, _ = self._get_name_data_config(some_data) assert hasattr(sparsifier._container, name) assert is_parametrized(sparsifier._container, name) sparsifier.step() sparsifier.squash_mask() for some_data in all_data: name, _, _ = self._get_name_data_config(some_data) assert not is_parametrized( sparsifier._container, name ) # not parametrized anymore with self.assertRaises(ValueError): sparsifier.get_data(name, return_original=True) def check_add_data(self, data_list, data_with_config, defaults, **kwargs): sparsifier = self._make_sparsifier( data_list, data_with_config, defaults=defaults, **kwargs ) all_data = data_list + data_with_config for some_data in all_data: name1, data1, config = self._get_name_data_config( some_data, defaults=defaults ) data1 = sparsifier._extract_weight(data1) data1_old = copy.deepcopy(data1) assert torch.all(data1 == sparsifier.get_data(name=name1)) sparsifier.step() mask = sparsifier.get_mask(name1) data2 = torch.randn( data1.shape ) # add another data with the same shape as original data sparsifier.add_data(name=name1, data=data2) assert torch.all(data2 == sparsifier.get_data(name=name1)) assert torch.all( sparsifier.get_mask(name1) == mask ) # mask should not change assert torch.all(data1_old == data1) assert ( sparsifier.data_groups[name1] == config ) # if replaced old_config should match new config def check_state_dict(self, data_list, data_with_config, defaults, **kwargs): sparsifier1 = self._make_sparsifier( data_list, data_with_config, defaults=defaults, **kwargs ) sparsifier2 = self._make_sparsifier( data_list=[data_list[0]], data_with_config=[], defaults=defaults, **kwargs ) sparsifier1.step() state_dict1 = sparsifier1.state_dict() assert sparsifier1.state != sparsifier2.state name, _, _ = self._get_name_data_config(data_list[0]) self.assertNotEqual(sparsifier1.get_mask(name), sparsifier2.get_mask(name)) sparsifier2.load_state_dict(state_dict1) assert len(sparsifier1.state) == len(sparsifier2.state) assert len(sparsifier1.data_groups) == len(sparsifier2.data_groups) state1 = state_dict1["state"] for name in state1: # compare mask assert name in sparsifier2.state assert "mask" in sparsifier2.state[name] assert "mask" in sparsifier1.state[name] mask1, mask2 = state1[name]["mask"], sparsifier2.state[name]["mask"] assert mask1.is_sparse and not mask2.is_sparse assert torch.all( mask1.to_dense() == mask2 ) # mask1 is stored as sparse coo now # compare data_groups dg1, dg2 = sparsifier1.data_groups, sparsifier2.data_groups assert name in dg1 and name in dg2 assert dg1[name] == dg2[name] # compare container container1, container2 = sparsifier1._container, sparsifier2._container assert torch.all(getattr(container1, name) == getattr(container2, name)) assert is_parametrized(container1, name) == is_parametrized( container2, name ) if is_parametrized(container1, name): param1 = getattr(container1.parametrizations, name)[0] param2 = getattr(container2.parametrizations, name)[0] assert hasattr(param1, "mask") assert hasattr(param2, "mask") self.assertEqual(param1.__dict__, param2.__dict__) def check_memory_reference(self, data_list, data_with_config, defaults, **kwargs): """Checks if the data is truly "attached" to the sparsifier. Meaning, when the data is changed outside of the sparsifier, the changes must be reflected on the data inside the data sparsifier as well. This makes sure that the sparsifier is holding the memory reference of the data and not copies. This test modifies the data and asserts that data in the sparsifier is changed as well """ sparsifier = self._make_sparsifier( data_list, data_with_config, defaults=defaults, **kwargs ) all_data = data_list + data_with_config for some_data in all_data: name, data, _ = self._get_name_data_config(some_data) weight = sparsifier._extract_weight(data) weight.data = weight + torch.randn(*weight.shape) contained_data = sparsifier.get_data(name=name) assert ( weight.data.storage().data_ptr() == contained_data.data.storage().data_ptr() ) assert torch.all(contained_data == weight)
_BaseDataSparsiferTestCase
python
hynek__structlog
tests/test_threadlocal.py
{ "start": 4189, "end": 8065 }
class ____: def test_wrap_returns_distinct_classes(self): """ Each call to wrap_dict returns a distinct new class whose context is independent from others. """ with pytest.deprecated_call(): D1 = wrap_dict(dict) D2 = wrap_dict(dict) assert D1 != D2 assert D1 is not D2 D1.x = 42 D2.x = 23 assert D1.x != D2.x @pytest.mark.skipif( greenlet is not None, reason="Don't mix threads and greenlets." ) def test_is_thread_local(self, D): """ The context is *not* shared between threads. """ class TestThread(threading.Thread): def __init__(self, d): self._d = d threading.Thread.__init__(self) def run(self): assert "tl" not in self._d._dict self._d["tl"] = 23 with pytest.deprecated_call(): d = wrap_dict(dict)() d["tl"] = 42 t = TestThread(d) t.start() t.join() assert 42 == d._dict["tl"] def test_context_is_global_to_thread(self, D): """ The context is shared between all instances of a wrapped class. """ d1 = D({"a": 42}) d2 = D({"b": 23}) d3 = D() assert {"a": 42, "b": 23} == d1._dict == d2._dict == d3._dict assert d1 == d2 == d3 with pytest.deprecated_call(): D_ = wrap_dict(dict) d_ = D_({"a": 42, "b": 23}) assert d1 != d_ def test_init_with_itself_works(self, D): """ Initializing with an instance of the wrapped class will use its values. """ d = D({"a": 42}) assert {"a": 42, "b": 23} == D(d, b=23)._dict def test_iter_works(self, D): """ ___iter__ is proxied to the wrapped class. """ d = D({"a": 42}) assert ["a"] == list(iter(d)) def test_non_dunder_proxy_works(self, D): """ Calls to a non-dunder method get proxied to the wrapped class. """ d = D({"a": 42}) d.clear() assert 0 == len(d) def test_repr(self, D): """ ___repr__ takes the repr of the wrapped class into account. """ r = repr(D({"a": 42})) assert r.startswith("<WrappedDict-") assert r.endswith("({'a': 42})>") @pytest.mark.skipif(greenlet is None, reason="Needs greenlet.") def test_is_greenlet_local(self, D): """ Context is shared between greenlets. """ with pytest.deprecated_call(): d = wrap_dict(dict)() d["switch"] = 42 def run(): assert "x" not in d._dict d["switch"] = 23 greenlet.greenlet(run).switch() assert 42 == d._dict["switch"] def test_delattr(self, D): """ ___delattr__ is proxied to the wrapped class. """ d = D() d["delattr"] = 42 assert 42 == d._dict["delattr"] del d.__class__._tl.dict_ def test_delattr_missing(self, D): """ __delattr__ on an inexisting attribute raises AttributeError. """ d = D() with pytest.raises(AttributeError) as e: d._tl.__delattr__("does_not_exist") assert e.value.args[0] in ( "does_not_exist", "'_thread._local' object has no attribute 'does_not_exist'", ) def test_del(self, D): """ ___del__ is proxied to the wrapped class. """ d = D() d["del"] = 13 assert 13 == d._dict["del"] del d["del"] assert "del" not in d._dict def test_new_class(self, D): """ The context of a new wrapped class is empty. """ assert 0 == len(D())
TestThreadLocalDict
python
coleifer__peewee
tests/fields.py
{ "start": 25528, "end": 27144 }
class ____(ModelTestCase): requires = [BlobModel] def test_blob_field(self): b = BlobModel.create(data=b'\xff\x01') b_db = BlobModel.get(BlobModel.data == b'\xff\x01') self.assertEqual(b.id, b_db.id) data = b_db.data if isinstance(data, memoryview): data = data.tobytes() elif not isinstance(data, bytes): data = bytes(data) self.assertEqual(data, b'\xff\x01') def test_blob_on_proxy(self): db = Proxy() class NewBlobModel(Model): data = BlobField() class Meta: database = db db_obj = SqliteDatabase(':memory:') db.initialize(db_obj) self.assertTrue(NewBlobModel.data._constructor is sqlite3.Binary) def test_blob_db_hook(self): sentinel = object() class FakeDatabase(Database): def get_binary_type(self): return sentinel class B(Model): b1 = BlobField() b2 = BlobField() B._meta.set_database(FakeDatabase(None)) self.assertTrue(B.b1._constructor is sentinel) self.assertTrue(B.b2._constructor is sentinel) alt_db = SqliteDatabase(':memory:') with alt_db.bind_ctx([B]): # The constructor has been changed. self.assertTrue(B.b1._constructor is sqlite3.Binary) self.assertTrue(B.b2._constructor is sqlite3.Binary) # The constructor has been restored. self.assertTrue(B.b1._constructor is sentinel) self.assertTrue(B.b2._constructor is sentinel)
TestBlobField
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/properties.py
{ "start": 1276, "end": 1755 }
class ____: # This will be the model. @property def my_property(self) -> str: # Ensure that setter taint doesn't pollute the getter, there shouldn't # be an issue here. _test_sink(self) return "" @my_property.setter def my_property(self, value) -> None: pass def uses_property(self): return self.my_property def writes_to_property(self): self.my_property = _test_source()
TaintedGetterAndSetter
python
pypa__hatch
src/hatch/utils/env.py
{ "start": 170, "end": 2445 }
class ____: def __init__(self, platform: Platform, executable: str = "python") -> None: self.platform = platform self.executable = executable self.__dep_check_data: dict[str, Any] | None = None self.__environment: dict[str, str] | None = None self.__sys_path: list[str] | None = None @property def dep_check_data(self) -> dict[str, Any]: if self.__dep_check_data is None: process = self.platform.check_command( [self.executable, "-W", "ignore", "-"], capture_output=True, input=DEP_CHECK_DATA_SCRIPT ) self.__dep_check_data = literal_eval(process.stdout.strip().decode("utf-8")) return self.__dep_check_data @property def environment(self) -> dict[str, str]: if self.__environment is None: self.__environment = self.dep_check_data["environment"] return self.__environment @property def sys_path(self) -> list[str]: if self.__sys_path is None: self.__sys_path = self.dep_check_data["sys_path"] return self.__sys_path # Keep support for Python 2 for a while: # https://github.com/pypa/packaging/blob/20.9/packaging/markers.py#L267-L300 DEP_CHECK_DATA_SCRIPT = b"""\ import os import platform import sys if hasattr(sys, 'implementation'): info = sys.implementation.version iver = '{0.major}.{0.minor}.{0.micro}'.format(info) kind = info.releaselevel if kind != 'final': iver += kind[0] + str(info.serial) implementation_name = sys.implementation.name else: iver = '0' implementation_name = '' environment = { 'implementation_name': implementation_name, 'implementation_version': iver, 'os_name': os.name, 'platform_machine': platform.machine(), 'platform_python_implementation': platform.python_implementation(), 'platform_release': platform.release(), 'platform_system': platform.system(), 'platform_version': platform.version(), 'python_full_version': platform.python_version(), 'python_version': '.'.join(platform.python_version_tuple()[:2]), 'sys_platform': sys.platform, } sys_path = [path for path in sys.path if path] print({'environment': environment, 'sys_path': sys_path}) """
PythonInfo
python
kamyu104__LeetCode-Solutions
Python/design-linked-list.py
{ "start": 144, "end": 3088 }
class ____(object): def __init__(self): """ Initialize your data structure here. """ self.__head = self.__tail = Node(-1) self.__head.next = self.__tail self.__tail.prev = self.__head self.__size = 0 def get(self, index): """ Get the value of the index-th node in the linked list. If the index is invalid, return -1. :type index: int :rtype: int """ if 0 <= index <= self.__size // 2: return self.__forward(0, index, self.__head.next).val elif self.__size // 2 < index < self.__size: return self.__backward(self.__size, index, self.__tail).val return -1 def addAtHead(self, val): """ Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. :type val: int :rtype: void """ self.__add(self.__head, val) def addAtTail(self, val): """ Append a node of value val to the last element of the linked list. :type val: int :rtype: void """ self.__add(self.__tail.prev, val) def addAtIndex(self, index, val): """ Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. :type index: int :type val: int :rtype: void """ if 0 <= index <= self.__size // 2: self.__add(self.__forward(0, index, self.__head.next).prev, val) elif self.__size // 2 < index <= self.__size: self.__add(self.__backward(self.__size, index, self.__tail).prev, val) def deleteAtIndex(self, index): """ Delete the index-th node in the linked list, if the index is valid. :type index: int :rtype: void """ if 0 <= index <= self.__size // 2: self.__remove(self.__forward(0, index, self.__head.next)) elif self.__size // 2 < index < self.__size: self.__remove(self.__backward(self.__size, index, self.__tail)) def __add(self, preNode, val): node = Node(val) node.prev = preNode node.next = preNode.next node.prev.next = node.next.prev = node self.__size += 1 def __remove(self, node): node.prev.next = node.next node.next.prev = node.prev self.__size -= 1 def __forward(self, start, end, curr): while start != end: start += 1 curr = curr.next return curr def __backward(self, start, end, curr): while start != end: start -= 1 curr = curr.prev return curr
MyLinkedList
python
spyder-ide__spyder
spyder/plugins/projects/widgets/projectdialog.py
{ "start": 7241, "end": 10517 }
class ____(BaseProjectPage): """New directory project page.""" LOCATION_TIP = _( "Select the location where the project directory will be created" ) PROJECTS_DOCS_URL = ( "https://docs.spyder-ide.org/current/panes/projects.html" ) def get_name(self): return _("New directory") def get_icon(self): return self.create_icon("folder_new") def setup_page(self): description = QLabel(_("Start a project in a new directory")) description.setWordWrap(True) description.setFont(self._description_font) docs_reference = QLabel( _( "To learn more about projects, see our " '<a href="{0}">documentation</a>.' ).format(self.PROJECTS_DOCS_URL) ) docs_reference.setOpenExternalLinks(True) self._name = self.create_lineedit( text=_("Project directory"), option=None, tip=_( "A directory with this name will be created in the location " "below" ), status_icon=ima.icon("error"), ) layout = QVBoxLayout() layout.addWidget(description) layout.addWidget(docs_reference) layout.addSpacing(5 * AppStyle.MarginSize) layout.addWidget(self._name) layout.addSpacing(5 * AppStyle.MarginSize) layout.addWidget(self._location) layout.addSpacing(7 * AppStyle.MarginSize) layout.addWidget(self._validation_label) layout.addStretch() self.setLayout(layout) @property def project_location(self): return osp.normpath( osp.join(self._location.textbox.text(), self._name.textbox.text()) ) def validate_page(self): name = self._name.textbox.text() # Avoid using "." as location, which is the result of os.normpath("") location_text = self._location.textbox.text() location = osp.normpath(location_text) if location_text else "" # Clear validation state self._validation_label.setVisible(False) for widget in [self._name, self._location]: widget.status_action.setVisible(False) # Perform validation reasons: ValidationReasons = {} if not name: self._name.status_action.setVisible(True) self._name.status_action.setToolTip(_("This is empty")) reasons["missing_info"] = True reasons = self._validate_location(location, reasons, name) if reasons: if reasons.get("location_exists"): self._name.status_action.setVisible(True) self._name.status_action.setToolTip( _("A directory with this name already exists") ) if reasons.get("wrong_name"): self._name.status_action.setVisible(True) self._name.status_action.setToolTip( _("The project directory can't contain ':'") ) self._validation_label.set_text( self._compose_failed_validation_text(reasons) ) self._validation_label.setVisible(True) return False if reasons else True
NewDirectoryPage
python
plotly__plotly.py
plotly/graph_objs/_contour.py
{ "start": 215, "end": 96398 }
class ____(_BaseTraceType): _parent_path_str = "" _path_str = "contour" _valid_props = { "autocolorscale", "autocontour", "coloraxis", "colorbar", "colorscale", "connectgaps", "contours", "customdata", "customdatasrc", "dx", "dy", "fillcolor", "hoverinfo", "hoverinfosrc", "hoverlabel", "hoverongaps", "hovertemplate", "hovertemplatefallback", "hovertemplatesrc", "hovertext", "hovertextsrc", "ids", "idssrc", "legend", "legendgroup", "legendgrouptitle", "legendrank", "legendwidth", "line", "meta", "metasrc", "name", "ncontours", "opacity", "reversescale", "showlegend", "showscale", "stream", "text", "textfont", "textsrc", "texttemplate", "texttemplatefallback", "transpose", "type", "uid", "uirevision", "visible", "x", "x0", "xaxis", "xcalendar", "xhoverformat", "xperiod", "xperiod0", "xperiodalignment", "xsrc", "xtype", "y", "y0", "yaxis", "ycalendar", "yhoverformat", "yperiod", "yperiod0", "yperiodalignment", "ysrc", "ytype", "z", "zauto", "zhoverformat", "zmax", "zmid", "zmin", "zorder", "zsrc", } @property def autocolorscale(self): """ Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. The 'autocolorscale' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["autocolorscale"] @autocolorscale.setter def autocolorscale(self, val): self["autocolorscale"] = val @property def autocontour(self): """ Determines whether or not the contour level attributes are picked by an algorithm. If True, the number of contour levels can be set in `ncontours`. If False, set the contour level attributes in `contours`. The 'autocontour' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["autocontour"] @autocontour.setter def autocontour(self, val): self["autocontour"] = val @property def coloraxis(self): """ Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. The 'coloraxis' property is an identifier of a particular subplot, of type 'coloraxis', that may be specified as the string 'coloraxis' optionally followed by an integer >= 1 (e.g. 'coloraxis', 'coloraxis1', 'coloraxis2', 'coloraxis3', etc.) Returns ------- str """ return self["coloraxis"] @coloraxis.setter def coloraxis(self, val): self["coloraxis"] = val @property def colorbar(self): """ The 'colorbar' property is an instance of ColorBar that may be specified as: - An instance of :class:`plotly.graph_objs.contour.ColorBar` - A dict of string/value properties that will be passed to the ColorBar constructor Returns ------- plotly.graph_objs.contour.ColorBar """ return self["colorbar"] @colorbar.setter def colorbar(self, val): self["colorbar"] = val @property def colorscale(self): """ Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,Cividis,Earth,Electric, Greens,Greys,Hot,Jet,Picnic,Portland,Rainbow,RdBu,Reds,Viridis, YlGnBu,YlOrRd. The 'colorscale' property is a colorscale and may be specified as: - A list of colors that will be spaced evenly to create the colorscale. Many predefined colorscale lists are included in the sequential, diverging, and cyclical modules in the plotly.colors package. - A list of 2-element lists where the first element is the normalized color level value (starting at 0 and ending at 1), and the second item is a valid color string. (e.g. [[0, 'green'], [0.5, 'red'], [1.0, 'rgb(0, 0, 255)']]) - One of the following named colorscales: ['aggrnyl', 'agsunset', 'algae', 'amp', 'armyrose', 'balance', 'blackbody', 'bluered', 'blues', 'blugrn', 'bluyl', 'brbg', 'brwnyl', 'bugn', 'bupu', 'burg', 'burgyl', 'cividis', 'curl', 'darkmint', 'deep', 'delta', 'dense', 'earth', 'edge', 'electric', 'emrld', 'fall', 'geyser', 'gnbu', 'gray', 'greens', 'greys', 'haline', 'hot', 'hsv', 'ice', 'icefire', 'inferno', 'jet', 'magenta', 'magma', 'matter', 'mint', 'mrybm', 'mygbm', 'oranges', 'orrd', 'oryel', 'oxy', 'peach', 'phase', 'picnic', 'pinkyl', 'piyg', 'plasma', 'plotly3', 'portland', 'prgn', 'pubu', 'pubugn', 'puor', 'purd', 'purp', 'purples', 'purpor', 'rainbow', 'rdbu', 'rdgy', 'rdpu', 'rdylbu', 'rdylgn', 'redor', 'reds', 'solar', 'spectral', 'speed', 'sunset', 'sunsetdark', 'teal', 'tealgrn', 'tealrose', 'tempo', 'temps', 'thermal', 'tropic', 'turbid', 'turbo', 'twilight', 'viridis', 'ylgn', 'ylgnbu', 'ylorbr', 'ylorrd']. Appending '_r' to a named colorscale reverses it. Returns ------- str """ return self["colorscale"] @colorscale.setter def colorscale(self, val): self["colorscale"] = val @property def connectgaps(self): """ Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in. It is defaulted to true if `z` is a one dimensional array otherwise it is defaulted to false. The 'connectgaps' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["connectgaps"] @connectgaps.setter def connectgaps(self, val): self["connectgaps"] = val @property def contours(self): """ The 'contours' property is an instance of Contours that may be specified as: - An instance of :class:`plotly.graph_objs.contour.Contours` - A dict of string/value properties that will be passed to the Contours constructor Returns ------- plotly.graph_objs.contour.Contours """ return self["contours"] @contours.setter def contours(self, val): self["contours"] = val @property def customdata(self): """ Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements The 'customdata' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["customdata"] @customdata.setter def customdata(self, val): self["customdata"] = val @property def customdatasrc(self): """ Sets the source reference on Chart Studio Cloud for `customdata`. The 'customdatasrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["customdatasrc"] @customdatasrc.setter def customdatasrc(self, val): self["customdatasrc"] = val @property def dx(self): """ Sets the x coordinate step. See `x0` for more info. The 'dx' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["dx"] @dx.setter def dx(self, val): self["dx"] = val @property def dy(self): """ Sets the y coordinate step. See `y0` for more info. The 'dy' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["dy"] @dy.setter def dy(self, val): self["dy"] = val @property def fillcolor(self): """ Sets the fill color if `contours.type` is "constraint". Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. The 'fillcolor' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') - An hsv/hsva string (e.g. 'hsv(0,100%,100%)') - A named CSS color: see https://plotly.com/python/css-colors/ for a list - A number that will be interpreted as a color according to contour.colorscale Returns ------- str """ return self["fillcolor"] @fillcolor.setter def fillcolor(self, val): self["fillcolor"] = val @property def hoverinfo(self): """ Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. The 'hoverinfo' property is a flaglist and may be specified as a string containing: - Any combination of ['x', 'y', 'z', 'text', 'name'] joined with '+' characters (e.g. 'x+y') OR exactly one of ['all', 'none', 'skip'] (e.g. 'skip') - A list or array of the above Returns ------- Any|numpy.ndarray """ return self["hoverinfo"] @hoverinfo.setter def hoverinfo(self, val): self["hoverinfo"] = val @property def hoverinfosrc(self): """ Sets the source reference on Chart Studio Cloud for `hoverinfo`. The 'hoverinfosrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["hoverinfosrc"] @hoverinfosrc.setter def hoverinfosrc(self, val): self["hoverinfosrc"] = val @property def hoverlabel(self): """ The 'hoverlabel' property is an instance of Hoverlabel that may be specified as: - An instance of :class:`plotly.graph_objs.contour.Hoverlabel` - A dict of string/value properties that will be passed to the Hoverlabel constructor Returns ------- plotly.graph_objs.contour.Hoverlabel """ return self["hoverlabel"] @hoverlabel.setter def hoverlabel(self, val): self["hoverlabel"] = val @property def hoverongaps(self): """ Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data have hover labels associated with them. The 'hoverongaps' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["hoverongaps"] @hoverongaps.setter def hoverongaps(self, val): self["hoverongaps"] = val @property def hovertemplate(self): """ Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}" as well as %{xother}, {%_xother}, {%_xother_}, {%xother_}. When showing info for several points, "xother" will be added to those with different x positions from the first point. An underscore before or after "(x|y)other" will add a space on that side, only when this field is shown. Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, all attributes that can be specified per- point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example `<extra>%{fullData.name}</extra>`. To hide the secondary box completely, use an empty tag `<extra></extra>`. The 'hovertemplate' property is a string and must be specified as: - A string - A number that will be converted to a string - A tuple, list, or one-dimensional numpy array of the above Returns ------- str|numpy.ndarray """ return self["hovertemplate"] @hovertemplate.setter def hovertemplate(self, val): self["hovertemplate"] = val @property def hovertemplatefallback(self): """ Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. The 'hovertemplatefallback' property accepts values of any type Returns ------- Any """ return self["hovertemplatefallback"] @hovertemplatefallback.setter def hovertemplatefallback(self, val): self["hovertemplatefallback"] = val @property def hovertemplatesrc(self): """ Sets the source reference on Chart Studio Cloud for `hovertemplate`. The 'hovertemplatesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["hovertemplatesrc"] @hovertemplatesrc.setter def hovertemplatesrc(self, val): self["hovertemplatesrc"] = val @property def hovertext(self): """ Same as `text`. The 'hovertext' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["hovertext"] @hovertext.setter def hovertext(self, val): self["hovertext"] = val @property def hovertextsrc(self): """ Sets the source reference on Chart Studio Cloud for `hovertext`. The 'hovertextsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["hovertextsrc"] @hovertextsrc.setter def hovertextsrc(self, val): self["hovertextsrc"] = val @property def ids(self): """ Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. The 'ids' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["ids"] @ids.setter def ids(self, val): self["ids"] = val @property def idssrc(self): """ Sets the source reference on Chart Studio Cloud for `ids`. The 'idssrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["idssrc"] @idssrc.setter def idssrc(self, val): self["idssrc"] = val @property def legend(self): """ Sets the reference to a legend to show this trace in. References to these legends are "legend", "legend2", "legend3", etc. Settings for these legends are set in the layout, under `layout.legend`, `layout.legend2`, etc. The 'legend' property is an identifier of a particular subplot, of type 'legend', that may be specified as the string 'legend' optionally followed by an integer >= 1 (e.g. 'legend', 'legend1', 'legend2', 'legend3', etc.) Returns ------- str """ return self["legend"] @legend.setter def legend(self, val): self["legend"] = val @property def legendgroup(self): """ Sets the legend group for this trace. Traces and shapes part of the same legend group hide/show at the same time when toggling legend items. The 'legendgroup' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["legendgroup"] @legendgroup.setter def legendgroup(self, val): self["legendgroup"] = val @property def legendgrouptitle(self): """ The 'legendgrouptitle' property is an instance of Legendgrouptitle that may be specified as: - An instance of :class:`plotly.graph_objs.contour.Legendgrouptitle` - A dict of string/value properties that will be passed to the Legendgrouptitle constructor Returns ------- plotly.graph_objs.contour.Legendgrouptitle """ return self["legendgrouptitle"] @legendgrouptitle.setter def legendgrouptitle(self, val): self["legendgrouptitle"] = val @property def legendrank(self): """ Sets the legend rank for this trace. Items and groups with smaller ranks are presented on top/left side while with "reversed" `legend.traceorder` they are on bottom/right side. The default legendrank is 1000, so that you can use ranks less than 1000 to place certain items before all unranked items, and ranks greater than 1000 to go after all unranked items. When having unranked or equal rank items shapes would be displayed after traces i.e. according to their order in data and layout. The 'legendrank' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["legendrank"] @legendrank.setter def legendrank(self, val): self["legendrank"] = val @property def legendwidth(self): """ Sets the width (in px or fraction) of the legend for this trace. The 'legendwidth' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ return self["legendwidth"] @legendwidth.setter def legendwidth(self, val): self["legendwidth"] = val @property def line(self): """ The 'line' property is an instance of Line that may be specified as: - An instance of :class:`plotly.graph_objs.contour.Line` - A dict of string/value properties that will be passed to the Line constructor Returns ------- plotly.graph_objs.contour.Line """ return self["line"] @line.setter def line(self, val): self["line"] = val @property def meta(self): """ Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. The 'meta' property accepts values of any type Returns ------- Any|numpy.ndarray """ return self["meta"] @meta.setter def meta(self, val): self["meta"] = val @property def metasrc(self): """ Sets the source reference on Chart Studio Cloud for `meta`. The 'metasrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["metasrc"] @metasrc.setter def metasrc(self, val): self["metasrc"] = val @property def name(self): """ Sets the trace name. The trace name appears as the legend item and on hover. The 'name' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["name"] @name.setter def name(self, val): self["name"] = val @property def ncontours(self): """ Sets the maximum number of contour levels. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is True or if `contours.size` is missing. The 'ncontours' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 9223372036854775807] Returns ------- int """ return self["ncontours"] @ncontours.setter def ncontours(self, val): self["ncontours"] = val @property def opacity(self): """ Sets the opacity of the trace. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ return self["opacity"] @opacity.setter def opacity(self, val): self["opacity"] = val @property def reversescale(self): """ Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. The 'reversescale' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["reversescale"] @reversescale.setter def reversescale(self, val): self["reversescale"] = val @property def showlegend(self): """ Determines whether or not an item corresponding to this trace is shown in the legend. The 'showlegend' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showlegend"] @showlegend.setter def showlegend(self, val): self["showlegend"] = val @property def showscale(self): """ Determines whether or not a colorbar is displayed for this trace. The 'showscale' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["showscale"] @showscale.setter def showscale(self, val): self["showscale"] = val @property def stream(self): """ The 'stream' property is an instance of Stream that may be specified as: - An instance of :class:`plotly.graph_objs.contour.Stream` - A dict of string/value properties that will be passed to the Stream constructor Returns ------- plotly.graph_objs.contour.Stream """ return self["stream"] @stream.setter def stream(self, val): self["stream"] = val @property def text(self): """ Sets the text elements associated with each z value. The 'text' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["text"] @text.setter def text(self, val): self["text"] = val @property def textfont(self): """ For this trace it only has an effect if `coloring` is set to "heatmap". Sets the text font. The 'textfont' property is an instance of Textfont that may be specified as: - An instance of :class:`plotly.graph_objs.contour.Textfont` - A dict of string/value properties that will be passed to the Textfont constructor Returns ------- plotly.graph_objs.contour.Textfont """ return self["textfont"] @textfont.setter def textfont(self, val): self["textfont"] = val @property def textsrc(self): """ Sets the source reference on Chart Studio Cloud for `text`. The 'textsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["textsrc"] @textsrc.setter def textsrc(self, val): self["textsrc"] = val @property def texttemplate(self): """ For this trace it only has an effect if `coloring` is set to "heatmap". Template string used for rendering the information text that appears on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `x`, `y`, `z` and `text`. The 'texttemplate' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["texttemplate"] @texttemplate.setter def texttemplate(self, val): self["texttemplate"] = val @property def texttemplatefallback(self): """ Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. The 'texttemplatefallback' property accepts values of any type Returns ------- Any """ return self["texttemplatefallback"] @texttemplatefallback.setter def texttemplatefallback(self, val): self["texttemplatefallback"] = val @property def transpose(self): """ Transposes the z data. The 'transpose' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["transpose"] @transpose.setter def transpose(self, val): self["transpose"] = val @property def uid(self): """ Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. The 'uid' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["uid"] @uid.setter def uid(self, val): self["uid"] = val @property def uirevision(self): """ Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. The 'uirevision' property accepts values of any type Returns ------- Any """ return self["uirevision"] @uirevision.setter def uirevision(self, val): self["uirevision"] = val @property def visible(self): """ Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). The 'visible' property is an enumeration that may be specified as: - One of the following enumeration values: [True, False, 'legendonly'] Returns ------- Any """ return self["visible"] @visible.setter def visible(self, val): self["visible"] = val @property def x(self): """ Sets the x coordinates. The 'x' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["x"] @x.setter def x(self, val): self["x"] = val @property def x0(self): """ Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. The 'x0' property accepts values of any type Returns ------- Any """ return self["x0"] @x0.setter def x0(self, val): self["x0"] = val @property def xaxis(self): """ Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. The 'xaxis' property is an identifier of a particular subplot, of type 'x', that may be specified as the string 'x' optionally followed by an integer >= 1 (e.g. 'x', 'x1', 'x2', 'x3', etc.) Returns ------- str """ return self["xaxis"] @xaxis.setter def xaxis(self, val): self["xaxis"] = val @property def xcalendar(self): """ Sets the calendar system to use with `x` date data. The 'xcalendar' property is an enumeration that may be specified as: - One of the following enumeration values: ['chinese', 'coptic', 'discworld', 'ethiopian', 'gregorian', 'hebrew', 'islamic', 'jalali', 'julian', 'mayan', 'nanakshahi', 'nepali', 'persian', 'taiwan', 'thai', 'ummalqura'] Returns ------- Any """ return self["xcalendar"] @xcalendar.setter def xcalendar(self, val): self["xcalendar"] = val @property def xhoverformat(self): """ Sets the hover text formatting rulefor `x` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display *09~15~23.46*By default the values are formatted using `xaxis.hoverformat`. The 'xhoverformat' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["xhoverformat"] @xhoverformat.setter def xhoverformat(self, val): self["xhoverformat"] = val @property def xperiod(self): """ Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the x axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. The 'xperiod' property accepts values of any type Returns ------- Any """ return self["xperiod"] @xperiod.setter def xperiod(self, val): self["xperiod"] = val @property def xperiod0(self): """ Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the x0 axis. When `x0period` is round number of weeks, the `x0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. The 'xperiod0' property accepts values of any type Returns ------- Any """ return self["xperiod0"] @xperiod0.setter def xperiod0(self, val): self["xperiod0"] = val @property def xperiodalignment(self): """ Only relevant when the axis `type` is "date". Sets the alignment of data points on the x axis. The 'xperiodalignment' property is an enumeration that may be specified as: - One of the following enumeration values: ['start', 'middle', 'end'] Returns ------- Any """ return self["xperiodalignment"] @xperiodalignment.setter def xperiodalignment(self, val): self["xperiodalignment"] = val @property def xsrc(self): """ Sets the source reference on Chart Studio Cloud for `x`. The 'xsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["xsrc"] @xsrc.setter def xsrc(self, val): self["xsrc"] = val @property def xtype(self): """ If "array", the heatmap's x coordinates are given by "x" (the default behavior when `x` is provided). If "scaled", the heatmap's x coordinates are given by "x0" and "dx" (the default behavior when `x` is not provided). The 'xtype' property is an enumeration that may be specified as: - One of the following enumeration values: ['array', 'scaled'] Returns ------- Any """ return self["xtype"] @xtype.setter def xtype(self, val): self["xtype"] = val @property def y(self): """ Sets the y coordinates. The 'y' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["y"] @y.setter def y(self, val): self["y"] = val @property def y0(self): """ Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. The 'y0' property accepts values of any type Returns ------- Any """ return self["y0"] @y0.setter def y0(self, val): self["y0"] = val @property def yaxis(self): """ Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. The 'yaxis' property is an identifier of a particular subplot, of type 'y', that may be specified as the string 'y' optionally followed by an integer >= 1 (e.g. 'y', 'y1', 'y2', 'y3', etc.) Returns ------- str """ return self["yaxis"] @yaxis.setter def yaxis(self, val): self["yaxis"] = val @property def ycalendar(self): """ Sets the calendar system to use with `y` date data. The 'ycalendar' property is an enumeration that may be specified as: - One of the following enumeration values: ['chinese', 'coptic', 'discworld', 'ethiopian', 'gregorian', 'hebrew', 'islamic', 'jalali', 'julian', 'mayan', 'nanakshahi', 'nepali', 'persian', 'taiwan', 'thai', 'ummalqura'] Returns ------- Any """ return self["ycalendar"] @ycalendar.setter def ycalendar(self, val): self["ycalendar"] = val @property def yhoverformat(self): """ Sets the hover text formatting rulefor `y` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display *09~15~23.46*By default the values are formatted using `yaxis.hoverformat`. The 'yhoverformat' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["yhoverformat"] @yhoverformat.setter def yhoverformat(self, val): self["yhoverformat"] = val @property def yperiod(self): """ Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the y axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. The 'yperiod' property accepts values of any type Returns ------- Any """ return self["yperiod"] @yperiod.setter def yperiod(self, val): self["yperiod"] = val @property def yperiod0(self): """ Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the y0 axis. When `y0period` is round number of weeks, the `y0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. The 'yperiod0' property accepts values of any type Returns ------- Any """ return self["yperiod0"] @yperiod0.setter def yperiod0(self, val): self["yperiod0"] = val @property def yperiodalignment(self): """ Only relevant when the axis `type` is "date". Sets the alignment of data points on the y axis. The 'yperiodalignment' property is an enumeration that may be specified as: - One of the following enumeration values: ['start', 'middle', 'end'] Returns ------- Any """ return self["yperiodalignment"] @yperiodalignment.setter def yperiodalignment(self, val): self["yperiodalignment"] = val @property def ysrc(self): """ Sets the source reference on Chart Studio Cloud for `y`. The 'ysrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["ysrc"] @ysrc.setter def ysrc(self, val): self["ysrc"] = val @property def ytype(self): """ If "array", the heatmap's y coordinates are given by "y" (the default behavior when `y` is provided) If "scaled", the heatmap's y coordinates are given by "y0" and "dy" (the default behavior when `y` is not provided) The 'ytype' property is an enumeration that may be specified as: - One of the following enumeration values: ['array', 'scaled'] Returns ------- Any """ return self["ytype"] @ytype.setter def ytype(self, val): self["ytype"] = val @property def z(self): """ Sets the z data. The 'z' property is an array that may be specified as a tuple, list, numpy array, or pandas Series Returns ------- numpy.ndarray """ return self["z"] @z.setter def z(self, val): self["z"] = val @property def zauto(self): """ Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. The 'zauto' property must be specified as a bool (either True, or False) Returns ------- bool """ return self["zauto"] @zauto.setter def zauto(self, val): self["zauto"] = val @property def zhoverformat(self): """ Sets the hover text formatting rulefor `z` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. The 'zhoverformat' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["zhoverformat"] @zhoverformat.setter def zhoverformat(self, val): self["zhoverformat"] = val @property def zmax(self): """ Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. The 'zmax' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["zmax"] @zmax.setter def zmax(self, val): self["zmax"] = val @property def zmid(self): """ Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. The 'zmid' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["zmid"] @zmid.setter def zmid(self, val): self["zmid"] = val @property def zmin(self): """ Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. The 'zmin' property is a number and may be specified as: - An int or float Returns ------- int|float """ return self["zmin"] @zmin.setter def zmin(self, val): self["zmin"] = val @property def zorder(self): """ Sets the layer on which this trace is displayed, relative to other SVG traces on the same subplot. SVG traces with higher `zorder` appear in front of those with lower `zorder`. The 'zorder' property is a integer and may be specified as: - An int (or float that will be cast to an int) Returns ------- int """ return self["zorder"] @zorder.setter def zorder(self, val): self["zorder"] = val @property def zsrc(self): """ Sets the source reference on Chart Studio Cloud for `z`. The 'zsrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["zsrc"] @zsrc.setter def zsrc(self, val): self["zsrc"] = val @property def type(self): return self._props["type"] @property def _prop_descriptions(self): return """\ autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. autocontour Determines whether or not the contour level attributes are picked by an algorithm. If True, the number of contour levels can be set in `ncontours`. If False, set the contour level attributes in `contours`. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.contour.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in. It is defaulted to true if `z` is a one dimensional array otherwise it is defaulted to false. contours :class:`plotly.graph_objects.contour.Contours` instance or dict with compatible properties customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for `customdata`. dx Sets the x coordinate step. See `x0` for more info. dy Sets the y coordinate step. See `y0` for more info. fillcolor Sets the fill color if `contours.type` is "constraint". Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for `hoverinfo`. hoverlabel :class:`plotly.graph_objects.contour.Hoverlabel` instance or dict with compatible properties hoverongaps Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data have hover labels associated with them. hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}" as well as %{xother}, {%_xother}, {%_xother_}, {%xother_}. When showing info for several points, "xother" will be added to those with different x positions from the first point. An underscore before or after "(x|y)other" will add a space on that side, only when this field is shown. Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example `<extra>%{fullData.name}</extra>`. To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for `hovertext`. ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for `ids`. legend Sets the reference to a legend to show this trace in. References to these legends are "legend", "legend2", "legend3", etc. Settings for these legends are set in the layout, under `layout.legend`, `layout.legend2`, etc. legendgroup Sets the legend group for this trace. Traces and shapes part of the same legend group hide/show at the same time when toggling legend items. legendgrouptitle :class:`plotly.graph_objects.contour.Legendgrouptitle` instance or dict with compatible properties legendrank Sets the legend rank for this trace. Items and groups with smaller ranks are presented on top/left side while with "reversed" `legend.traceorder` they are on bottom/right side. The default legendrank is 1000, so that you can use ranks less than 1000 to place certain items before all unranked items, and ranks greater than 1000 to go after all unranked items. When having unranked or equal rank items shapes would be displayed after traces i.e. according to their order in data and layout. legendwidth Sets the width (in px or fraction) of the legend for this trace. line :class:`plotly.graph_objects.contour.Line` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for `meta`. name Sets the trace name. The trace name appears as the legend item and on hover. ncontours Sets the maximum number of contour levels. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is True or if `contours.size` is missing. opacity Sets the opacity of the trace. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.contour.Stream` instance or dict with compatible properties text Sets the text elements associated with each z value. textfont For this trace it only has an effect if `coloring` is set to "heatmap". Sets the text font. textsrc Sets the source reference on Chart Studio Cloud for `text`. texttemplate For this trace it only has an effect if `coloring` is set to "heatmap". Template string used for rendering the information text that appears on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `x`, `y`, `z` and `text`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. transpose Transposes the z data. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the x coordinates. x0 Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xcalendar Sets the calendar system to use with `x` date data. xhoverformat Sets the hover text formatting rulefor `x` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display *09~15~23.46*By default the values are formatted using `xaxis.hoverformat`. xperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the x axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. xperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the x0 axis. When `x0period` is round number of weeks, the `x0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. xperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the x axis. xsrc Sets the source reference on Chart Studio Cloud for `x`. xtype If "array", the heatmap's x coordinates are given by "x" (the default behavior when `x` is provided). If "scaled", the heatmap's x coordinates are given by "x0" and "dx" (the default behavior when `x` is not provided). y Sets the y coordinates. y0 Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ycalendar Sets the calendar system to use with `y` date data. yhoverformat Sets the hover text formatting rulefor `y` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display *09~15~23.46*By default the values are formatted using `yaxis.hoverformat`. yperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the y axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. yperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the y0 axis. When `y0period` is round number of weeks, the `y0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. yperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the y axis. ysrc Sets the source reference on Chart Studio Cloud for `y`. ytype If "array", the heatmap's y coordinates are given by "y" (the default behavior when `y` is provided) If "scaled", the heatmap's y coordinates are given by "y0" and "dy" (the default behavior when `y` is not provided) z Sets the z data. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zhoverformat Sets the hover text formatting rulefor `z` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d 3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zorder Sets the layer on which this trace is displayed, relative to other SVG traces on the same subplot. SVG traces with higher `zorder` appear in front of those with lower `zorder`. zsrc Sets the source reference on Chart Studio Cloud for `z`. """ def __init__( self, arg=None, autocolorscale=None, autocontour=None, coloraxis=None, colorbar=None, colorscale=None, connectgaps=None, contours=None, customdata=None, customdatasrc=None, dx=None, dy=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoverongaps=None, hovertemplate=None, hovertemplatefallback=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legend=None, legendgroup=None, legendgrouptitle=None, legendrank=None, legendwidth=None, line=None, meta=None, metasrc=None, name=None, ncontours=None, opacity=None, reversescale=None, showlegend=None, showscale=None, stream=None, text=None, textfont=None, textsrc=None, texttemplate=None, texttemplatefallback=None, transpose=None, uid=None, uirevision=None, visible=None, x=None, x0=None, xaxis=None, xcalendar=None, xhoverformat=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, xtype=None, y=None, y0=None, yaxis=None, ycalendar=None, yhoverformat=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, ytype=None, z=None, zauto=None, zhoverformat=None, zmax=None, zmid=None, zmin=None, zorder=None, zsrc=None, **kwargs, ): """ Construct a new Contour object The data from which contour lines are computed is set in `z`. Data in `z` must be a 2D list of numbers. Say that `z` has N rows and M columns, then by default, these N rows correspond to N y coordinates (set in `y` or auto-generated) and the M columns correspond to M x coordinates (set in `x` or auto- generated). By setting `transpose` to True, the above behavior is flipped. Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.Contour` autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. autocontour Determines whether or not the contour level attributes are picked by an algorithm. If True, the number of contour levels can be set in `ncontours`. If False, set the contour level attributes in `contours`. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.contour.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use `zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Blackbody,Bluered,Blues,C ividis,Earth,Electric,Greens,Greys,Hot,Jet,Picnic,Portl and,Rainbow,RdBu,Reds,Viridis,YlGnBu,YlOrRd. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in. It is defaulted to true if `z` is a one dimensional array otherwise it is defaulted to false. contours :class:`plotly.graph_objects.contour.Contours` instance or dict with compatible properties customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for `customdata`. dx Sets the x coordinate step. See `x0` for more info. dy Sets the y coordinate step. See `y0` for more info. fillcolor Sets the fill color if `contours.type` is "constraint". Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for `hoverinfo`. hoverlabel :class:`plotly.graph_objects.contour.Hoverlabel` instance or dict with compatible properties hoverongaps Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data have hover labels associated with them. hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}" as well as %{xother}, {%_xother}, {%_xother_}, {%xother_}. When showing info for several points, "xother" will be added to those with different x positions from the first point. An underscore before or after "(x|y)other" will add a space on that side, only when this field is shown. Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, all attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example `<extra>%{fullData.name}</extra>`. To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. hovertemplatesrc Sets the source reference on Chart Studio Cloud for `hovertemplate`. hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for `hovertext`. ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for `ids`. legend Sets the reference to a legend to show this trace in. References to these legends are "legend", "legend2", "legend3", etc. Settings for these legends are set in the layout, under `layout.legend`, `layout.legend2`, etc. legendgroup Sets the legend group for this trace. Traces and shapes part of the same legend group hide/show at the same time when toggling legend items. legendgrouptitle :class:`plotly.graph_objects.contour.Legendgrouptitle` instance or dict with compatible properties legendrank Sets the legend rank for this trace. Items and groups with smaller ranks are presented on top/left side while with "reversed" `legend.traceorder` they are on bottom/right side. The default legendrank is 1000, so that you can use ranks less than 1000 to place certain items before all unranked items, and ranks greater than 1000 to go after all unranked items. When having unranked or equal rank items shapes would be displayed after traces i.e. according to their order in data and layout. legendwidth Sets the width (in px or fraction) of the legend for this trace. line :class:`plotly.graph_objects.contour.Line` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for `meta`. name Sets the trace name. The trace name appears as the legend item and on hover. ncontours Sets the maximum number of contour levels. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is True or if `contours.size` is missing. opacity Sets the opacity of the trace. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.contour.Stream` instance or dict with compatible properties text Sets the text elements associated with each z value. textfont For this trace it only has an effect if `coloring` is set to "heatmap". Sets the text font. textsrc Sets the source reference on Chart Studio Cloud for `text`. texttemplate For this trace it only has an effect if `coloring` is set to "heatmap". Template string used for rendering the information text that appears on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-format/tree/v1.4.5#d3-format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format for details on the date formatting syntax. Variables that can't be found will be replaced with the specifier. For example, a template of "data: %{x}, %{y}" will result in a value of "data: 1, %{y}" if x is 1 and y is missing. Variables with an undefined value will be replaced with the fallback value. All attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Finally, the template string has access to variables `x`, `y`, `z` and `text`. texttemplatefallback Fallback string that's displayed when a variable referenced in a template is missing. If the boolean value 'false' is passed in, the specifier with the missing variable will be displayed. transpose Transposes the z data. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the x coordinates. x0 Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xcalendar Sets the calendar system to use with `x` date data. xhoverformat Sets the hover text formatting rulefor `x` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display *09~15~23.46*By default the values are formatted using `xaxis.hoverformat`. xperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the x axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. xperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the x0 axis. When `x0period` is round number of weeks, the `x0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. xperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the x axis. xsrc Sets the source reference on Chart Studio Cloud for `x`. xtype If "array", the heatmap's x coordinates are given by "x" (the default behavior when `x` is provided). If "scaled", the heatmap's x coordinates are given by "x0" and "dx" (the default behavior when `x` is not provided). y Sets the y coordinates. y0 Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ycalendar Sets the calendar system to use with `y` date data. yhoverformat Sets the hover text formatting rulefor `y` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d3/d3-format/tree/v1.4.5#d3-format. And for dates see: https://github.com/d3/d3-time- format/tree/v2.2.3#locale_format. We add two items to d3's date formatter: "%h" for half of the year as a decimal number as well as "%{n}f" for fractional seconds with n digits. For example, *2016-10-13 09:15:23.456* with tickformat "%H~%M~%S.%2f" would display *09~15~23.46*By default the values are formatted using `yaxis.hoverformat`. yperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the y axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. yperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the y0 axis. When `y0period` is round number of weeks, the `y0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. yperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the y axis. ysrc Sets the source reference on Chart Studio Cloud for `y`. ytype If "array", the heatmap's y coordinates are given by "y" (the default behavior when `y` is provided) If "scaled", the heatmap's y coordinates are given by "y0" and "dy" (the default behavior when `y` is not provided) z Sets the z data. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zhoverformat Sets the hover text formatting rulefor `z` using d3 formatting mini-languages which are very similar to those in Python. For numbers, see: https://github.com/d 3/d3-format/tree/v1.4.5#d3-format.By default the values are formatted using generic number format. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zorder Sets the layer on which this trace is displayed, relative to other SVG traces on the same subplot. SVG traces with higher `zorder` appear in front of those with lower `zorder`. zsrc Sets the source reference on Chart Studio Cloud for `z`. Returns ------- Contour """ super().__init__("contour") if "_parent" in kwargs: self._parent = kwargs["_parent"] return if arg is None: arg = {} elif isinstance(arg, self.__class__): arg = arg.to_plotly_json() elif isinstance(arg, dict): arg = _copy.copy(arg) else: raise ValueError("""\ The first argument to the plotly.graph_objs.Contour constructor must be a dict or an instance of :class:`plotly.graph_objs.Contour`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("autocolorscale", arg, autocolorscale) self._set_property("autocontour", arg, autocontour) self._set_property("coloraxis", arg, coloraxis) self._set_property("colorbar", arg, colorbar) self._set_property("colorscale", arg, colorscale) self._set_property("connectgaps", arg, connectgaps) self._set_property("contours", arg, contours) self._set_property("customdata", arg, customdata) self._set_property("customdatasrc", arg, customdatasrc) self._set_property("dx", arg, dx) self._set_property("dy", arg, dy) self._set_property("fillcolor", arg, fillcolor) self._set_property("hoverinfo", arg, hoverinfo) self._set_property("hoverinfosrc", arg, hoverinfosrc) self._set_property("hoverlabel", arg, hoverlabel) self._set_property("hoverongaps", arg, hoverongaps) self._set_property("hovertemplate", arg, hovertemplate) self._set_property("hovertemplatefallback", arg, hovertemplatefallback) self._set_property("hovertemplatesrc", arg, hovertemplatesrc) self._set_property("hovertext", arg, hovertext) self._set_property("hovertextsrc", arg, hovertextsrc) self._set_property("ids", arg, ids) self._set_property("idssrc", arg, idssrc) self._set_property("legend", arg, legend) self._set_property("legendgroup", arg, legendgroup) self._set_property("legendgrouptitle", arg, legendgrouptitle) self._set_property("legendrank", arg, legendrank) self._set_property("legendwidth", arg, legendwidth) self._set_property("line", arg, line) self._set_property("meta", arg, meta) self._set_property("metasrc", arg, metasrc) self._set_property("name", arg, name) self._set_property("ncontours", arg, ncontours) self._set_property("opacity", arg, opacity) self._set_property("reversescale", arg, reversescale) self._set_property("showlegend", arg, showlegend) self._set_property("showscale", arg, showscale) self._set_property("stream", arg, stream) self._set_property("text", arg, text) self._set_property("textfont", arg, textfont) self._set_property("textsrc", arg, textsrc) self._set_property("texttemplate", arg, texttemplate) self._set_property("texttemplatefallback", arg, texttemplatefallback) self._set_property("transpose", arg, transpose) self._set_property("uid", arg, uid) self._set_property("uirevision", arg, uirevision) self._set_property("visible", arg, visible) self._set_property("x", arg, x) self._set_property("x0", arg, x0) self._set_property("xaxis", arg, xaxis) self._set_property("xcalendar", arg, xcalendar) self._set_property("xhoverformat", arg, xhoverformat) self._set_property("xperiod", arg, xperiod) self._set_property("xperiod0", arg, xperiod0) self._set_property("xperiodalignment", arg, xperiodalignment) self._set_property("xsrc", arg, xsrc) self._set_property("xtype", arg, xtype) self._set_property("y", arg, y) self._set_property("y0", arg, y0) self._set_property("yaxis", arg, yaxis) self._set_property("ycalendar", arg, ycalendar) self._set_property("yhoverformat", arg, yhoverformat) self._set_property("yperiod", arg, yperiod) self._set_property("yperiod0", arg, yperiod0) self._set_property("yperiodalignment", arg, yperiodalignment) self._set_property("ysrc", arg, ysrc) self._set_property("ytype", arg, ytype) self._set_property("z", arg, z) self._set_property("zauto", arg, zauto) self._set_property("zhoverformat", arg, zhoverformat) self._set_property("zmax", arg, zmax) self._set_property("zmid", arg, zmid) self._set_property("zmin", arg, zmin) self._set_property("zorder", arg, zorder) self._set_property("zsrc", arg, zsrc) self._props["type"] = "contour" arg.pop("type", None) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Contour
python
coleifer__peewee
tests/shortcuts.py
{ "start": 27698, "end": 27742 }
class ____(TSBase): key = TextField()
TSReg
python
streamlit__streamlit
lib/streamlit/errors.py
{ "start": 838, "end": 1110 }
class ____(Exception): """The base class for all exceptions thrown by Streamlit. Should be used for exceptions raised due to user errors (typically via StreamlitAPIException) as well as exceptions raised by Streamlit's internal code. """ pass
Error
python
donnemartin__interactive-coding-challenges
arrays_strings/permutation/test_permutation_solution.py
{ "start": 18, "end": 855 }
class ____(unittest.TestCase): def test_permutation(self, func): self.assertEqual(func(None, 'foo'), False) self.assertEqual(func('', 'foo'), False) self.assertEqual(func('Nib', 'bin'), False) self.assertEqual(func('act', 'cat'), True) self.assertEqual(func('a ct', 'ca t'), True) self.assertEqual(func('dog', 'doggo'), False) print('Success: test_permutation') def main(): test = TestPermutation() permutations = Permutations() test.test_permutation(permutations.is_permutation) try: permutations_alt = PermutationsAlt() test.test_permutation(permutations_alt.is_permutation) except NameError: # Alternate solutions are only defined # in the solutions file pass if __name__ == '__main__': main()
TestPermutation
python
ray-project__ray
python/ray/data/_internal/issue_detection/detectors/hash_shuffle_detector.py
{ "start": 783, "end": 5333 }
class ____(IssueDetector): """Detector for hash shuffle aggregator health issues.""" def __init__( self, dataset_id: str, operators: List["PhysicalOperator"], config: HashShuffleAggregatorIssueDetectorConfig, ): self._dataset_id = dataset_id self._operators = operators self._detector_cfg = config self._last_warning_times = {} # Track per-operator warning times @classmethod def from_executor( cls, executor: "StreamingExecutor" ) -> "HashShuffleAggregatorIssueDetector": """Factory method to create a HashShuffleAggregatorIssueDetector from a StreamingExecutor. Args: executor: The StreamingExecutor instance to extract dependencies from. Returns: An instance of HashShuffleAggregatorIssueDetector. """ operators = list(executor._topology.keys()) if executor._topology else [] ctx = executor._data_context return cls( dataset_id=executor._dataset_id, operators=operators, config=ctx.issue_detectors_config.hash_shuffle_detector_config, ) def detect(self) -> List[Issue]: issues = [] current_time = time.time() # Find all hash shuffle operators in the topology for op in self._operators: if not isinstance(op, HashShuffleOperator): continue # Skip if operator doesn't have aggregator pool yet if op._aggregator_pool is None: continue pool = op._aggregator_pool aggregator_info = pool.check_aggregator_health() if aggregator_info is None: continue # Check if we should emit a warning for this operator should_warn = self._should_emit_warning( op.id, current_time, aggregator_info ) if should_warn: message = self._format_health_warning(aggregator_info) issues.append( Issue( dataset_name=self._dataset_id, operator_id=op.id, issue_type=IssueType.HANGING, message=message, ) ) self._last_warning_times[op.id] = current_time return issues def detection_time_interval_s(self) -> float: return self._detector_cfg.detection_time_interval_s def _should_emit_warning( self, op_id: str, current_time: float, info: AggregatorHealthInfo ) -> bool: """Check if we should emit a warning for this operator.""" if not info.has_unready_aggregators: # Clear warning time if all aggregators are healthy self._last_warning_times.pop(op_id, None) return False # Check if enough time has passed since start if current_time - info.started_at < self._detector_cfg.min_wait_time_s: return False # Check if enough time has passed since last warning last_warning = self._last_warning_times.get(op_id) if last_warning is None: return True return current_time - last_warning >= self.detection_time_interval_s() def _format_health_warning(self, info: AggregatorHealthInfo) -> str: """Format the health warning message.""" available_resources = ray.available_resources() available_cpus = available_resources.get("CPU", 0) cluster_resources = ray.cluster_resources() total_memory = cluster_resources.get("memory", 0) available_memory = available_resources.get("memory", 0) return ( f"Only {info.ready_aggregators} out of {info.total_aggregators} " f"hash-shuffle aggregators are ready after {info.wait_time:.1f} secs. " f"This might indicate resource contention for cluster resources " f"(available CPUs: {available_cpus}, required CPUs: {info.required_resources.cpu}). " f"Cluster only has {available_memory / GiB:.2f} GiB available memory, required memory: {info.required_resources.memory / GiB:.2f} GiB. " f"{total_memory / GiB:.2f} GiB total memory. " f"Consider increasing cluster size or reducing the number of aggregators " f"via `DataContext.max_hash_shuffle_aggregators`. " f"Will continue checking every {self.detection_time_interval_s()}s." )
HashShuffleAggregatorIssueDetector
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_cloud_memorystore.py
{ "start": 2824, "end": 4097 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.cloud_memorystore.CloudMemorystoreHook") def test_assert_valid_hook_call(self, mock_hook): task = CloudMemorystoreCreateInstanceOperator( task_id=TEST_TASK_ID, location=TEST_LOCATION, instance_id=TEST_INSTANCE_ID, instance=TEST_INSTANCE, project_id=TEST_PROJECT_ID, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, gcp_conn_id=TEST_GCP_CONN_ID, impersonation_chain=TEST_IMPERSONATION_CHAIN, ) mock_hook.return_value.create_instance.return_value = Instance(name=TEST_NAME) task.execute(mock.MagicMock()) mock_hook.assert_called_once_with( gcp_conn_id=TEST_GCP_CONN_ID, impersonation_chain=TEST_IMPERSONATION_CHAIN, ) mock_hook.return_value.create_instance.assert_called_once_with( location=TEST_LOCATION, instance_id=TEST_INSTANCE_ID, instance=TEST_INSTANCE, project_id=TEST_PROJECT_ID, retry=TEST_RETRY, timeout=TEST_TIMEOUT, metadata=TEST_METADATA, )
TestCloudMemorystoreCreateInstanceOperator
python
PyCQA__pylint
pylint/config/argument.py
{ "start": 6178, "end": 6990 }
class ____(_Argument): """Base class for store arguments to be parsed by an argparse.ArgumentsParser. This is based on the parameters passed to argparse.ArgumentsParser.add_message. See: https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.add_argument """ def __init__( self, *, flags: list[str], action: str, default: _ArgumentTypes, arg_help: str, hide_help: bool, section: str | None, ) -> None: super().__init__( flags=flags, arg_help=arg_help, hide_help=hide_help, section=section ) self.action = action """The action to perform with the argument.""" self.default = default """The default value of the argument."""
_BaseStoreArgument
python
pyinstaller__pyinstaller
bootloader/waflib/Tools/qt5.py
{ "start": 3351, "end": 3451 }
class ____(Task.Task): run_str = '${QT_LUPDATE} ${SRC} -ts ${TGT}' color = 'BLUE'
trans_update
python
allegroai__clearml
clearml/backend_api/services/v2_23/pipelines.py
{ "start": 2994, "end": 4837 }
class ____(Response): """ Response of pipelines.start_pipeline endpoint. :param pipeline: ID of the new pipeline task :type pipeline: str :param enqueued: True if the task was successfully enqueued :type enqueued: bool """ _service = "pipelines" _action = "start_pipeline" _version = "2.23" _schema = { "definitions": {}, "properties": { "enqueued": { "description": "True if the task was successfully enqueued", "type": ["boolean", "null"], }, "pipeline": { "description": "ID of the new pipeline task", "type": ["string", "null"], }, }, "type": "object", } def __init__(self, pipeline: Optional[str] = None, enqueued: Optional[bool] = None, **kwargs: Any) -> None: super(StartPipelineResponse, self).__init__(**kwargs) self.pipeline = pipeline self.enqueued = enqueued @schema_property("pipeline") def pipeline(self) -> Optional[str]: return self._property_pipeline @pipeline.setter def pipeline(self, value: Optional[str]) -> None: if value is None: self._property_pipeline = None return self.assert_isinstance(value, "pipeline", six.string_types) self._property_pipeline = value @schema_property("enqueued") def enqueued(self) -> Optional[bool]: return self._property_enqueued @enqueued.setter def enqueued(self, value: Optional[bool]) -> None: if value is None: self._property_enqueued = None return self.assert_isinstance(value, "enqueued", (bool,)) self._property_enqueued = value response_mapping = {StartPipelineRequest: StartPipelineResponse}
StartPipelineResponse
python
kubernetes-client__python
kubernetes/client/models/v1_container_port.py
{ "start": 383, "end": 7629 }
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 = { 'container_port': 'int', 'host_ip': 'str', 'host_port': 'int', 'name': 'str', 'protocol': 'str' } attribute_map = { 'container_port': 'containerPort', 'host_ip': 'hostIP', 'host_port': 'hostPort', 'name': 'name', 'protocol': 'protocol' } def __init__(self, container_port=None, host_ip=None, host_port=None, name=None, protocol=None, local_vars_configuration=None): # noqa: E501 """V1ContainerPort - 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._container_port = None self._host_ip = None self._host_port = None self._name = None self._protocol = None self.discriminator = None self.container_port = container_port if host_ip is not None: self.host_ip = host_ip if host_port is not None: self.host_port = host_port if name is not None: self.name = name if protocol is not None: self.protocol = protocol @property def container_port(self): """Gets the container_port of this V1ContainerPort. # noqa: E501 Number of port to expose on the pod's IP address. This must be a valid port number, 0 < x < 65536. # noqa: E501 :return: The container_port of this V1ContainerPort. # noqa: E501 :rtype: int """ return self._container_port @container_port.setter def container_port(self, container_port): """Sets the container_port of this V1ContainerPort. Number of port to expose on the pod's IP address. This must be a valid port number, 0 < x < 65536. # noqa: E501 :param container_port: The container_port of this V1ContainerPort. # noqa: E501 :type: int """ if self.local_vars_configuration.client_side_validation and container_port is None: # noqa: E501 raise ValueError("Invalid value for `container_port`, must not be `None`") # noqa: E501 self._container_port = container_port @property def host_ip(self): """Gets the host_ip of this V1ContainerPort. # noqa: E501 What host IP to bind the external port to. # noqa: E501 :return: The host_ip of this V1ContainerPort. # noqa: E501 :rtype: str """ return self._host_ip @host_ip.setter def host_ip(self, host_ip): """Sets the host_ip of this V1ContainerPort. What host IP to bind the external port to. # noqa: E501 :param host_ip: The host_ip of this V1ContainerPort. # noqa: E501 :type: str """ self._host_ip = host_ip @property def host_port(self): """Gets the host_port of this V1ContainerPort. # noqa: E501 Number of port to expose on the host. If specified, this must be a valid port number, 0 < x < 65536. If HostNetwork is specified, this must match ContainerPort. Most containers do not need this. # noqa: E501 :return: The host_port of this V1ContainerPort. # noqa: E501 :rtype: int """ return self._host_port @host_port.setter def host_port(self, host_port): """Sets the host_port of this V1ContainerPort. Number of port to expose on the host. If specified, this must be a valid port number, 0 < x < 65536. If HostNetwork is specified, this must match ContainerPort. Most containers do not need this. # noqa: E501 :param host_port: The host_port of this V1ContainerPort. # noqa: E501 :type: int """ self._host_port = host_port @property def name(self): """Gets the name of this V1ContainerPort. # noqa: E501 If specified, this must be an IANA_SVC_NAME and unique within the pod. Each named port in a pod must have a unique name. Name for the port that can be referred to by services. # noqa: E501 :return: The name of this V1ContainerPort. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this V1ContainerPort. If specified, this must be an IANA_SVC_NAME and unique within the pod. Each named port in a pod must have a unique name. Name for the port that can be referred to by services. # noqa: E501 :param name: The name of this V1ContainerPort. # noqa: E501 :type: str """ self._name = name @property def protocol(self): """Gets the protocol of this V1ContainerPort. # noqa: E501 Protocol for port. Must be UDP, TCP, or SCTP. Defaults to \"TCP\". # noqa: E501 :return: The protocol of this V1ContainerPort. # noqa: E501 :rtype: str """ return self._protocol @protocol.setter def protocol(self, protocol): """Sets the protocol of this V1ContainerPort. Protocol for port. Must be UDP, TCP, or SCTP. Defaults to \"TCP\". # noqa: E501 :param protocol: The protocol of this V1ContainerPort. # noqa: E501 :type: str """ self._protocol = protocol 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, V1ContainerPort): 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, V1ContainerPort): return True return self.to_dict() != other.to_dict()
V1ContainerPort
python
django__django
tests/migrations/test_migrations_fake_split_initial/0001_initial.py
{ "start": 43, "end": 866 }
class ____(migrations.Migration): initial = True operations = [ migrations.CreateModel( "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=255)), ("slug", models.SlugField(null=True)), ("age", models.IntegerField(default=0)), ("silly_field", models.BooleanField(default=False)), ], ), migrations.CreateModel( "Tribble", [ ("id", models.AutoField(primary_key=True)), ("fluffy", models.BooleanField(default=True)), ], ), migrations.AlterUniqueTogether( name="author", unique_together={("name", "slug")}, ), ]
Migration
python
Pylons__pyramid
src/pyramid/httpexceptions.py
{ "start": 19174, "end": 19454 }
class ____(_HTTPMove): """ subclass of :class:`~_HTTPMove` This indicates that the requested resource resides temporarily under a different URI. code: 307, title: Temporary Redirect """ code = 307 title = 'Temporary Redirect'
HTTPTemporaryRedirect
python
airbytehq__airbyte
airbyte-integrations/connectors/source-linkedin-ads/components.py
{ "start": 4833, "end": 5771 }
class ____(RecordExtractor): """ Extracts and transforms LinkedIn Ads records, ensuring that 'lastModified' and 'created' date-time fields are formatted to RFC3339. """ def _date_time_to_rfc3339(self, record: MutableMapping[str, Any]) -> MutableMapping[str, Any]: """ Converts 'lastModified' and 'created' fields in the record to RFC3339 format. """ for item in ["lastModified", "created"]: if record.get(item) is not None: record[item] = ab_datetime_parse(record[item]).to_datetime().isoformat() return record def extract_records(self, response: requests.Response) -> Iterable[Mapping[str, Any]]: """ Extracts and transforms records from an HTTP response. """ for record in transform_data(response.json().get("elements")): yield self._date_time_to_rfc3339(record) @dataclass
LinkedInAdsRecordExtractor
python
spyder-ide__spyder
spyder/plugins/console/widgets/main_widget.py
{ "start": 2408, "end": 20208 }
class ____(PluginMainWidget): # --- Signals # This signal emits a parsed error traceback text so we can then # request opening the file that traceback comes from in the Editor. sig_edit_goto_requested = Signal(str, int, str) # TODO: I do not think we use this? sig_focus_changed = Signal() # Emit this when the interpreter buffer is flushed sig_refreshed = Signal() # Request to show a status message on the main window sig_show_status_requested = Signal(str) sig_help_requested = Signal(dict) """ This signal is emitted to request help on a given object `name`. Parameters ---------- help_data: dict Example `{'name': str, 'ignore_unknown': bool}`. """ def __init__(self, name, plugin, parent=None): super().__init__(name, plugin, parent) logger.info("Initializing...") # Traceback MessageBox self.error_traceback = '' self.dismiss_error = False # Header message message = _( "Spyder Internal Console\n\n" "This console is used to report application\n" "internal errors and to inspect Spyder\n" "internals with the following commands:\n" " spy.app, spy.window, dir(spy)\n\n" "Please do not use it to run your code\n\n" ) # Options that come from the command line cli_options = plugin.get_command_line_options() profile = cli_options.profile multithreaded = cli_options.multithreaded # Widgets self.dialog_manager = DialogManager() self.error_dlg = None self.shell = InternalShell( # TODO: Move to use SpyderWidgetMixin? parent=parent, commands=[], message=message, max_line_count=self.get_conf('max_line_count'), profile=profile, multithreaded=multithreaded, ) self.find_widget = FindReplace(self) # Setup self.setAcceptDrops(True) self.find_widget.set_editor(self.shell) self.find_widget.hide() self.shell.toggle_wrap_mode(self.get_conf('wrap')) # Layout layout = QVBoxLayout() layout.setSpacing(0) layout.addWidget(self.shell) layout.addWidget(self.find_widget) self.setLayout(layout) # Signals self.shell.sig_help_requested.connect(self.sig_help_requested) self.shell.sig_exception_occurred.connect(self.handle_exception) self.shell.sig_focus_changed.connect(self.sig_focus_changed) self.shell.sig_go_to_error_requested.connect(self.go_to_error) self.shell.sig_redirect_stdio_requested.connect( self.sig_redirect_stdio_requested) self.shell.sig_refreshed.connect(self.sig_refreshed) self.shell.sig_show_status_requested.connect( lambda msg: self.sig_show_status_message.emit(msg, 0)) # --- PluginMainWidget API # ------------------------------------------------------------------------ def get_title(self): return _('Internal console') def setup(self): # TODO: Move this to the shell self.quit_action = self.create_action( ConsoleWidgetActions.Quit, text=_("&Quit"), tip=_("Quit"), icon=self.create_icon('exit'), triggered=self.sig_quit_requested, context=Qt.ApplicationShortcut, shortcut_context="_", register_shortcut=True, menurole=QAction.QuitRole ) run_action = self.create_action( ConsoleWidgetActions.Run, text=_("&Run..."), tip=_("Run a Python file"), icon=self.create_icon('run_small'), triggered=self.run_script, ) environ_action = self.create_action( ConsoleWidgetActions.Environment, text=_("Environment variables..."), tip=_("Show and edit environment variables (for current " "session)"), icon=self.create_icon('environ'), triggered=self.show_env, ) syspath_action = self.create_action( ConsoleWidgetActions.SysPath, text=_("Show sys.path contents..."), tip=_("Show (read-only) sys.path"), icon=self.create_icon('syspath'), triggered=self.show_syspath, ) buffer_action = self.create_action( ConsoleWidgetActions.MaxLineCount, text=_("Buffer..."), tip=_("Set maximum line count"), triggered=self.change_max_line_count, ) exteditor_action = self.create_action( ConsoleWidgetActions.ExternalEditor, text=_("External editor path..."), tip=_("Set external editor executable path"), triggered=self.change_exteditor, ) wrap_action = self.create_action( ConsoleWidgetActions.ToggleWrap, text=_("Wrap lines"), toggled=lambda val: self.set_conf('wrap', val), initial=self.get_conf('wrap'), ) codecompletion_action = self.create_action( ConsoleWidgetActions.ToggleCodeCompletion, text=_("Automatic code completion"), toggled=lambda val: self.set_conf('codecompletion/auto', val), initial=self.get_conf('codecompletion/auto'), ) # Submenu internal_settings_menu = self.create_menu( ConsoleWidgetMenus.InternalSettings, _('Internal console settings'), icon=self.create_icon('tooloptions'), ) for item in [buffer_action, wrap_action, codecompletion_action, exteditor_action]: self.add_item_to_menu( item, menu=internal_settings_menu, section=ConsoleWidgetInternalSettingsSubMenuSections.Main, ) # Options menu options_menu = self.get_options_menu() for item in [run_action, environ_action, syspath_action, internal_settings_menu]: self.add_item_to_menu( item, menu=options_menu, section=ConsoleWidgetOptionsMenuSections.Run, ) self.add_item_to_menu( self.quit_action, menu=options_menu, section=ConsoleWidgetOptionsMenuSections.Quit, ) self.shell.set_external_editor( self.get_conf('external_editor/path'), '') @on_conf_change(option='max_line_count') def max_line_count_update(self, value): self.shell.setMaximumBlockCount(value) @on_conf_change(option='wrap') def wrap_mode_update(self, value): self.shell.toggle_wrap_mode(value) @on_conf_change(option='external_editor/path') def external_editor_update(self, value): self.shell.set_external_editor(value, '') def update_actions(self): pass def get_focus_widget(self): return self.shell # --- Qt overrides # ------------------------------------------------------------------------ def dragEnterEvent(self, event): """ Reimplement Qt method. Inform Qt about the types of data that the widget accepts. """ source = event.mimeData() if source.hasUrls(): if mimedata2url(source): event.acceptProposedAction() else: event.ignore() elif source.hasText(): event.acceptProposedAction() def dropEvent(self, event): """ Reimplement Qt method. Unpack dropped data and handle it. """ source = event.mimeData() if source.hasUrls(): pathlist = mimedata2url(source) self.shell.drop_pathlist(pathlist) elif source.hasText(): lines = str(source.text()) self.shell.set_cursor_position('eof') self.shell.execute_lines(lines) event.acceptProposedAction() # --- Public API # ------------------------------------------------------------------------ def start_interpreter(self, namespace): """ Start internal console interpreter. """ self.shell.start_interpreter(namespace) def set_historylog(self, historylog): """ Bind historylog instance to this console. Not used anymore since v2.0. """ historylog.add_history(self.shell.history_filename) self.shell.sig_append_to_history_requested.connect( historylog.append_to_history) def set_help(self, help_plugin): """ Bind help instance to this console. """ self.shell.help = help_plugin def report_issue(self): """Report an issue with the SpyderErrorDialog.""" self._report_dlg = SpyderErrorDialog(self, is_report=True) self._report_dlg.set_color_scheme(self.get_conf( 'selected', section='appearance')) self._report_dlg.show() @Slot(dict) def handle_exception(self, error_data, sender=None): """ Exception occurred in the internal console. Show a QDialog or the internal console to warn the user. Handle any exception that occurs during Spyder usage. Parameters ---------- error_data: dict The dictionary containing error data. The expected keys are: >>> error_data= { "text": str, "is_traceback": bool, "repo": str, "title": str, "label": str, "steps": str, } sender: spyder.api.plugins.SpyderPluginV2, optional The sender plugin. Default is None. Notes ----- The `is_traceback` key indicates if `text` contains plain text or a Python error traceback. The `title` and `repo` keys indicate how the error data should customize the report dialog and Github error submission. The `label` and `steps` keys allow customizing the content of the error dialog. """ text = error_data.get("text", None) is_traceback = error_data.get("is_traceback", False) title = error_data.get("title", "") label = error_data.get("label", "") steps = error_data.get("steps", "") # Skip errors without traceback (and no text) or dismiss if ((not text and not is_traceback and self.error_dlg is None) or self.dismiss_error): return InstallerInternalError(title + text) # Retrieve internal plugins internal_plugins = PLUGIN_REGISTRY.internal_plugins # Get if sender is internal or not is_internal_plugin = True if sender is not None: sender_name = getattr( sender, 'NAME', getattr(sender, 'CONF_SECTION')) is_internal_plugin = sender_name in internal_plugins # Set repo repo = "spyder-ide/spyder" if not is_internal_plugin: repo = error_data.get("repo", None) if repo is None: raise SpyderAPIError( f"External plugin '{sender_name}' does not define 'repo' " "key in the 'error_data' dictionary in the form " "my-org/my-repo (only Github is supported)." ) if repo == 'spyder-ide/spyder': raise SpyderAPIError( f"External plugin '{sender_name}' 'repo' key needs to be " "different from the main Spyder repo." ) if self.get_conf('show_internal_errors', section='main'): if self.error_dlg is None: self.error_dlg = SpyderErrorDialog(self) self.error_dlg.set_color_scheme( self.get_conf('selected', section='appearance')) self.error_dlg.rejected.connect(self.remove_error_dlg) self.error_dlg.details.sig_go_to_error_requested.connect( self.go_to_error) # Set the report repository self.error_dlg.set_github_repo_org(repo) if title: self.error_dlg.set_title(title) self.error_dlg.title.setEnabled(False) if label: self.error_dlg.main_label.setText(label) self.error_dlg.submit_btn.setEnabled(True) if steps: self.error_dlg.steps_text.setText(steps) self.error_dlg.set_require_minimum_length(False) self.error_dlg.append_traceback(text) self.error_dlg.show() elif DEV or get_debug_level(): self.change_visibility(True, True) def close_error_dlg(self): """ Close error dialog. """ if self.error_dlg: self.error_dlg.reject() def remove_error_dlg(self): """ Remove error dialog. """ if self.error_dlg.dismiss_box.isChecked(): self.dismiss_error = True if PYSIDE2 or PYSIDE6: self.error_dlg.disconnect(None, None, None) else: self.error_dlg.disconnect() self.error_dlg = None @Slot() def show_env(self): """ Show environment variables. """ self.dialog_manager.show(EnvDialog(parent=self)) def get_sys_path(self): """ Return the `sys.path`. """ return sys.path @Slot() def show_syspath(self): """ Show `sys.path`. """ editor = CollectionsEditor(parent=self) editor.setup( sys.path, title="sys.path", readonly=True, icon=self.create_icon('syspath'), ) self.dialog_manager.show(editor) @Slot() def run_script(self, filename=None, silent=False, args=None): """ Run a Python script. """ if filename is None: self.shell.interpreter.restore_stds() filename, _selfilter = getopenfilename( self, _("Run Python file"), getcwd_or_home(), _("Python files") + " (*.py ; *.pyw ; *.ipy)", ) self.shell.interpreter.redirect_stds() if filename: os.chdir(osp.dirname(filename)) filename = osp.basename(filename) else: return logger.debug("Running script with %s", args) filename = osp.abspath(filename) rbs = remove_backslashes command = '%runfile {} --args {}'.format( repr(rbs(filename)), repr(rbs(args))) self.change_visibility(True, True) self.shell.write(command+'\n') self.shell.run_command(command) def go_to_error(self, text): """ Go to error if relevant. """ match = get_error_match(str(text)) if match: fname, lnb = match.groups() self.edit_script(fname, int(lnb)) def edit_script(self, filename=None, goto=-1): """ Edit script. """ if filename is not None: # Called from InternalShell self.shell.external_editor(filename, goto) self.sig_edit_goto_requested.emit(osp.abspath(filename), goto, '') def execute_lines(self, lines): """ Execute lines and give focus to shell. """ self.shell.execute_lines(str(lines)) self.shell.setFocus() @Slot() def change_max_line_count(self, value=None): """" Change maximum line count. """ valid = True if value is None: value, valid = QInputDialog.getInt( self, _('Buffer'), _('Maximum line count'), self.get_conf('max_line_count'), 0, 1000000, ) if valid: self.set_conf('max_line_count', value) @Slot() def change_exteditor(self, path=None): """ Change external editor path. """ valid = True if path is None: path, valid = QInputDialog.getText( self, _('External editor'), _('External editor executable path:'), QLineEdit.Normal, self.get_conf('external_editor/path'), ) if valid: self.set_conf('external_editor/path', str(path)) def set_exit_function(self, func): """ Set the callback function to execute when the `exit_interpreter` is called. """ self.shell.exitfunc = func def set_font(self, font): """ Set font of the internal shell. """ self.shell.set_font(font) def redirect_stds(self): """ Redirect stdout and stderr when using open file dialogs. """ self.shell.interpreter.redirect_stds() def restore_stds(self): """ Restore stdout and stderr when using open file dialogs. """ self.shell.interpreter.restore_stds() def set_namespace_item(self, name, item): """ Add an object to the namespace dictionary of the internal console. """ self.shell.interpreter.namespace[name] = item def exit_interpreter(self): """ Exit the internal console interpreter. This is equivalent to requesting the main application to quit. """ self.shell.exit_interpreter()
ConsoleWidget
python
huggingface__transformers
src/transformers/models/ibert/modeling_ibert.py
{ "start": 15074, "end": 16463 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.quant_mode = config.quant_mode self.act_bit = 8 self.weight_bit = 8 self.bias_bit = 32 self.dense = QuantLinear( config.hidden_size, config.intermediate_size, bias=True, weight_bit=self.weight_bit, bias_bit=self.bias_bit, quant_mode=self.quant_mode, per_channel=True, ) if config.hidden_act != "gelu": raise ValueError("I-BERT only supports 'gelu' for `config.hidden_act`") self.intermediate_act_fn = IntGELU(quant_mode=self.quant_mode, force_dequant=config.force_dequant) self.output_activation = QuantAct(self.act_bit, quant_mode=self.quant_mode) def forward(self, hidden_states, hidden_states_scaling_factor): hidden_states, hidden_states_scaling_factor = self.dense(hidden_states, hidden_states_scaling_factor) hidden_states, hidden_states_scaling_factor = self.intermediate_act_fn( hidden_states, hidden_states_scaling_factor ) # Requantization: 32bit -> 8-bit hidden_states, hidden_states_scaling_factor = self.output_activation( hidden_states, hidden_states_scaling_factor ) return hidden_states, hidden_states_scaling_factor
IBertIntermediate
python
getsentry__sentry
tests/sentry/uptime/endpoints/test_detector.py
{ "start": 2261, "end": 8859 }
class ____(UptimeDetectorBaseTest): endpoint = "sentry-api-0-organization-detector-details" def setUp(self) -> None: super().setUp() self.context = { "organization": self.project.organization, "project": self.project, "request": self.make_request(), } def test_update_non_superuser_cannot_change_mode_via_endpoint(self) -> None: """Integration test: non-superuser cannot change mode via API endpoint.""" # Create a detector with MANUAL mode specifically for this test manual_uptime_subscription = self.create_uptime_subscription( url="https://manual-test-site.com", interval_seconds=UptimeSubscription.IntervalSeconds.ONE_MINUTE, timeout_ms=30000, ) manual_detector = self.create_uptime_detector( project=self.project, env=self.environment, uptime_subscription=manual_uptime_subscription, name="Manual Test Detector", mode=UptimeMonitorMode.MANUAL, ) assert manual_detector.workflow_condition_group is not None invalid_data = { "id": manual_detector.id, "projectId": self.project.id, "name": "Manual Test Detector", "type": UptimeDomainCheckFailure.slug, "dateCreated": manual_detector.date_added, "dateUpdated": timezone.now(), "conditionGroup": { "id": manual_detector.workflow_condition_group.id, "organizationId": self.organization.id, }, "config": { "environment": self.environment.name, "mode": UptimeMonitorMode.AUTO_DETECTED_ACTIVE.value, "recovery_threshold": 1, "downtime_threshold": 1, }, } response = self.get_error_response( self.organization.slug, manual_detector.id, **invalid_data, status_code=status.HTTP_400_BAD_REQUEST, method="PUT", ) assert response.data["config"] == ["Only superusers can modify `mode`"] # Verify that mode was NOT changed manual_detector.refresh_from_db() assert manual_detector.config["mode"] == UptimeMonitorMode.MANUAL.value def test_update(self) -> None: assert self.detector.workflow_condition_group is not None valid_data = { "id": self.detector.id, "projectId": self.project.id, "name": "Test Uptime Detector", "type": UptimeDomainCheckFailure.slug, "dateCreated": self.detector.date_added, "dateUpdated": timezone.now(), "dataSources": [ { "timeout_ms": 15000, } ], "conditionGroup": { "id": self.detector.workflow_condition_group.id, "organizationId": self.organization.id, }, "config": self.detector.config, } self.get_success_response( self.organization.slug, self.detector.id, **valid_data, status_code=status.HTTP_200_OK, method="PUT", ) updated_sub: UptimeSubscription = UptimeSubscription.objects.get( id=self.uptime_subscription.id ) assert updated_sub.timeout_ms == 15000 def test_update_auto_detected_switches_to_manual(self) -> None: """Test that when a user modifies an AUTO_DETECTED detector, it automatically switches to MANUAL mode.""" # Create an AUTO_DETECTED detector auto_uptime_subscription = self.create_uptime_subscription( url="https://auto-detected-site.com", interval_seconds=UptimeSubscription.IntervalSeconds.ONE_MINUTE, timeout_ms=30000, ) auto_detector = self.create_uptime_detector( project=self.project, env=self.environment, uptime_subscription=auto_uptime_subscription, name="Auto Detected Monitor", mode=UptimeMonitorMode.AUTO_DETECTED_ACTIVE, ) assert auto_detector.workflow_condition_group is not None # User modifies the detector (e.g., changes name) # They pass the current config including the AUTO_DETECTED mode valid_data = { "id": auto_detector.id, "projectId": self.project.id, "name": "User Modified Monitor", "type": UptimeDomainCheckFailure.slug, "dateCreated": auto_detector.date_added, "dateUpdated": timezone.now(), "conditionGroup": { "id": auto_detector.workflow_condition_group.id, "organizationId": self.organization.id, }, "config": auto_detector.config, # Passing existing config with AUTO_DETECTED mode } self.get_success_response( self.organization.slug, auto_detector.id, **valid_data, status_code=status.HTTP_200_OK, method="PUT", ) # Verify that mode was automatically switched to MANUAL auto_detector.refresh_from_db() assert auto_detector.name == "User Modified Monitor" assert auto_detector.config["mode"] == UptimeMonitorMode.MANUAL.value def test_update_invalid(self) -> None: assert self.detector.workflow_condition_group is not None valid_data = { "id": self.detector.id, "projectId": self.project.id, "name": "Test Uptime Detector", "type": UptimeDomainCheckFailure.slug, "dateCreated": self.detector.date_added, "dateUpdated": timezone.now(), "dataSources": [ { "timeout_ms": 80000, } ], "conditionGroup": { "id": self.detector.workflow_condition_group.id, "organizationId": self.organization.id, }, "config": self.detector.config, } response = self.get_error_response( self.organization.slug, self.detector.id, **valid_data, status_code=status.HTTP_400_BAD_REQUEST, method="PUT", ) assert "dataSources" in response.data assert "Ensure this value is less than or equal to 60000." in str( response.data["dataSources"] )
OrganizationDetectorDetailsPutTest
python
PyCQA__pylint
tests/functional/a/assignment/assignment_from_no_return_2.py
{ "start": 1493, "end": 1780 }
class ____: """bla bla""" def abstract_method(self): """use to return something in concrete implementation""" raise NotImplementedError def use_abstract(self): """should not issue E1111""" var = self.abstract_method() print(var)
Abstract
python
kamyu104__LeetCode-Solutions
Python/minimum-number-of-operations-to-make-array-xor-equal-to-k.py
{ "start": 48, "end": 331 }
class ____(object): def minOperations(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ def popcount(x): return bin(x).count('1') return popcount(reduce(lambda x, y: x^y, nums, k))
Solution
python
kamyu104__LeetCode-Solutions
Python/maximize-the-number-of-target-nodes-after-connecting-trees-i.py
{ "start": 87, "end": 3588 }
class ____(object): def maxTargetNodes(self, edges1, edges2, k): """ :type edges1: List[List[int]] :type edges2: List[List[int]] :type k: int :rtype: List[int] """ def centroid_decomposition(adj, k): def dfs(u): # https://usaco.guide/plat/centroid def find_subtree_size(u, p): sizes[u] = 1 for v in adj[u]: if v == p or lookup[v]: continue sizes[u] += find_subtree_size(v, u) return sizes[u] def find_centroid(u, p): for v in adj[u]: if v == p or lookup[v]: continue if sizes[v]*2 > n: return find_centroid(v, u) return u def count(u, p, d): if d > k: return if d-1 == len(cnt): cnt.append(0) cnt[d-1] += 1 for v in adj[u]: if v == p or lookup[v]: continue count(v, u, d+1) def update(u, p, d): if d > k: return result[u] += total[min(k-d, len(total)-1)]-curr[min(k-d, len(curr)-1)] for v in adj[u]: if v == p or lookup[v]: continue update(v, u, d+1) find_subtree_size(u, -1) n = sizes[u] u = find_centroid(u, -1) lookup[u] = True max_d = 0 for v in adj[u]: if lookup[v]: continue cnt = [] count(v, u, 0+1) prefix[v].append(0) for d in xrange(len(cnt)): prefix[v].append(prefix[v][-1]+cnt[d]) max_d = max(max_d, len(cnt)) total = [1]*(max_d+1) for v in adj[u]: if lookup[v]: continue for d in xrange(len(total)): total[d] += prefix[v][min(d, len(prefix[v])-1)] result[u] += total[min(k, len(total)-1)] for v in adj[u]: if lookup[v]: continue curr, prefix[v] = prefix[v], [] update(v, u, 0+1) for v in adj[u]: if lookup[v]: continue dfs(v) result = [0]*len(adj) sizes = [0]*len(adj) lookup = [False]*len(adj) prefix = [[] for _ in xrange(len(adj))] if k >= 0: dfs(0) return result def find_adj(edges): adj = [[] for _ in xrange(len(edges)+1)] for u, v in edges: adj[u].append(v) adj[v].append(u) return adj adj2 = find_adj(edges2) mx = max(centroid_decomposition(adj2, k-1)) adj1 = find_adj(edges1) return [mx+x for x in centroid_decomposition(adj1, k)] # Time: O((n + m) * k) # Space: O((n + m) * k) # dfs, tree dp
Solution
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingIsinstance1.py
{ "start": 399, "end": 510 }
class ____(UnrelatedClass): def __init__(self) -> None: self.property2: None = None
UnrelatedSubclass
python
django-haystack__django-haystack
test_haystack/solr_tests/test_solr_management_commands.py
{ "start": 529, "end": 896 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr="author", faceted=True) pub_date = indexes.DateTimeField(model_attr="pub_date") def get_model(self): return MockModel def get_updated_field(self): return "pub_date"
SolrMockSearchIndex
python
huggingface__transformers
src/transformers/models/grounding_dino/modeling_grounding_dino.py
{ "start": 24510, "end": 25876 }
class ____(nn.Module): """ This is a more standard version of the position embedding, very similar to the one used by the Attention is all you need paper, generalized to work on images. """ def __init__(self, config): super().__init__() self.embedding_dim = config.d_model // 2 self.temperature = config.positional_embedding_temperature self.scale = 2 * math.pi def forward(self, pixel_values, pixel_mask): y_embed = pixel_mask.cumsum(1, dtype=torch.float32) x_embed = pixel_mask.cumsum(2, dtype=torch.float32) eps = 1e-6 y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale dim_t = torch.arange(self.embedding_dim, dtype=torch.float32, device=pixel_values.device) dim_t = self.temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / self.embedding_dim) pos_x = x_embed[:, :, :, None] / dim_t pos_y = y_embed[:, :, :, None] / dim_t pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3) pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3) pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) return pos
GroundingDinoSinePositionEmbedding
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/inputs.py
{ "start": 4364, "end": 4735 }
class ____(graphene.InputObjectType): graphName = graphene.NonNull(graphene.String) repositoryName = graphene.NonNull(graphene.String) repositoryLocationName = graphene.NonNull(graphene.String) class Meta: description = """This type represents the fields necessary to identify a graph""" name = "GraphSelector"
GrapheneGraphSelector
python
FactoryBoy__factory_boy
factory/django.py
{ "start": 8668, "end": 9369 }
class ____(FileField): DEFAULT_FILENAME = 'example.jpg' def _make_data(self, params): # ImageField (both django's and factory_boy's) require PIL. # Try to import it along one of its known installation paths. from PIL import Image width = params.get('width', 100) height = params.get('height', width) color = params.get('color', 'blue') image_format = params.get('format', 'JPEG') image_palette = params.get('palette', 'RGB') thumb_io = io.BytesIO() with Image.new(image_palette, (width, height), color) as thumb: thumb.save(thumb_io, format=image_format) return thumb_io.getvalue()
ImageField
python
donnemartin__interactive-coding-challenges
staging/graphs_trees/binary_tree/binary_search_tree.py
{ "start": 119, "end": 3231 }
class ____ (object): def __init__ (self): self.root = None def insert (self, newData): leaf = Node(newData) if self.root is None: self.root = leaf else: current = self.root parent = self.root while current is not None: parent = current if newData < current.data: current = current.leftChild else: current = current.rightChild if newData < parent.data: parent.leftChild = leaf else: parent.rightChild = leaf # returns false if the item to be deleted is not on the tree def delete (self, data): current = self.root parent = self.root isLeft = False if current is None: return False while current is not None and current.data is not data: parent = current if data < current.data: current = current.leftChild isLeft = True else: current = current.rightChild isLeft = False if current is None: return False if current.leftChild is None and current.rightChild is None: if current is self.root: self.root = None elif isLeft: parent.leftChild = None else: parent.rightChild = None elif current.rightChild is None: if current is self.root: self.root = current.leftChild elif isLeft: parent.leftChild = current.leftChild else: parent.rightChild = current.leftChild elif current.rightChild is None: if current is self.root: self.root = current.rightChild elif isLeft: parent.lChild = current.rightChild else: parent.rightChild = current.rightChild else: successor = current.rightChild successorParent = current while successor.leftChild is not None: successorParent = successor successor = successor.leftChild if current is self.root: self.root = successor elif isLeft: parent.leftChild = successor else: parent.rightChild = successor successor.leftChild = current.leftChild if successor is not current.rightChild: successorParent.leftChild = successor.rightChild successor.rightChild = current.rightChild return True def minNode (self): current = self.root while current.leftChild is not None: current = current.leftChild return current.data def maxNode (self): current = self.root while current.rightChild is not None: current = current.rightChild return current.data def printPostOrder (self): global postOrder postOrder = [] def PostOrder(node): if node is not None: PostOrder(node.leftChild) PostOrder(node.rightChild) postOrder.append(node.data) PostOrder(self.root) return postOrder def printInOrder (self): global inOrder inOrder = [] def InOrder (node): if node is not None: InOrder(node.leftChild) inOrder.append(node.data) InOrder(node.rightChild) InOrder(self.root) return inOrder def printPreOrder (self): global preOrder preOrder = [] def PreOrder (node): if node is not None: preOrder.append(node.data) PreOrder(node.leftChild) PreOrder(node.rightChild) PreOrder(self.root) return preOrder def treeIsEmpty (self): return self.root is None
BinaryTree
python
getsentry__sentry
tests/sentry/models/test_releasefile.py
{ "start": 2278, "end": 7157 }
class ____(TestCase): def create_archive(self, fields, files, dist=None): manifest = dict( fields, files={filename: {"url": f"fake://{filename}"} for filename in files} ) buffer = BytesIO() with ZipFile(buffer, mode="w") as zf: zf.writestr("manifest.json", json.dumps(manifest)) for filename, content in files.items(): zf.writestr(filename, content) buffer.seek(0) file_ = File.objects.create(name=str(hash(tuple(files.items())))) file_.putfile(buffer) file_.update(timestamp=datetime(2021, 6, 11, 9, 13, 1, 317902, tzinfo=timezone.utc)) return update_artifact_index(self.release, dist, file_) def test_multi_archive(self) -> None: assert read_artifact_index(self.release, None) is None # Delete does nothing assert delete_from_artifact_index(self.release, None, "foo") is False archive1 = self.create_archive( fields={}, files={ "foo": "foo", "bar": "bar", "baz": "bazaa", }, ) assert read_artifact_index(self.release, None) == { "files": { "fake://bar": { "archive_ident": archive1.ident, "date_created": "2021-06-11T09:13:01.317902Z", "filename": "bar", "sha1": "62cdb7020ff920e5aa642c3d4066950dd1f01f4d", "size": 3, }, "fake://baz": { "archive_ident": archive1.ident, "date_created": "2021-06-11T09:13:01.317902Z", "filename": "baz", "sha1": "1a74885aa2771a6a0edcc80dbd0cf396dfaf1aab", "size": 5, }, "fake://foo": { "archive_ident": archive1.ident, "date_created": "2021-06-11T09:13:01.317902Z", "filename": "foo", "sha1": "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33", "size": 3, }, }, } # See if creating a second manifest interferes: dist = Distribution.objects.create( organization_id=self.organization.id, release_id=self.release.id, name="foo" ) self.create_archive(fields={}, files={"xyz": "123"}, dist=dist) archive2 = self.create_archive( fields={}, files={ "foo": "foo", "bar": "BAR", "zap": "zapz", }, ) # Two files were overwritten, one was added expected = { "files": { "fake://bar": { "archive_ident": archive2.ident, "date_created": "2021-06-11T09:13:01.317902Z", "filename": "bar", "sha1": "a5d5c1bba91fdb6c669e1ae0413820885bbfc455", "size": 3, }, "fake://baz": { "archive_ident": archive1.ident, "date_created": "2021-06-11T09:13:01.317902Z", "filename": "baz", "sha1": "1a74885aa2771a6a0edcc80dbd0cf396dfaf1aab", "size": 5, }, "fake://foo": { "archive_ident": archive2.ident, "date_created": "2021-06-11T09:13:01.317902Z", "filename": "foo", "sha1": "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33", "size": 3, }, "fake://zap": { "archive_ident": archive2.ident, "date_created": "2021-06-11T09:13:01.317902Z", "filename": "zap", "sha1": "a7a9c12205f9cb1f53f8b6678265c9e8158f2a8f", "size": 4, }, }, } assert read_artifact_index(self.release, None) == expected # Deletion works: assert delete_from_artifact_index(self.release, None, "fake://foo") is True expected["files"].pop("fake://foo") assert read_artifact_index(self.release, None) == expected def test_same_sha(self) -> None: """Stand-alone release file has same sha1 as one in manifest""" self.create_archive(fields={}, files={"foo": "bar"}) file_ = File.objects.create() file_.putfile(BytesIO(b"bar")) self.create_release_file(file=file_) index = read_artifact_index(self.release, None) assert index is not None assert file_.checksum == index["files"]["fake://foo"]["sha1"] @pytest.mark.skip(reason="Causes 'There is 1 other session using the database.'")
ReleaseArchiveTestCase
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol11.py
{ "start": 466, "end": 683 }
class ____(SourceProvider[_TBase2]): def get(self) -> Optional[_TBase2]: source = my_next(self) return source def __next__(self) -> _TBase2: raise NotImplementedError
ManagedSourceProvider
python
streamlit__streamlit
lib/streamlit/components/v2/component_file_watcher.py
{ "start": 2417, "end": 14653 }
class ____: """Handle file watching for component asset directories. Parameters ---------- component_update_callback : Callable[[list[str]], None] Callback invoked when files change under any watched directory. It receives a list of component names affected by the change. """ def __init__(self, component_update_callback: Callable[[list[str]], None]) -> None: """Initialize the file watcher. Parameters ---------- component_update_callback : Callable[[list[str]], None] Callback function to call when components under watched roots change. Signature: (affected_component_names) """ self._component_update_callback = component_update_callback self._lock = threading.Lock() # File watching state self._watched_directories: dict[ str, list[str] ] = {} # directory -> component_names self._path_watchers: list[_HasClose] = [] # Store actual watcher instances self._watching_active = False # Store asset roots to watch: component_name -> asset_root self._asset_watch_roots: dict[str, Path] = {} # Default noisy directories to ignore in callbacks self._ignored_dirs: tuple[str, ...] = ( "__pycache__", ".cache", ".git", ".hg", ".mypy_cache", ".pytest_cache", ".ruff_cache", ".svn", ".swc", ".yarn", "coverage", "node_modules", "venv", ) @property def is_watching_active(self) -> bool: """Check if file watching is currently active. Returns ------- bool True if file watching is active, False otherwise """ return self._watching_active def start_file_watching(self, asset_watch_roots: dict[str, Path]) -> None: """Start file watching for asset roots. Parameters ---------- asset_watch_roots : dict[str, Path] Mapping of component names to asset root directories to watch. Notes ----- The method is idempotent: it stops any active watchers first, then re-initializes watchers for the provided ``asset_watch_roots``. """ # Always stop first to ensure a clean state, then start with the new roots. # This sequencing avoids races between concurrent stop/start calls. self.stop_file_watching() self._start_file_watching(asset_watch_roots) def stop_file_watching(self) -> None: """Stop file watching and clean up watchers. Notes ----- This method is safe to call multiple times and will no-op if watching is not active. """ with self._lock: if not self._watching_active: return # Close all path watchers for watcher in self._path_watchers: try: watcher.close() except Exception: # noqa: PERF203 _LOGGER.exception("Failed to close path watcher") self._path_watchers.clear() self._watched_directories.clear() # Also clear asset root references to avoid stale state retention self._asset_watch_roots.clear() self._watching_active = False _LOGGER.debug("Stopped file watching for component registry") def _start_file_watching(self, asset_watch_roots: dict[str, Path]) -> None: """Internal method to start file watching with the given roots. This method is exception-safe: in case of failures while creating watchers, any previously created watcher instances are closed and no internal state is committed. """ with self._lock: if self._watching_active: return if not asset_watch_roots: _LOGGER.debug("No asset roots to watch") return try: path_watcher_class = self._get_default_path_watcher_class() if path_watcher_class is None: # NoOp watcher; skip activation return directories_to_watch = self._prepare_directories_to_watch( asset_watch_roots ) new_watchers, new_watched_dirs = self._build_watchers_for_directories( path_watcher_class, directories_to_watch ) # Commit new watchers and state only after successful creation if new_watchers: self._commit_watch_state( new_watchers, new_watched_dirs, asset_watch_roots ) else: _LOGGER.debug("No directories were watched; staying inactive") except Exception: _LOGGER.exception("Failed to start file watching") def _get_default_path_watcher_class(self) -> type | None: """Return the default path watcher class. Returns ------- type | None The concrete path watcher class to instantiate, or ``None`` if the NoOp watcher is configured and file watching should be skipped. """ from streamlit.watcher.path_watcher import ( NoOpPathWatcher, get_default_path_watcher_class, ) path_watcher_class = get_default_path_watcher_class() if path_watcher_class is NoOpPathWatcher: _LOGGER.debug("NoOpPathWatcher in use; skipping component file watching") return None return path_watcher_class def _prepare_directories_to_watch( self, asset_watch_roots: dict[str, Path] ) -> dict[str, list[str]]: """Build a mapping of directory to component names. Parameters ---------- asset_watch_roots : dict[str, Path] Mapping of component names to their asset root directories. Returns ------- dict[str, list[str]] A map from absolute directory path to a deduplicated list of component names contained in that directory. """ directories_to_watch: dict[str, list[str]] = {} for comp_name, root in asset_watch_roots.items(): directory = str(root.resolve()) if directory not in directories_to_watch: directories_to_watch[directory] = [] if comp_name not in directories_to_watch[directory]: directories_to_watch[directory].append(comp_name) return directories_to_watch def _build_watchers_for_directories( self, path_watcher_class: type, directories_to_watch: dict[str, list[str]] ) -> tuple[list[_HasClose], dict[str, list[str]]]: """Create watchers for directories with rollback on failure. Parameters ---------- path_watcher_class : type The path watcher class to instantiate for each directory. directories_to_watch : dict[str, list[str]] A map of directory to the associated component name list. Returns ------- tuple[list[_HasClose], dict[str, list[str]]] The list of created watcher instances and the watched directory mapping. Raises ------ Exception Propagates any exception during watcher creation after closing already-created watchers. """ new_watchers: list[_HasClose] = [] new_watched_dirs: dict[str, list[str]] = {} for directory, component_names in directories_to_watch.items(): try: cb = self._make_directory_callback(tuple(component_names)) # Use a glob pattern that matches all files to let Streamlit's # watcher handle MD5 calculation and change detection watcher = path_watcher_class( directory, cb, glob_pattern="**/*", allow_nonexistent=False, ) new_watchers.append(cast("_HasClose", watcher)) new_watched_dirs[directory] = component_names _LOGGER.debug( "Prepared watcher for directory %s (components: %s)", directory, component_names, ) except Exception: # noqa: PERF203 # Roll back watchers created so far self._rollback_watchers(new_watchers) raise return new_watchers, new_watched_dirs def _commit_watch_state( self, new_watchers: list[_HasClose], new_watched_dirs: dict[str, list[str]], asset_watch_roots: dict[str, Path], ) -> None: """Commit created watchers and mark watching active. Parameters ---------- new_watchers : list[_HasClose] Fully initialized watcher instances. new_watched_dirs : dict[str, list[str]] Mapping from directory to component names. asset_watch_roots : dict[str, Path] The asset roots used to initialize watchers; stored for reference. """ self._path_watchers = new_watchers self._watched_directories = new_watched_dirs self._asset_watch_roots = dict(asset_watch_roots) self._watching_active = True _LOGGER.debug( "Started file watching for %d directories", len(self._watched_directories) ) def _rollback_watchers(self, watchers: list[_HasClose]) -> None: """Close any created watchers when setup fails. Parameters ---------- watchers : list[_HasClose] Watcher instances that were successfully created before a failure. """ for w in watchers: try: w.close() except Exception: # noqa: PERF203 _LOGGER.exception("Failed to close path watcher during rollback") def _make_directory_callback(self, comps: tuple[str, ...]) -> Callable[[str], None]: """Create a callback for a directory watcher that captures component names.""" def callback(changed_path: str) -> None: if self._is_in_ignored_directory(changed_path): _LOGGER.debug("Ignoring change in noisy directory: %s", changed_path) return _LOGGER.debug( "Directory change detected: %s, checking components: %s", changed_path, comps, ) self._handle_component_change(list(comps)) return callback def _handle_component_change(self, affected_components: list[str]) -> None: """Handle component changes for both directory and file events. Parameters ---------- affected_components : list[str] List of component names affected by the change """ if not self._watching_active: return # Notify manager to handle re-resolution based on recorded API inputs try: self._component_update_callback(affected_components) except Exception: # Never allow exceptions from user callbacks to break watcher loops _LOGGER.exception("Component update callback raised") def _is_in_ignored_directory(self, changed_path: str) -> bool: """Return True if the changed path is inside an ignored directory. Parameters ---------- changed_path : str The filesystem path that triggered the change event. Returns ------- bool True if the path is located inside one of the ignored directories, False otherwise. """ try: from pathlib import Path as _Path parts = set(_Path(changed_path).resolve().parts) return any(ignored in parts for ignored in self._ignored_dirs) except Exception: return False
ComponentFileWatcher
python
PrefectHQ__prefect
src/prefect/client/schemas/objects.py
{ "start": 44230, "end": 44588 }
class ____(ObjectBaseModel): """An ORM representation of saved search data. Represents a set of filter criteria.""" name: str = Field(default=..., description="The name of the saved search.") filters: list[SavedSearchFilter] = Field( default_factory=lambda: [], description="The filter set for the saved search.", )
SavedSearch
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1007893, "end": 1008073 }
class ____(RangeScheme): """RangeRaw schema wrapper.""" _schema = {"$ref": "#/definitions/RangeRaw"} def __init__(self, *args): super().__init__(*args)
RangeRaw
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 40876, "end": 41364 }
class ____(sgqlc.types.Enum): """Properties by which milestone connections can be ordered. Enumeration Choices: * `CREATED_AT`: Order milestones by when they were created. * `DUE_DATE`: Order milestones by when they are due. * `NUMBER`: Order milestones by their number. * `UPDATED_AT`: Order milestones by when they were last updated. """ __schema__ = github_schema __choices__ = ("CREATED_AT", "DUE_DATE", "NUMBER", "UPDATED_AT")
MilestoneOrderField
python
Lightning-AI__lightning
tests/tests_pytorch/trainer/connectors/test_callback_connector.py
{ "start": 12650, "end": 13235 }
class ____(Callback): @property def state_key(self): return "unique_key_2" def state_dict(self): return {"state": 2} @pytest.mark.parametrize( ("callbacks"), [ [Callback(), Callback()], [StatefulCallback()], [StatefulCallback1(), StatefulCallback2()], ], ) def test_validate_callbacks_list_function(callbacks: list): """Test the _validate_callbacks_list function directly with various scenarios.""" _validate_callbacks_list(callbacks) # Test with multiple stateful callbacks with same state key
StatefulCallback2
python
getsentry__sentry
src/sentry/replays/usecases/query/conditions/tags.py
{ "start": 2642, "end": 5234 }
class ____(GenericBase): @staticmethod def visit_eq(expression: Expression, value: str) -> Condition: return contains(TagAggregate.visit_eq(expression, value)) @staticmethod def visit_neq(expression: Expression, value: str) -> Condition: return does_not_contain(TagAggregate.visit_eq(expression, value)) @staticmethod def visit_match(expression: Expression, value: str) -> Condition: return contains(TagAggregate.visit_match(expression, value)) @staticmethod def visit_not_match(expression: Expression, value: str) -> Condition: return does_not_contain(TagAggregate.visit_match(expression, value)) @staticmethod def visit_in(expression: Expression, value: list[str]) -> Condition: return contains(TagAggregate.visit_in(expression, value)) @staticmethod def visit_not_in(expression: Expression, value: list[str]) -> Condition: return does_not_contain(TagAggregate.visit_in(expression, value)) def _match_key_value_exact(key: str, value: str) -> Function: return Function("has", parameters=[_get_tag_values(key), value]) def _match_key_values_exact(key: str, values: list[str]) -> Function: return Function("hasAny", parameters=[_get_tag_values(key), values]) def _match_key_value_wildcard(key: str, value: str) -> Function: return Function( "arrayExists", parameters=[ Lambda(["tag_value"], _search(value, Identifier("tag_value"))), _get_tag_values(key), ], ) def _get_tag_values(key: str) -> Function: return Function( "arrayFilter", parameters=[ Lambda(["key", "mask"], Function("equals", parameters=[Identifier("mask"), 1])), Column("tags.value"), _bitmask_on_tag_key(key), ], ) def _bitmask_on_tag_key(key: str) -> Function: """Create a bit mask. Returns an array where the integer 1 represents a match. e.g.: [0, 0, 1, 0, 1, 0] """ return Function( "arrayMap", parameters=[ Lambda(["i", "key"], Function("equals", parameters=[Identifier("key"), key])), Function("arrayEnumerate", parameters=[Column("tags.key")]), Column("tags.key"), ], ) def _search(value: str, identifier: Identifier) -> Function: # XXX: We don't want the '^$' values at the beginning and end of # the regex since we want to find the pattern anywhere in the # message. Strip off here return Function("match", parameters=[identifier, f"(?i){value[1:-1]}"])
SumOfTagAggregate
python
pytorch__pytorch
test/dynamo/test_fake_distributed.py
{ "start": 3619, "end": 5004 }
class ____(torch.nn.Module): def forward(self, primals_1: "Sym(u0)", primals_2: "Sym(u1)", primals_3: "Sym(u2)", primals_4: "f32[u0, u1, u2]"): ge_1: "Sym(u0 >= 0)" = primals_1 >= 0 _assert_scalar = torch.ops.aten._assert_scalar.default(ge_1, "Runtime assertion failed for expression u0 >= 0 on node 'ge'"); ge_1 = _assert_scalar = None ge_3: "Sym(u1 >= 0)" = primals_2 >= 0 _assert_scalar_1 = torch.ops.aten._assert_scalar.default(ge_3, "Runtime assertion failed for expression u1 >= 0 on node 'ge_1'"); ge_3 = _assert_scalar_1 = None ge_5: "Sym(u2 >= 0)" = primals_3 >= 0 _assert_scalar_2 = torch.ops.aten._assert_scalar.default(ge_5, "Runtime assertion failed for expression u2 >= 0 on node 'ge_2'"); ge_5 = _assert_scalar_2 = None floordiv: "Sym((u0//2))" = primals_1 // 2 all_to_all_single: "f32[2*((u0//2)), u1, u2]" = torch.ops._c10d_functional.all_to_all_single.default(primals_4, [floordiv, floordiv], [floordiv, floordiv], '0'); primals_4 = None wait_tensor: "f32[2*((u0//2)), u1, u2]" = torch.ops._c10d_functional.wait_tensor.default(all_to_all_single); all_to_all_single = None return (wait_tensor, primals_1, primals_2, primals_3, floordiv) """, # noqa: B950 ) self.assertExpectedInline( normalize_graph(backend.bw_graphs[0]), """\
GraphModule
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql_tests/graphql/test_runs.py
{ "start": 7486, "end": 37004 }
class ____(ExecutingGraphQLContextTestMatrix): def test_get_runs_over_graphql(self, graphql_context: WorkspaceRequestContext): # This include needs to be here because its inclusion screws up # other code in this file which reads itself to load a repo from dagster_graphql_tests.graphql.utils import sync_execute_get_run_log_data selector = infer_job_selector(graphql_context, "required_resource_job") payload_one = sync_execute_get_run_log_data( context=graphql_context, variables={ "executionParams": { "selector": selector, "mode": "default", "runConfigData": {"resources": {"R1": {"config": 2}}}, "executionMetadata": {"tags": [{"key": "fruit", "value": "apple"}]}, } }, ) run_id_one = payload_one["run"]["runId"] read_context = graphql_context result = execute_dagster_graphql(read_context, RUNS_QUERY, variables={"selector": selector}) runs = result.data["pipelineOrError"]["runs"] assert len(runs) == 1 tags = runs[0]["tags"] tags_by_key = {tag["key"]: tag["value"] for tag in tags} assert tags_by_key["fruit"] == "apple" origin = runs[0]["repositoryOrigin"] assert origin assert origin["repositoryLocationName"] == selector["repositoryLocationName"] assert origin["repositoryName"] == selector["repositoryName"] payload_two = sync_execute_get_run_log_data( context=graphql_context, variables={ "executionParams": { "selector": selector, "mode": "default", "runConfigData": {"resources": {"R1": {"config": 3}}}, "executionMetadata": {"tags": [{"key": "veggie", "value": "carrot"}]}, } }, ) run_id_two = payload_two["run"]["runId"] result = execute_dagster_graphql(read_context, RUNS_QUERY, variables={"selector": selector}) runs = result.data["pipelineOrError"]["runs"] assert len(runs) == 2 all_tag_keys_result = execute_dagster_graphql(read_context, ALL_TAG_KEYS_QUERY) tag_keys = set(all_tag_keys_result.data["runTagKeysOrError"]["keys"]) # check presence rather than set equality since we might have extra tags in cloud assert "fruit" in tag_keys assert "veggie" in tag_keys filtered_tags_result = execute_dagster_graphql( read_context, FILTERED_TAGS_QUERY, variables={"tagKeys": ["fruit"]} ) tags = filtered_tags_result.data["runTagsOrError"]["tags"] tags_dict = {item["key"]: item["values"] for item in tags} assert len(tags_dict) == 1 assert tags_dict["fruit"] == ["apple"] run_logs_result = execute_dagster_graphql( read_context, RUN_LOGS_QUERY, variables={"runId": run_id_one, "limit": 5} ) run_log_events = run_logs_result.data["pipelineRunOrError"]["eventConnection"]["events"] assert len(run_log_events) == 5 assert run_logs_result.data["pipelineRunOrError"]["eventConnection"]["hasMore"] cursor = run_logs_result.data["pipelineRunOrError"]["eventConnection"]["cursor"] assert cursor run_logs_result = execute_dagster_graphql( read_context, RUN_LOGS_QUERY, variables={"runId": run_id_one, "limit": 1000, "afterCursor": cursor}, ) assert not run_logs_result.data["pipelineRunOrError"]["eventConnection"]["hasMore"] with pytest.raises(Exception, match="Limit of 5000 is too large. Max is 1000"): run_logs_result = execute_dagster_graphql( read_context, RUN_LOGS_QUERY, variables={"runId": run_id_one, "limit": 5000, "afterCursor": cursor}, ) with mock.patch.object( type(read_context), "records_for_run_default_limit", new_callable=mock.PropertyMock, ) as mock_records_for_run_default_limit: mock_records_for_run_default_limit.return_value = 5 run_logs_result = execute_dagster_graphql( read_context, RUN_LOGS_QUERY, variables={"runId": run_id_one, "afterCursor": cursor}, ) assert len(run_logs_result.data["pipelineRunOrError"]["eventConnection"]["events"]) == 5 with pytest.raises(Exception, match="Limit of 1000 is too large. Max is 5"): run_logs_result = execute_dagster_graphql( read_context, RUN_LOGS_QUERY, variables={"runId": run_id_one, "limit": 1000, "afterCursor": cursor}, ) run_logs_result = execute_dagster_graphql( read_context, RUN_LOGS_QUERY, variables={"runId": run_id_one, "limit": 4, "afterCursor": cursor}, ) assert len(run_logs_result.data["pipelineRunOrError"]["eventConnection"]["events"]) == 4 # delete the second run result = execute_dagster_graphql( read_context, DELETE_RUN_MUTATION, variables={"runId": run_id_two} ) assert result.data["deletePipelineRun"]["__typename"] == "DeletePipelineRunSuccess" assert result.data["deletePipelineRun"]["runId"] == run_id_two # query it back out result = execute_dagster_graphql(read_context, RUNS_QUERY, variables={"selector": selector}) # first is the same run_one_data = _get_runs_data(result, run_id_one) assert run_one_data # second is gone run_two_data = _get_runs_data(result, run_id_two) assert run_two_data is None # try to delete the second run again execute_dagster_graphql(read_context, DELETE_RUN_MUTATION, variables={"runId": run_id_two}) result = execute_dagster_graphql( read_context, DELETE_RUN_MUTATION, variables={"runId": run_id_two} ) assert result.data["deletePipelineRun"]["__typename"] == "RunNotFoundError" def test_run_config(self, graphql_context: WorkspaceRequestContext): # This include needs to be here because its inclusion screws up # other code in this file which reads itself to load a repo from dagster_graphql_tests.graphql.utils import sync_execute_get_run_log_data selector = infer_job_selector(graphql_context, "required_resource_job") sync_execute_get_run_log_data( context=graphql_context, variables={ "executionParams": { "selector": selector, "mode": "default", "runConfigData": {"resources": {"R1": {"config": 2}}}, } }, ) result = execute_dagster_graphql( graphql_context, RUNS_QUERY, variables={"selector": selector} ) runs = result.data["pipelineOrError"]["runs"] assert len(runs) == 1 run = runs[0] assert run["runConfig"] == {"resources": {"R1": {"config": 2}}} assert run["runConfigYaml"] == yaml.safe_dump( run["runConfig"], default_flow_style=False, allow_unicode=True ) def get_repo_at_time_1(): @op def op_A(): pass @op def op_B(): pass @job def evolving_job(): op_A() op_B() @job def foo_job(): op_A() @repository def evolving_repo(): return [evolving_job, foo_job] return evolving_repo def get_repo_at_time_2(): @op def op_A(): pass @op def op_B_prime(): pass @job def evolving_job(): op_A() op_B_prime() @job def bar_job(): op_A() @repository def evolving_repo(): return [evolving_job, bar_job] return evolving_repo def get_asset_repo(): @op(tags={"dagster/concurrency_key": "foo"}) def foo(): yield AssetMaterialization(asset_key="foo", description="foo") yield AssetObservation(asset_key="bar", description="bar") yield Output(None) @job def foo_job(): foo() @asset def my_fail_asset(): raise Exception("OOPS") my_fail_asset_job = define_asset_job(name="my_fail_asset_job", selection="my_fail_asset") @repository def asset_repo(): return [foo_job, my_fail_asset, my_fail_asset_job] return asset_repo def test_runs_over_time(): with instance_for_test() as instance: repo_1 = get_repo_at_time_1() full_evolve_run_id = ( repo_1.get_job("evolving_job").execute_in_process(instance=instance).run_id ) foo_run_id = repo_1.get_job("foo_job").execute_in_process(instance=instance).run_id evolve_a_run_id = ( repo_1.get_job("evolving_job") .get_subset(op_selection={"op_A"}) .execute_in_process( instance=instance, ) .run_id ) evolve_b_run_id = ( repo_1.get_job("evolving_job") .get_subset(op_selection={"op_B"}) .execute_in_process( instance=instance, ) .run_id ) with define_out_of_process_context( __file__, "get_repo_at_time_1", instance ) as context_at_time_1: result = execute_dagster_graphql(context_at_time_1, ALL_RUNS_QUERY) assert result.data t1_runs = {run["runId"]: run for run in result.data["pipelineRunsOrError"]["results"]} assert t1_runs[full_evolve_run_id]["pipeline"] == { "__typename": "PipelineSnapshot", "name": "evolving_job", "solidSelection": None, } assert t1_runs[foo_run_id]["pipeline"] == { "__typename": "PipelineSnapshot", "name": "foo_job", "solidSelection": None, } assert t1_runs[evolve_a_run_id]["pipeline"] == { "__typename": "PipelineSnapshot", "name": "evolving_job", "solidSelection": None, } assert t1_runs[evolve_b_run_id]["pipeline"] == { "__typename": "PipelineSnapshot", "name": "evolving_job", "solidSelection": None, } with define_out_of_process_context( __file__, "get_repo_at_time_2", instance ) as context_at_time_2: result = execute_dagster_graphql(context_at_time_2, ALL_RUNS_QUERY) assert result.data t2_runs = {run["runId"]: run for run in result.data["pipelineRunsOrError"]["results"]} assert t2_runs[full_evolve_run_id]["pipeline"] == { "__typename": "PipelineSnapshot", "name": "evolving_job", "solidSelection": None, } assert t2_runs[evolve_a_run_id]["pipeline"] == { "__typename": "PipelineSnapshot", "name": "evolving_job", "solidSelection": None, } # pipeline name changed assert t2_runs[foo_run_id]["pipeline"] == { "__typename": "PipelineSnapshot", "name": "foo_job", "solidSelection": None, } # subset no longer valid - b renamed assert t2_runs[evolve_b_run_id]["pipeline"] == { "__typename": "PipelineSnapshot", "name": "evolving_job", "solidSelection": None, } def test_filtered_runs(): with instance_for_test() as instance: repo = get_repo_at_time_1() run_id_1 = ( repo.get_job("foo_job") .execute_in_process(instance=instance, tags={"run": "one"}) .run_id ) run_id_2 = ( repo.get_job("foo_job") .execute_in_process(instance=instance, tags={"run": "two"}) .run_id ) with define_out_of_process_context(__file__, "get_repo_at_time_1", instance) as context: result = execute_dagster_graphql( context, FILTERED_RUN_QUERY, variables={"filter": {"runIds": [run_id_1]}}, ) assert result.data run_ids = [run["runId"] for run in result.data["pipelineRunsOrError"]["results"]] assert len(run_ids) == 1 assert run_ids[0] == run_id_1 run_response = result.data["pipelineRunsOrError"]["results"][0] assert run_response["hasReExecutePermission"] is True assert run_response["hasTerminatePermission"] is True assert run_response["hasDeletePermission"] is True result = execute_dagster_graphql( context, FILTERED_RUN_QUERY, variables={"filter": {"tags": [{"key": "run", "value": "one"}]}}, ) assert result.data run_ids = [run["runId"] for run in result.data["pipelineRunsOrError"]["results"]] assert len(run_ids) == 1 assert run_ids[0] == run_id_1 # test multiple run ids result = execute_dagster_graphql( context, FILTERED_RUN_QUERY, variables={"filter": {"runIds": [run_id_1, run_id_2]}}, ) assert result.data run_ids = [run["runId"] for run in result.data["pipelineRunsOrError"]["results"]] assert len(run_ids) == 2 assert set(run_ids) == set([run_id_1, run_id_2]) def test_filtered_runs_status(): with instance_for_test() as instance: repo = get_repo_at_time_1() _ = instance.create_run_for_job( repo.get_job("foo_job"), status=DagsterRunStatus.STARTED ).run_id run_id_2 = instance.create_run_for_job( repo.get_job("foo_job"), status=DagsterRunStatus.FAILURE ).run_id with define_out_of_process_context(__file__, "get_repo_at_time_1", instance) as context: result = execute_dagster_graphql( context, FILTERED_RUN_QUERY, variables={"filter": {"statuses": ["FAILURE"]}}, ) assert result.data run_ids = [run["runId"] for run in result.data["pipelineRunsOrError"]["results"]] assert len(run_ids) == 1 assert run_ids[0] == run_id_2 def test_filtered_runs_multiple_statuses(): with instance_for_test() as instance: repo = get_repo_at_time_1() _ = instance.create_run_for_job( repo.get_job("foo_job"), status=DagsterRunStatus.STARTED ).run_id run_id_2 = instance.create_run_for_job( repo.get_job("foo_job"), status=DagsterRunStatus.FAILURE ).run_id run_id_3 = instance.create_run_for_job( repo.get_job("foo_job"), status=DagsterRunStatus.SUCCESS ).run_id with define_out_of_process_context(__file__, "get_repo_at_time_1", instance) as context: result = execute_dagster_graphql( context, FILTERED_RUN_QUERY, variables={"filter": {"statuses": ["FAILURE", "SUCCESS"]}}, ) assert result.data run_ids = [run["runId"] for run in result.data["pipelineRunsOrError"]["results"]] assert len(run_ids) == 2 assert run_id_2 in run_ids assert run_id_3 in run_ids def test_filtered_runs_multiple_filters(): with instance_for_test() as instance: repo = get_repo_at_time_1() started_run_with_tags = instance.create_run_for_job( repo.get_job("foo_job"), status=DagsterRunStatus.STARTED, tags={"foo": "bar"}, ) failed_run_with_tags = instance.create_run_for_job( repo.get_job("foo_job"), status=DagsterRunStatus.FAILURE, tags={"foo": "bar"}, ) started_run_without_tags = instance.create_run_for_job( repo.get_job("foo_job"), status=DagsterRunStatus.STARTED, tags={"baz": "boom"}, ) with define_out_of_process_context(__file__, "get_repo_at_time_1", instance) as context: result = execute_dagster_graphql( context, FILTERED_RUN_QUERY, variables={ "filter": { "statuses": ["STARTED"], "tags": [{"key": "foo", "value": "bar"}], } }, ) assert result.data run_ids = [run["runId"] for run in result.data["pipelineRunsOrError"]["results"]] assert len(run_ids) == 1 assert started_run_with_tags.run_id in run_ids assert failed_run_with_tags.run_id not in run_ids assert started_run_without_tags.run_id not in run_ids def test_filtered_runs_count(): with instance_for_test() as instance: repo = get_repo_at_time_1() instance.create_run_for_job( # noqa: B018 repo.get_job("foo_job"), status=DagsterRunStatus.STARTED ).run_id instance.create_run_for_job( # noqa: B018 repo.get_job("foo_job"), status=DagsterRunStatus.FAILURE ).run_id with define_out_of_process_context(__file__, "get_repo_at_time_1", instance) as context: result = execute_dagster_graphql( context, FILTERED_RUN_COUNT_QUERY, variables={"filter": {"statuses": ["FAILURE"]}}, ) assert result.data count = result.data["pipelineRunsOrError"]["count"] assert count == 1 def test_run_ids(): with instance_for_test() as instance: repo = get_repo_at_time_1() run_id_1 = instance.create_run_for_job( repo.get_job("foo_job"), status=DagsterRunStatus.STARTED ).run_id run_id_2 = instance.create_run_for_job( repo.get_job("foo_job"), status=DagsterRunStatus.FAILURE ).run_id run_id_3 = instance.create_run_for_job( repo.get_job("foo_job"), status=DagsterRunStatus.FAILURE ).run_id with define_out_of_process_context(__file__, "get_repo_at_time_1", instance) as context: result = execute_dagster_graphql( context, RUN_IDS_QUERY, variables={"filter": {"statuses": ["FAILURE"]}}, ) assert result.data assert result.data["runIdsOrError"]["results"] == [run_id_3, run_id_2] result = execute_dagster_graphql( context, RUN_IDS_QUERY, variables={"filter": {"statuses": ["FAILURE"]}, "limit": 1}, ) assert result.data assert result.data["runIdsOrError"]["results"] == [run_id_3] result = execute_dagster_graphql( context, RUN_IDS_QUERY, variables={"cursor": run_id_2}, ) assert result.data assert result.data["runIdsOrError"]["results"] == [run_id_1] def test_run_group(): with instance_for_test() as instance: repo = get_repo_at_time_1() foo_job = repo.get_job("foo_job") runs = [foo_job.execute_in_process(instance=instance)] root_run_id = runs[-1].run_id for _ in range(3): # https://github.com/dagster-io/dagster/issues/2433 run = instance.create_run_for_job( foo_job, parent_run_id=root_run_id, root_run_id=root_run_id, tags={PARENT_RUN_ID_TAG: root_run_id, ROOT_RUN_ID_TAG: root_run_id}, ) execute_run(InMemoryJob(foo_job), run, instance) runs.append(run) # pyright: ignore[reportArgumentType] with define_out_of_process_context( __file__, "get_repo_at_time_1", instance ) as context_at_time_1: result_one = execute_dagster_graphql( context_at_time_1, RUN_GROUP_QUERY, variables={"runId": root_run_id}, ) assert result_one.data["runGroupOrError"]["__typename"] == "RunGroup" assert len(result_one.data["runGroupOrError"]["runs"]) == 4 result_two = execute_dagster_graphql( context_at_time_1, RUN_GROUP_QUERY, variables={"runId": runs[-1].run_id}, ) assert result_one.data["runGroupOrError"]["__typename"] == "RunGroup" assert len(result_two.data["runGroupOrError"]["runs"]) == 4 assert ( result_one.data["runGroupOrError"]["rootRunId"] == result_two.data["runGroupOrError"]["rootRunId"] ) assert ( result_one.data["runGroupOrError"]["runs"] == result_two.data["runGroupOrError"]["runs"] ) def test_run_group_not_found(): with instance_for_test() as instance: with define_out_of_process_context( __file__, "get_repo_at_time_1", instance ) as context_at_time_1: result = execute_dagster_graphql( context_at_time_1, RUN_GROUP_QUERY, variables={"runId": "foo"}, ) assert result.data assert result.data["runGroupOrError"] assert result.data["runGroupOrError"]["__typename"] == "RunGroupNotFoundError" assert result.data["runGroupOrError"]["runId"] == "foo" assert result.data["runGroupOrError"][ "message" ] == "Run group of run {run_id} could not be found.".format(run_id="foo") def test_asset_batching(): with instance_for_test() as instance: repo = get_asset_repo() foo_job = repo.get_job("foo_job") for _ in range(3): foo_job.execute_in_process(instance=instance) my_fail_asset_job = repo.get_job("my_fail_asset_job") result = my_fail_asset_job.execute_in_process(instance=instance, raise_on_error=False) fail_run_id = result.dagster_run.run_id with define_out_of_process_context(__file__, "asset_repo", instance) as context: traced_counter.set(Counter()) result = execute_dagster_graphql( context, ASSET_RUNS_QUERY, variables={"assetKey": {"path": ["foo"]}} ) assert result.data assert "assetOrError" in result.data assert "assetMaterializations" in result.data["assetOrError"] materializations = result.data["assetOrError"]["assetMaterializations"] assert len(materializations) == 3 counter = traced_counter.get() counts = counter.counts() # pyright: ignore[reportOptionalMemberAccess] assert counts assert counts.get("DagsterInstance.get_run_records") == 1 run_ids = [materialization["runOrError"]["id"] for materialization in materializations] run_id = run_ids[0] result = execute_dagster_graphql(context, RUN_ASSETS_QUERY, variables={"runId": run_id}) asset_ids = [asset["id"] for asset in result.data["pipelineRunOrError"]["assets"]] assert sorted(asset_ids) == sorted(['["foo"]', '["bar"]']) fail_run_result = execute_dagster_graphql( context, RUN_ASSETS_QUERY, variables={"runId": fail_run_id} ) # despite no materialization or observation, the asset is returned, because it was planned asset_ids = [ asset["id"] for asset in fail_run_result.data["pipelineRunOrError"]["assets"] ] assert asset_ids == ['["my_fail_asset"]'] def test_run_has_concurrency_slots(): with tempfile.TemporaryDirectory() as temp_dir: with instance_for_test( overrides={ "event_log_storage": { "module": "dagster.utils.test", "class": "ConcurrencyEnabledSqliteTestEventLogStorage", "config": {"base_dir": temp_dir}, }, } ) as instance: repo = get_asset_repo() instance.event_log_storage.set_concurrency_slots("foo", 1) run_id = instance.create_run_for_job( repo.get_job("foo_job"), status=DagsterRunStatus.FAILURE ).run_id with define_out_of_process_context(__file__, "asset_repo", instance) as context: result = execute_dagster_graphql(context, RUN_CONCURRENCY_QUERY) assert result.data assert len(result.data["pipelineRunsOrError"]["results"]) == 1 assert result.data["pipelineRunsOrError"]["results"][0]["runId"] == run_id assert not result.data["pipelineRunsOrError"]["results"][0][ "hasConcurrencyKeySlots" ] assert result.data["pipelineRunsOrError"]["results"][0]["rootConcurrencyKeys"] assert result.data["pipelineRunsOrError"]["results"][0]["allPools"] claim = instance.event_log_storage.claim_concurrency_slot( "foo", run_id, "fake_step_key" ) assert claim.is_claimed with define_out_of_process_context(__file__, "asset_repo", instance) as context: result = execute_dagster_graphql(context, RUN_CONCURRENCY_QUERY) assert result.data assert len(result.data["pipelineRunsOrError"]["results"]) == 1 assert result.data["pipelineRunsOrError"]["results"][0]["runId"] == run_id assert result.data["pipelineRunsOrError"]["results"][0]["hasConcurrencyKeySlots"] assert result.data["pipelineRunsOrError"]["results"][0]["rootConcurrencyKeys"] assert result.data["pipelineRunsOrError"]["results"][0]["allPools"] @pytest.mark.parametrize( "run_tag, run_tag_value, run_metrics_enabled, failure_message", [ (None, None, False, "run_metrics tag not present should result to false"), (".dagster/run_metrics", "true", True, "run_metrics tag set to true should result to true"), ( ".dagster/run_metrics", "false", False, "run_metrics tag set to falsy value should result to false", ), ( "dagster/run_metrics", "true", True, "public run_metrics tag set to true should result to true", ), ], ) def test_run_has_run_metrics_enabled(run_tag, run_tag_value, run_metrics_enabled, failure_message): with instance_for_test() as instance: repo = get_repo_at_time_1() tags = ( { run_tag: run_tag_value, } if run_tag else {} ) run = instance.create_run_for_job( repo.get_job("foo_job"), status=DagsterRunStatus.STARTED, tags=tags ) with define_out_of_process_context(__file__, "get_repo_at_time_1", instance) as context: result = execute_dagster_graphql( context, RUN_METRICS_QUERY, variables={"runId": run.run_id}, ) assert result.data has_run_metrics_enabled = result.data["pipelineRunOrError"]["hasRunMetricsEnabled"] assert has_run_metrics_enabled == run_metrics_enabled, failure_message def test_event_log_step_stats_retry_with_no_start(): with instance_for_test() as instance: repo = get_repo_at_time_1() run = instance.create_run_for_job(repo.get_job("foo_job"), status=DagsterRunStatus.STARTED) storage = instance.event_log_storage node_handle = NodeHandle("E", None) step_handle = StepHandle(node_handle) storage.store_event( EventLogEntry( error_info=None, user_message="", level="debug", run_id=run.run_id, timestamp=time.time() - 150, step_key=step_handle.to_key(), job_name="foo_job", dagster_event=DagsterEvent( DagsterEventType.STEP_UP_FOR_RETRY.value, "foo_job", node_handle=node_handle, step_handle=step_handle, event_specific_data=None, ), ) ) with define_out_of_process_context(__file__, "get_repo_at_time_1", instance) as context: result = execute_dagster_graphql( context, RUN_STEP_STATS_QUERY, variables={"runId": run.run_id}, ) assert result.data step_stats = result.data["pipelineRunOrError"]["stepStats"] assert len(step_stats) == 1 step_stat = step_stats[0] assert step_stat["stepKey"] == "E" assert step_stat["status"] is None
TestGetRuns
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/hooks/glue_databrew.py
{ "start": 894, "end": 2580 }
class ____(AwsBaseHook): """ Interact with AWS DataBrew. Additional arguments (such as ``aws_conn_id``) may be specified and are passed down to the underlying AwsBaseHook. .. seealso:: - :class:`~airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook` """ def __init__(self, *args, **kwargs): kwargs["client_type"] = "databrew" super().__init__(*args, **kwargs) def job_completion(self, job_name: str, run_id: str, delay: int = 10, max_attempts: int = 60) -> str: """ Wait until Glue DataBrew job reaches terminal status. :param job_name: The name of the job being processed during this run. :param run_id: The unique identifier of the job run. :param delay: Time in seconds to delay between polls :param maxAttempts: Maximum number of attempts to poll for completion :return: job status """ self.get_waiter("job_complete").wait( Name=job_name, RunId=run_id, WaiterConfig={"Delay": delay, "maxAttempts": max_attempts}, ) status = self.get_job_state(job_name, run_id) return status def get_job_state(self, job_name: str, run_id: str) -> str: """ Get the status of a job run. :param job_name: The name of the job being processed during this run. :param run_id: The unique identifier of the job run. :return: State of the job run. 'STARTING'|'RUNNING'|'STOPPING'|'STOPPED'|'SUCCEEDED'|'FAILED'|'TIMEOUT' """ response = self.conn.describe_job_run(Name=job_name, RunId=run_id) return response["State"]
GlueDataBrewHook
python
getsentry__sentry
tests/sentry/integrations/api/endpoints/test_organization_integration_serverless_functions.py
{ "start": 554, "end": 3716 }
class ____(APITestCase): endpoint = "sentry-api-0-organization-integration-serverless-functions" def setUp(self) -> None: super().setUp() self.project = self.create_project(organization=self.organization) self.integration, self.org_integration = self.create_provider_integration_for( self.organization, user=None, provider="aws_lambda", metadata={ "region": "us-east-2", "account_number": "599817902985", "aws_external_id": "599817902985", }, ) with assume_test_silo_mode(SiloMode.CONTROL): self.org_integration.config = {"default_project_id": self.project.id} self.org_integration.save() self.login_as(self.user) def get_response(self, **kwargs): return super().get_response(self.organization.slug, self.integration.id, **kwargs) @property def sentry_dsn(self): return ProjectKey.get_default(project=self.project).get_dsn(public=True) def set_up_response_mocks(self, get_function_response, update_function_configuration_kwargs): responses.add( responses.POST, "http://controlserver/api/0/internal/integration-proxy/", match=[ matchers.header_matcher( { "Content-Type": "application/json", "X-Sentry-Subnet-Organization-Integration": str(self.org_integration.id), }, ), matchers.json_params_matcher( { "args": [], "function_name": "get_function", "kwargs": { "FunctionName": get_function_response["Configuration"]["FunctionName"], }, } ), ], json={ "function_name": "get_function", "return_response": get_function_response, "exception": None, }, ) responses.add( responses.POST, "http://controlserver/api/0/internal/integration-proxy/", match=[ matchers.header_matcher( { "Content-Type": "application/json", "X-Sentry-Subnet-Organization-Integration": str(self.org_integration.id), }, ), matchers.json_params_matcher( { "args": [], "function_name": "update_function_configuration", "kwargs": update_function_configuration_kwargs, } ), ], json={ "function_name": "update_function_configuration", "return_response": {}, "exception": None, }, ) @override_settings( SENTRY_SUBNET_SECRET="hush-hush-im-invisible", SENTRY_CONTROL_ADDRESS="http://controlserver", )
AbstractServerlessTest
python
tox-dev__tox
src/tox/config/loader/replacer.py
{ "start": 2263, "end": 6524 }
class ____: # noqa: PLW1641 """An expression that is handled specially by the Replacer.""" def __init__(self, expr: Sequence[MatchArg], term_pos: int | None = None) -> None: self.expr = expr self.term_pos = term_pos def __repr__(self) -> str: return f"MatchExpression(expr={self.expr!r}, term_pos={self.term_pos!r})" def __eq__(self, other: object) -> bool: if isinstance(other, type(self)): return self.expr == other.expr return NotImplemented @classmethod def _next_replace_expression(cls, value: str) -> MatchExpression | None: """Process a curly brace replacement expression.""" if value.startswith("[]"): # `[]` is shorthand for `{posargs}` return MatchExpression(expr=[["posargs"]], term_pos=1) if not value.startswith(REPLACE_START): return None try: # recursively handle inner expression rec_expr, term_pos = cls.parse_and_split_to_terminator( value[1:], terminator=REPLACE_END, split=ARG_DELIMITER, ) except MatchError: # didn't find the expected terminator character, so treat `{` as if escaped. pass else: return MatchExpression(expr=rec_expr, term_pos=term_pos) return None @classmethod def parse_and_split_to_terminator( cls, value: str, terminator: str = "", split: str | None = None, ) -> tuple[Sequence[MatchArg], int]: """ Tokenize `value` to up `terminator` character. If `split` is given, multiple arguments will be returned. Returns list of arguments (list of str or MatchExpression) and final character position examined in value. This function recursively calls itself via `_next_replace_expression`. """ args = [] last_arg: list[str | MatchExpression] = [] pos = 0 while pos < len(value): if len(value) > pos + 1 and value[pos] == "\\": if value[pos + 1] in BACKSLASH_ESCAPE_CHARS: # backslash escapes the next character from a special set last_arg.append(value[pos + 1]) pos += 2 continue if value[pos + 1] == "\\": # backlash doesn't escape a backslash, but does prevent it from affecting the next char # a subsequent `shlex` pass will eat the double backslash during command splitting. last_arg.append(value[pos : pos + 2]) pos += 2 continue fragment = value[pos:] if terminator and fragment.startswith(terminator): pos += len(terminator) break if split and fragment.startswith(split): # found a new argument args.append(last_arg) last_arg = [] pos += len(split) continue expr = cls._next_replace_expression(fragment) if expr is not None: pos += (expr.term_pos or 0) + 1 last_arg.append(expr) continue # default case: consume the next character last_arg.append(value[pos]) pos += 1 else: # fell out of the loop if terminator: msg = f"{terminator!r} remains unmatched in {value!r}" raise MatchError(msg) args.append(last_arg) return [_flatten_string_fragments(a) for a in args], pos def _flatten_string_fragments(seq_of_str_or_other: Sequence[str | Any]) -> Sequence[str | Any]: """Join runs of contiguous str values in a sequence; nny non-str items in the sequence are left as-is.""" result = [] last_str = [] for obj in seq_of_str_or_other: if isinstance(obj, str): last_str.append(obj) else: if last_str: result.append("".join(last_str)) last_str = [] result.append(obj) if last_str: result.append("".join(last_str)) return result
MatchExpression
python
pypa__setuptools
setuptools/command/build_py.py
{ "start": 13102, "end": 15826 }
class ____: """Inform users that package or module is included as 'data file'""" class _Warning(SetuptoolsDeprecationWarning): _SUMMARY = """ Package {importable!r} is absent from the `packages` configuration. """ _DETAILS = """ ############################ # Package would be ignored # ############################ Python recognizes {importable!r} as an importable package[^1], but it is absent from setuptools' `packages` configuration. This leads to an ambiguous overall configuration. If you want to distribute this package, please make sure that {importable!r} is explicitly added to the `packages` configuration field. Alternatively, you can also rely on setuptools' discovery methods (for example by using `find_namespace_packages(...)`/`find_namespace:` instead of `find_packages(...)`/`find:`). You can read more about "package discovery" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/package_discovery.html If you don't want {importable!r} to be distributed and are already explicitly excluding {importable!r} via `find_namespace_packages(...)/find_namespace` or `find_packages(...)/find`, you can try to use `exclude_package_data`, or `include-package-data=False` in combination with a more fine grained `package-data` configuration. You can read more about "package data files" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/datafiles.html [^1]: For Python, any directory (with suitable naming) can be imported, even if it does not contain any `.py` files. On the other hand, currently there is no concept of package data directory, all directories are treated like packages. """ # _DUE_DATE: still not defined as this is particularly controversial. # Warning initially introduced in May 2022. See issue #3340 for discussion. def __init__(self) -> None: self._already_warned = set[str]() def is_module(self, file): return file.endswith(".py") and file[: -len(".py")].isidentifier() def importable_subpackage(self, parent, file): pkg = Path(file).parent parts = list(itertools.takewhile(str.isidentifier, pkg.parts)) if parts: return ".".join([parent, *parts]) return None def warn(self, importable): if importable not in self._already_warned: self._Warning.emit(importable=importable) self._already_warned.add(importable)
_IncludePackageDataAbuse
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/layout/processors.py
{ "start": 14412, "end": 16010 }
class ____(Processor): """ When we're in Vi block insert mode, display all the cursors. """ def apply_transformation( self, transformation_input: TransformationInput ) -> Transformation: ( buffer_control, document, lineno, source_to_display, fragments, _, _, ) = transformation_input.unpack() buff = buffer_control.buffer if vi_insert_multiple_mode(): cursor_positions = buff.multiple_cursor_positions fragments = explode_text_fragments(fragments) # If any cursor appears on the current line, highlight that. start_pos = document.translate_row_col_to_index(lineno, 0) end_pos = start_pos + len(document.lines[lineno]) fragment_suffix = " class:multiple-cursors" for p in cursor_positions: if start_pos <= p <= end_pos: column = source_to_display(p - start_pos) # Replace fragment. try: style, text, *_ = fragments[column] except IndexError: # Cursor needs to be displayed after the current text. fragments.append((fragment_suffix, " ")) else: style += fragment_suffix fragments[column] = (style, text) return Transformation(fragments) else: return Transformation(fragments)
DisplayMultipleCursors
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 243320, "end": 245445 }
class ____(sgqlc.types.Input): """Ways in which to filter lists of issues.""" __schema__ = github_schema __field_names__ = ( "assignee", "created_by", "labels", "mentioned", "milestone", "milestone_number", "since", "states", "viewer_subscribed", ) assignee = sgqlc.types.Field(String, graphql_name="assignee") """List issues assigned to given name. Pass in `null` for issues with no assigned user, and `*` for issues assigned to any user. """ created_by = sgqlc.types.Field(String, graphql_name="createdBy") """List issues created by given name.""" labels = sgqlc.types.Field(sgqlc.types.list_of(sgqlc.types.non_null(String)), graphql_name="labels") """List issues where the list of label names exist on the issue.""" mentioned = sgqlc.types.Field(String, graphql_name="mentioned") """List issues where the given name is mentioned in the issue.""" milestone = sgqlc.types.Field(String, graphql_name="milestone") """List issues by given milestone argument. If an string representation of an integer is passed, it should refer to a milestone by its database ID. Pass in `null` for issues with no milestone, and `*` for issues that are assigned to any milestone. """ milestone_number = sgqlc.types.Field(String, graphql_name="milestoneNumber") """List issues by given milestone argument. If an string representation of an integer is passed, it should refer to a milestone by its number field. Pass in `null` for issues with no milestone, and `*` for issues that are assigned to any milestone. """ since = sgqlc.types.Field(DateTime, graphql_name="since") """List issues that have been updated at or after the given date.""" states = sgqlc.types.Field(sgqlc.types.list_of(sgqlc.types.non_null(IssueState)), graphql_name="states") """List issues filtered by the list of states given.""" viewer_subscribed = sgqlc.types.Field(Boolean, graphql_name="viewerSubscribed") """List issues subscribed to by viewer."""
IssueFilters
python
huggingface__transformers
src/transformers/models/pegasus_x/modeling_pegasus_x.py
{ "start": 22580, "end": 27933 }
class ____(GradientCheckpointingLayer): def __init__(self, stagger_blocks_this_layer: bool, config: PegasusXConfig): super().__init__() self.embed_dim = config.d_model self.self_attn = PegasusXGlobalLocalAttention( embed_dim=self.embed_dim, num_heads=config.encoder_attention_heads, block_size=config.block_size, dropout=config.attention_dropout, ) self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) self.global_self_attn_layer_norm = nn.LayerNorm(self.embed_dim) self.dropout = config.dropout self.activation_fn = ACT2FN[config.activation_function] self.activation_dropout = config.activation_dropout self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim) self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim) self.final_layer_norm = nn.LayerNorm(self.embed_dim) self.stagger_blocks_this_layer = stagger_blocks_this_layer self.block_size = config.block_size def forward( self, hidden_states: torch.Tensor, global_hidden_states: torch.Tensor, attention_mask: torch.Tensor, output_attentions: bool = False, ) -> torch.Tensor: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape *(seq_len, batch, embed_dim)* global_hidden_states (`torch.FloatTensor`): global token hidden states *(seq_len, num_global_tokens, embed_dim)* attention_mask (`torch.FloatTensor`): attention mask of size *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. """ residual = hidden_states global_residual = global_hidden_states hidden_states = self.self_attn_layer_norm(hidden_states) global_hidden_states = self.global_self_attn_layer_norm(global_hidden_states) if self.stagger_blocks_this_layer: # Pad the blocks to simulate staggering hidden_states, attention_mask = self.pad_local_tokens( hidden_states=hidden_states, attention_mask=attention_mask, block_size=self.block_size ) hidden_states, global_hidden_states, attn_weights = self.self_attn( token_hidden_states=hidden_states, global_hidden_states=global_hidden_states, attention_mask=attention_mask, output_attentions=output_attentions, ) if self.stagger_blocks_this_layer: # Undo the padding hidden_states = self.unpad_local_tokens(padded_hidden_states=hidden_states, block_size=self.block_size) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states global_hidden_states = nn.functional.dropout(global_hidden_states, p=self.dropout, training=self.training) global_hidden_states = global_residual + global_hidden_states residual = hidden_states hidden_states = self.final_layer_norm(hidden_states) hidden_states = self.activation_fn(self.fc1(hidden_states)) hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training) hidden_states = self.fc2(hidden_states) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states global_residual = global_hidden_states global_hidden_states = self.final_layer_norm(global_hidden_states) global_hidden_states = self.activation_fn(self.fc1(global_hidden_states)) global_hidden_states = nn.functional.dropout( global_hidden_states, p=self.activation_dropout, training=self.training ) global_hidden_states = self.fc2(global_hidden_states) global_hidden_states = nn.functional.dropout(global_hidden_states, p=self.dropout, training=self.training) global_hidden_states = global_residual + global_hidden_states outputs = (hidden_states, global_hidden_states) if output_attentions: outputs += (attn_weights,) return outputs @classmethod def pad_local_tokens(cls, hidden_states, attention_mask, block_size): # hidden_states: [batch_size, seq_len, hidden_dim] pad_size = block_size // 2 mask_min_value = torch.finfo(hidden_states.dtype).min padded_hidden_states = torch.nn.functional.pad( hidden_states, pad=(0, 0, pad_size, pad_size), ) padded_mask = torch.nn.functional.pad( attention_mask, pad=(pad_size, pad_size), value=mask_min_value, ) return padded_hidden_states, padded_mask @classmethod def unpad_local_tokens(cls, padded_hidden_states, block_size): # padded_hidden_states: [batch_size, padded seq_len, hidden_dim] pad_size = block_size // 2 return padded_hidden_states[:, pad_size:-pad_size, :]
PegasusXEncoderLayer
python
openai__openai-python
src/openai/types/beta/threads/runs/message_creation_step_details.py
{ "start": 347, "end": 506 }
class ____(BaseModel): message_creation: MessageCreation type: Literal["message_creation"] """Always `message_creation`."""
MessageCreationStepDetails
python
readthedocs__readthedocs.org
readthedocs/organizations/migrations/0001_squashed.py
{ "start": 238, "end": 13343 }
class ____(migrations.Migration): safe = Safe.after_deploy() initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("projects", "0002_add_importedfile_model"), ] operations = [ migrations.CreateModel( name="Organization", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "pub_date", models.DateTimeField(auto_now_add=True, verbose_name="Publication date"), ), ( "modified_date", models.DateTimeField(auto_now=True, verbose_name="Modified date"), ), ("name", models.CharField(max_length=100, verbose_name="Name")), ( "slug", models.SlugField(max_length=255, unique=True, verbose_name="Slug"), ), ( "email", models.EmailField( blank=True, help_text=b"How can we get in touch with you?", max_length=255, null=True, verbose_name="E-mail", ), ), ( "description", models.TextField( blank=True, help_text=b"Tell us a little about yourself.", null=True, verbose_name="Description", ), ), ( "url", models.URLField( blank=True, help_text=b"The main website for your Organization", max_length=255, null=True, verbose_name="Home Page", ), ), ( "public_key", models.TextField( blank=True, help_text=b"Add this to your version control to give us access. Specific to your Organization.", null=True, verbose_name="Public SSH Key", ), ), ( "private_key", models.TextField(blank=True, null=True, verbose_name="Private SSH Key"), ), ], ), migrations.CreateModel( name="OrganizationOwner", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "organization", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="organizations.Organization", ), ), ( "owner", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, ), ), ], ), migrations.CreateModel( name="Team", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "pub_date", models.DateTimeField(auto_now_add=True, verbose_name="Publication date"), ), ( "modified_date", models.DateTimeField(auto_now=True, verbose_name="Modified date"), ), ("name", models.CharField(max_length=100, verbose_name="Name")), ("slug", models.SlugField(max_length=255, verbose_name="Slug")), ( "access", models.CharField( choices=[(b"readonly", "Read-only"), (b"admin", "Admin")], default=b"readonly", max_length=100, verbose_name="Access", ), ), ], ), migrations.CreateModel( name="TeamInvite", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "pub_date", models.DateTimeField(auto_now_add=True, verbose_name="Publication date"), ), ( "modified_date", models.DateTimeField(auto_now=True, verbose_name="Modified date"), ), ("email", models.EmailField(max_length=254, verbose_name="E-mail")), ("hash", models.CharField(max_length=250, verbose_name="Hash")), ("count", models.IntegerField(default=0, verbose_name="Count")), ("total", models.IntegerField(default=10, verbose_name="Total")), ( "organization", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="invites", to="organizations.Organization", ), ), ( "team", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="invites", to="organizations.Team", verbose_name="Team", ), ), ], options={ "unique_together": {("team", "email")}, }, ), migrations.CreateModel( name="TeamMember", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ( "invite", models.ForeignKey( blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_NULL, to="organizations.TeamInvite", ), ), ( "member", models.ForeignKey( blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, ), ), ( "team", models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, to="organizations.Team", ), ), ], options={ "unique_together": { ("team", "member"), ("team", "invite"), ("team", "member", "invite"), }, }, ), migrations.AddField( model_name="team", name="members", field=models.ManyToManyField( blank=True, related_name="teams", through="organizations.TeamMember", to=settings.AUTH_USER_MODEL, verbose_name="Users", ), ), migrations.AddField( model_name="team", name="organization", field=models.ForeignKey( on_delete=django.db.models.deletion.CASCADE, related_name="teams", to="organizations.Organization", ), ), migrations.AddField( model_name="team", name="projects", field=models.ManyToManyField( blank=True, related_name="teams", to="projects.Project", verbose_name="Projects", ), ), migrations.AddField( model_name="organization", name="owners", field=models.ManyToManyField( related_name="owner_organizations", through="organizations.OrganizationOwner", to=settings.AUTH_USER_MODEL, verbose_name="Owners", ), ), migrations.AddField( model_name="organization", name="projects", field=models.ManyToManyField( related_name="organizations", to="projects.Project", verbose_name="Projects", ), ), migrations.AlterUniqueTogether( name="team", unique_together={("name", "organization"), ("slug", "organization")}, ), migrations.AddField( model_name="organization", name="stripe_id", field=models.CharField( blank=True, max_length=100, null=True, verbose_name="Stripe customer ID" ), ), migrations.AlterField( model_name="team", name="slug", field=autoslug.fields.AutoSlugField( always_update=True, editable=False, populate_from=models.CharField(max_length=100, verbose_name="Name"), unique_with=[b"organization"], ), ), migrations.AddField( model_name="organization", name="disabled", field=models.BooleanField( default=False, help_text="Docs and builds are disabled for this organization", verbose_name="Disabled", ), ), migrations.AlterModelOptions( name="organization", options={"get_latest_by": ["-pub_date"], "ordering": ["name"]}, ), migrations.AlterField( model_name="organization", name="description", field=models.TextField( blank=True, help_text="Tell us a little about yourself.", null=True, verbose_name="Description", ), ), migrations.AlterField( model_name="organization", name="email", field=models.EmailField( blank=True, help_text="How can we get in touch with you?", max_length=255, null=True, verbose_name="E-mail", ), ), migrations.RemoveField( model_name="organization", name="public_key", ), migrations.AlterField( model_name="organization", name="url", field=models.URLField( blank=True, help_text="The main website for your Organization", max_length=255, null=True, verbose_name="Home Page", ), ), migrations.AlterField( model_name="team", name="access", field=models.CharField( choices=[("readonly", "Read-only"), ("admin", "Admin")], default="readonly", max_length=100, verbose_name="Access", ), ), migrations.AlterField( model_name="team", name="slug", field=autoslug.fields.AutoSlugField( always_update=True, editable=False, populate_from="name", unique_with=["organization"], ), ), migrations.RemoveField( model_name="organization", name="private_key", ), ]
Migration
python
scrapy__scrapy
tests/test_spidermiddleware_referer.py
{ "start": 25053, "end": 25180 }
class ____(MixinUnsafeUrl, TestRefererMiddleware): req_meta = {"referrer_policy": POLICY_UNSAFE_URL}
TestRequestMetaUnsafeUrl
python
kamyu104__LeetCode-Solutions
Python/check-if-a-string-is-a-valid-sequence-from-root-to-leaves-path-in-a-binary-tree.py
{ "start": 894, "end": 1496 }
class ____(object): def isValidSequence(self, root, arr): """ :type root: TreeNode :type arr: List[int] :rtype: bool """ s = [(root, 0)] while s: node, depth = s.pop() if not node or depth == len(arr) or node.val != arr[depth]: continue if depth+1 == len(arr) and node.left == node.right: return True s.append((node.right, depth+1)) s.append((node.left, depth+1)) return False # Time: O(n) # Space: O(h) # dfs solution with recursion
Solution2
python
readthedocs__readthedocs.org
readthedocs/search/tests/test_faceted_search.py
{ "start": 117, "end": 2290 }
class ____: @pytest.mark.parametrize("case", ["upper", "lower", "title"]) def test_search_exact_match(self, client, project, case): """Check quoted query match exact phrase with case insensitively Making a query with quoted text like ``"foo bar"`` should match exactly ``foo bar`` or ``Foo Bar`` etc """ # `Sphinx` word is present both in `kuma` and `docs` files # But the phrase `Sphinx uses` is available only in kuma docs. # So search with this phrase to check query_text = r'"Sphinx uses"' cased_query = getattr(query_text, case) query = cased_query() page_search = PageSearch(query=query) results = page_search.execute() assert len(results) == 2 # Both versions have the same exact content. # Order of results is not deterministic anymore for some reason, # so we use a set to compare the results. assert {result["version"] for result in results} == {"stable", "latest"} for result in results: assert result["project"] == "kuma" assert result["path"] == "testdocumentation" def test_search_combined_result(self, client, project): """Check search result are combined of both `AND` and `OR` operator If query is `Foo Bar` then the result should be as following order: - Where both `Foo Bar` is present - Where `Foo` or `Bar` is present """ query = "Elasticsearch Query" page_search = PageSearch(query=query) results = page_search.execute() assert len(results) == 6 result_paths_latest = [r.path for r in results if r.version == "latest"] result_paths_stable = [r.path for r in results if r.version == "stable"] # ``guides/wipe-environment`` page has both ``Elasticsearch Query`` words # ``docker`` page has ``Elasticsearch`` word # ``installation`` page has ``Query`` word. expected_paths = ["guides/wipe-environment", "docker", "installation"] assert result_paths_latest == expected_paths assert result_paths_stable == expected_paths
TestPageSearch
python
facebook__pyre-check
source/interprocedural_analyses/taint/test/integration/readonly.py
{ "start": 1078, "end": 1475 }
class ____: tainted: str = "" not_tainted: str = "" def readonly_foo_tainted(foo: PyreReadOnly[Foo]) -> None: _test_sink(foo.tainted) def readonly_foo_not_tainted(foo: PyreReadOnly[Foo]) -> None: _test_sink(foo.not_tainted) def regular_foo_tainted(foo: Foo) -> None: _test_sink(foo.tainted) def regular_foo_not_tainted(foo: Foo) -> None: _test_sink(foo.not_tainted)
Foo
python
apache__airflow
airflow-core/tests/unit/core/test_sqlalchemy_config.py
{ "start": 1232, "end": 4595 }
class ____: @pytest.fixture(autouse=True, scope="class") def reset(self): try: with pytest.MonkeyPatch.context() as mp: mp.setattr( settings, "SQL_ALCHEMY_CONN", "mysql+foobar://user:pass@host/dbname?inline=param&another=param", ) yield finally: settings.configure_orm() @patch("airflow.settings.setup_event_handlers") @patch("airflow.settings.scoped_session") @patch("airflow.settings.sessionmaker") @patch("airflow.settings.create_engine") def test_configure_orm_with_default_values( self, mock_create_engine, mock_sessionmaker, mock_scoped_session, mock_setup_event_handlers ): settings.configure_orm() expected_kwargs = dict( connect_args={} if not settings.SQL_ALCHEMY_CONN.startswith("sqlite") else {"check_same_thread": False}, max_overflow=10, pool_pre_ping=True, pool_recycle=1800, pool_size=5, isolation_level="READ COMMITTED", future=True, ) if SQLALCHEMY_V_1_4: expected_kwargs["encoding"] = "utf-8" mock_create_engine.assert_called_once_with( settings.SQL_ALCHEMY_CONN, **expected_kwargs, ) @patch("airflow.settings.setup_event_handlers") @patch("airflow.settings.scoped_session") @patch("airflow.settings.sessionmaker") @patch("airflow.settings.create_engine") def test_sql_alchemy_connect_args( self, mock_create_engine, mock_sessionmaker, mock_scoped_session, mock_setup_event_handlers ): config = { ( "database", "sql_alchemy_connect_args", ): "unit.core.test_sqlalchemy_config.SQL_ALCHEMY_CONNECT_ARGS", ("database", "sql_alchemy_engine_args"): '{"arg": 1}', ("database", "sql_alchemy_pool_enabled"): "False", } with conf_vars(config): settings.configure_orm() engine_args = {"arg": 1} if settings.SQL_ALCHEMY_CONN.startswith("mysql"): engine_args["isolation_level"] = "READ COMMITTED" expected_kwargs = dict( connect_args=SQL_ALCHEMY_CONNECT_ARGS, poolclass=NullPool, future=True, **engine_args, ) if SQLALCHEMY_V_1_4: expected_kwargs["encoding"] = "utf-8" mock_create_engine.assert_called_once_with( settings.SQL_ALCHEMY_CONN, **expected_kwargs, ) @patch("airflow.settings.setup_event_handlers") @patch("airflow.settings.scoped_session") @patch("airflow.settings.sessionmaker") @patch("airflow.settings.create_engine") def test_sql_alchemy_invalid_connect_args( self, mock_create_engine, mock_sessionmaker, mock_scoped_session, mock_setup_event_handlers ): config = { ("database", "sql_alchemy_connect_args"): "does.not.exist", ("database", "sql_alchemy_pool_enabled"): "False", } with pytest.raises(AirflowConfigException): with conf_vars(config): settings.configure_orm()
TestSqlAlchemySettings
python
plotly__plotly.py
tests/test_optional/test_figure_factory/test_figure_factory.py
{ "start": 144901, "end": 153895 }
class ____(NumpyTestUtilsMixin, TestCaseNoTemplate): def compare_list_values(self, list1, list2, decimal=7): assert len(list1) == len(list2), "Lists are not of the same length." for i in range(len(list1)): if isinstance(list1[i], list): self.compare_list_values(list1[i], list2[i], decimal=decimal) elif isinstance(list1[i], dict): self.compare_dict_values(list1[i], list2[i], decimal=decimal) elif isinstance(list1[i], float): np.testing.assert_almost_equal(list1[i], list2[i], decimal=decimal) else: assert list1[i] == list2[i], ( f"Values at index {i} are not equal: {list1[i]} != {list2[i]}" ) def compare_dict_values(self, dict1, dict2, decimal=7): for k, v in dict1.items(): if isinstance(v, dict): self.compare_dict_values(v, dict2[k], decimal=decimal) elif isinstance(v, list): self.compare_list_values(v, dict2[k], decimal=decimal) elif isinstance(v, float): np.testing.assert_almost_equal(v, dict2[k], decimal=decimal) else: assert v == dict2[k], ( f"Values for key {k} are not equal: {v} != {dict2[k]}" ) def test_aggregation(self): lat = [0, 1, 1, 2, 4, 5, 1, 2, 4, 5, 2, 3, 2, 1, 5, 3, 5] lon = [1, 2, 3, 3, 0, 4, 5, 0, 5, 3, 1, 5, 4, 0, 1, 2, 5] color = np.ones(len(lat)) fig1 = ff.create_hexbin_map(lat=lat, lon=lon, nx_hexagon=1) actual_geojson = { "type": "FeatureCollection", "features": [ { "type": "Feature", "id": "-8.726646259971648e-11,-0.031886255679892235", "geometry": { "type": "Polygon", "coordinates": [ [ [-5e-09, -4.7083909316316985], [2.4999999999999996, -3.268549270944215], [2.4999999999999996, -0.38356933397072673], [-5e-09, 1.0597430482129082], [-2.50000001, -0.38356933397072673], [-2.50000001, -3.268549270944215], [-5e-09, -4.7083909316316985], ] ], }, }, { "type": "Feature", "id": "-8.726646259971648e-11,0.1192636916419258", "geometry": { "type": "Polygon", "coordinates": [ [ [-5e-09, 3.9434377827164666], [2.4999999999999996, 5.381998306154031], [2.4999999999999996, 8.248045720432454], [-5e-09, 9.673766164509932], [-2.50000001, 8.248045720432454], [-2.50000001, 5.381998306154031], [-5e-09, 3.9434377827164666], ] ], }, }, { "type": "Feature", "id": "0.08726646268698293,-0.031886255679892235", "geometry": { "type": "Polygon", "coordinates": [ [ [5.0000000049999995, -4.7083909316316985], [7.500000009999999, -3.268549270944215], [7.500000009999999, -0.38356933397072673], [5.0000000049999995, 1.0597430482129082], [2.5, -0.38356933397072673], [2.5, -3.268549270944215], [5.0000000049999995, -4.7083909316316985], ] ], }, }, { "type": "Feature", "id": "0.08726646268698293,0.1192636916419258", "geometry": { "type": "Polygon", "coordinates": [ [ [5.0000000049999995, 3.9434377827164666], [7.500000009999999, 5.381998306154031], [7.500000009999999, 8.248045720432454], [5.0000000049999995, 9.673766164509932], [2.5, 8.248045720432454], [2.5, 5.381998306154031], [5.0000000049999995, 3.9434377827164666], ] ], }, }, { "type": "Feature", "id": "0.04363323129985823,0.04368871798101678", "geometry": { "type": "Polygon", "coordinates": [ [ [2.4999999999999996, -0.38356933397072673], [5.0000000049999995, 1.0597430482129082], [5.0000000049999995, 3.9434377827164666], [2.4999999999999996, 5.381998306154031], [-5.0000001310894304e-09, 3.9434377827164666], [-5.0000001310894304e-09, 1.0597430482129082], [2.4999999999999996, -0.38356933397072673], ] ], }, }, ], } actual_agg = [2.0, 2.0, 1.0, 3.0, 9.0] self.compare_dict_values(fig1.data[0].geojson, actual_geojson) assert np.array_equal(fig1.data[0].z, actual_agg) fig2 = ff.create_hexbin_map( lat=lat, lon=lon, nx_hexagon=1, color=color, agg_func=np.mean, ) assert np.array_equal(fig2.data[0].z, np.ones(5)) fig3 = ff.create_hexbin_map( lat=np.random.randn(1000), lon=np.random.randn(1000), nx_hexagon=20, ) assert fig3.data[0].z.sum() == 1000 def test_build_dataframe(self): np.random.seed(0) N = 10000 nx_hexagon = 20 n_frames = 3 lat = np.random.randn(N) lon = np.random.randn(N) color = np.ones(N) frame = np.random.randint(0, n_frames, N) df = pd.DataFrame( # TODO: Test other constructors? np.c_[lat, lon, color, frame], columns=["Latitude", "Longitude", "Metric", "Frame"], ) fig1 = ff.create_hexbin_map(lat=lat, lon=lon, nx_hexagon=nx_hexagon) fig2 = ff.create_hexbin_map( data_frame=df, lat="Latitude", lon="Longitude", nx_hexagon=nx_hexagon ) assert isinstance(fig1, go.Figure) assert len(fig1.data) == 1 self.assert_dict_equal( fig1.to_plotly_json()["data"][0], fig2.to_plotly_json()["data"][0] ) fig3 = ff.create_hexbin_map( lat=lat, lon=lon, nx_hexagon=nx_hexagon, color=color, agg_func=np.sum, min_count=0, ) fig4 = ff.create_hexbin_map( lat=lat, lon=lon, nx_hexagon=nx_hexagon, color=color, agg_func=np.sum, ) fig5 = ff.create_hexbin_map( data_frame=df, lat="Latitude", lon="Longitude", nx_hexagon=nx_hexagon, color="Metric", agg_func=np.sum, ) self.assert_dict_equal( fig1.to_plotly_json()["data"][0], fig3.to_plotly_json()["data"][0] ) self.assert_dict_equal( fig4.to_plotly_json()["data"][0], fig5.to_plotly_json()["data"][0] ) fig6 = ff.create_hexbin_map( data_frame=df, lat="Latitude", lon="Longitude", nx_hexagon=nx_hexagon, color="Metric", agg_func=np.sum, animation_frame="Frame", ) fig7 = ff.create_hexbin_map( lat=lat, lon=lon, nx_hexagon=nx_hexagon, color=color, agg_func=np.sum, animation_frame=frame, ) assert len(fig6.frames) == n_frames assert len(fig7.frames) == n_frames assert fig6.data[0].geojson == fig1.data[0].geojson
TestHexbinMapbox
python
getsentry__sentry
tests/sentry/workflow_engine/endpoints/test_organization_detector_index.py
{ "start": 27469, "end": 46023 }
class ____(OrganizationDetectorIndexBaseTest): method = "POST" def setUp(self) -> None: super().setUp() self.connected_workflow = self.create_workflow( organization_id=self.organization.id, ) self.valid_data = { "name": "Test Detector", "type": MetricIssue.slug, "projectId": self.project.id, "dataSources": [ { "queryType": SnubaQuery.Type.ERROR.value, "dataset": Dataset.Events.name.lower(), "query": "test query", "aggregate": "count()", "timeWindow": 3600, "environment": self.environment.name, "eventTypes": [SnubaQueryEventType.EventType.ERROR.name.lower()], } ], "conditionGroup": { "id": self.data_condition_group.id, "organizationId": self.organization.id, "logicType": self.data_condition_group.logic_type, "conditions": [ { "type": Condition.GREATER, "comparison": 100, "conditionResult": DetectorPriorityLevel.HIGH, "conditionGroupId": self.data_condition_group.id, }, { "type": Condition.LESS_OR_EQUAL, "comparison": 100, "conditionResult": DetectorPriorityLevel.OK, "conditionGroupId": self.data_condition_group.id, }, ], }, "config": { "thresholdPeriod": 1, "detectionType": AlertRuleDetectionType.STATIC.value, }, "workflowIds": [self.connected_workflow.id], } def test_reject_upsampled_count_aggregate(self) -> None: """Users should not be able to submit upsampled_count() directly in ACI.""" data = {**self.valid_data} data["dataSources"] = [ {**self.valid_data["dataSources"][0], "aggregate": "upsampled_count()"} ] response = self.get_error_response( self.organization.slug, **data, status_code=400, ) assert "upsampled_count() is not allowed as user input" in str(response.data) def test_missing_group_type(self) -> None: data = {**self.valid_data} del data["type"] response = self.get_error_response( self.organization.slug, **data, status_code=400, ) assert response.data == {"type": ["This field is required."]} def test_invalid_group_type(self) -> None: data = {**self.valid_data, "type": "invalid_type"} response = self.get_error_response( self.organization.slug, **data, status_code=400, ) assert response.data == { "type": [get_unknown_detector_type_error("invalid_type", self.organization)] } def test_incompatible_group_type(self) -> None: with mock.patch("sentry.issues.grouptype.registry.get_by_slug") as mock_get: mock_get.return_value = mock.Mock(detector_settings=None) data = {**self.valid_data, "type": "incompatible_type"} response = self.get_error_response( self.organization.slug, **data, status_code=400, ) assert response.data == {"type": ["Detector type not compatible with detectors"]} def test_missing_project_id(self) -> None: data = {**self.valid_data} del data["projectId"] response = self.get_error_response( self.organization.slug, **data, status_code=400, ) assert response.data == {"projectId": ["This field is required."]} def test_project_id_not_found(self) -> None: data = {**self.valid_data} data["projectId"] = 123456 response = self.get_error_response( self.organization.slug, **data, status_code=400, ) assert response.data == {"projectId": ["Project not found"]} def test_wrong_org_project_id(self) -> None: data = {**self.valid_data} data["projectId"] = self.create_project(organization=self.create_organization()).id response = self.get_error_response( self.organization.slug, **data, status_code=400, ) assert response.data == {"projectId": ["Project not found"]} def test_without_feature_flag(self) -> None: with self.feature({"organizations:incidents": False}): response = self.get_error_response( self.organization.slug, **self.valid_data, status_code=404, ) assert response.data == { "detail": ErrorDetail(string="The requested resource does not exist", code="error") } @mock.patch("sentry.incidents.metric_issue_detector.schedule_update_project_config") @mock.patch("sentry.workflow_engine.endpoints.validators.base.detector.create_audit_entry") def test_valid_creation( self, mock_audit: mock.MagicMock, mock_schedule_update_project_config: mock.MagicMock, ) -> None: with self.tasks(): response = self.get_success_response( self.organization.slug, **self.valid_data, status_code=201, ) detector = Detector.objects.get(id=response.data["id"]) assert response.data == serialize([detector])[0] assert detector.name == "Test Detector" assert detector.type == MetricIssue.slug assert detector.project_id == self.project.id assert detector.description is None # Verify data source data_source = DataSource.objects.get(detector=detector) assert data_source.type == data_source_type_registry.get_key( QuerySubscriptionDataSourceHandler ) assert data_source.organization_id == self.organization.id # Verify query subscription query_sub = QuerySubscription.objects.get(id=int(data_source.source_id)) assert query_sub.project == self.project assert query_sub.snuba_query.type == SnubaQuery.Type.ERROR.value assert query_sub.snuba_query.dataset == Dataset.Events.value assert query_sub.snuba_query.query == "test query" assert query_sub.snuba_query.aggregate == "count()" assert query_sub.snuba_query.time_window == 3600 assert query_sub.snuba_query.environment == self.environment assert query_sub.snuba_query.event_types == [SnubaQueryEventType.EventType.ERROR] # Verify condition group and conditions condition_group = detector.workflow_condition_group assert condition_group assert condition_group.logic_type == DataConditionGroup.Type.ANY assert condition_group.organization_id == self.organization.id conditions = list(DataCondition.objects.filter(condition_group=condition_group)) assert len(conditions) == 2 condition = conditions[0] assert condition.type == Condition.GREATER assert condition.comparison == 100 assert condition.condition_result == DetectorPriorityLevel.HIGH # Verify connected workflows detector_workflow = DetectorWorkflow.objects.get( detector=detector, workflow=self.connected_workflow ) assert detector_workflow.detector == detector assert detector_workflow.workflow == self.connected_workflow # Verify audit log mock_audit.assert_called_once_with( request=mock.ANY, organization=self.organization, target_object=detector.id, event=mock.ANY, data=detector.get_audit_log_data(), ) mock_schedule_update_project_config.assert_called_once_with(detector) def test_creation_with_description(self) -> None: data = {**self.valid_data, "description": "This is a test metric detector"} with self.tasks(): response = self.get_success_response( self.organization.slug, **data, status_code=201, ) detector = Detector.objects.get(id=response.data["id"]) assert detector.description == "This is a test metric detector" def test_invalid_workflow_ids(self) -> None: # Workflow doesn't exist at all data = {**self.valid_data, "workflowIds": [999999]} response = self.get_error_response( self.organization.slug, **data, status_code=400, ) assert "Some workflows do not exist" in str(response.data) # Workflow that exists but is in another org should also fail validation other_org = self.create_organization() other_workflow = self.create_workflow(organization_id=other_org.id) data = {**self.valid_data, "workflowIds": [other_workflow.id]} response = self.get_error_response( self.organization.slug, **data, status_code=400, ) assert "Some workflows do not exist" in str(response.data) def test_transaction_rollback_on_workflow_validation_failure(self) -> None: initial_detector_count = Detector.objects.filter(project=self.project).count() # Try to create detector with invalid workflow, get an error response back data = {**self.valid_data, "workflowIds": [999999]} response = self.get_error_response( self.organization.slug, **data, status_code=400, ) # Verify that the detector was never created (same number of detectors as before) final_detector_count = Detector.objects.filter(project=self.project).count() assert final_detector_count == initial_detector_count assert "Some workflows do not exist" in str(response.data) def test_missing_required_field(self) -> None: response = self.get_error_response( self.organization.slug, status_code=400, ) assert response.data == {"type": ["This field is required."]} def test_missing_name(self) -> None: data = {**self.valid_data} del data["name"] response = self.get_error_response( self.organization.slug, **data, status_code=400, ) assert response.data == {"name": ["This field is required."]} def test_empty_query_string(self) -> None: data = {**self.valid_data} data["dataSources"][0]["query"] = "" with self.tasks(): response = self.get_success_response( self.organization.slug, **data, status_code=201, ) detector = Detector.objects.get(id=response.data["id"]) data_source = DataSource.objects.get(detector=detector) query_sub = QuerySubscription.objects.get(id=int(data_source.source_id)) assert query_sub.snuba_query.query == "" def test_valid_creation_with_owner(self) -> None: # Test data with owner field data_with_owner = { **self.valid_data, "owner": self.user.get_actor_identifier(), } with self.tasks(): response = self.get_success_response( self.organization.slug, **data_with_owner, status_code=201, ) detector = Detector.objects.get(id=response.data["id"]) # Verify owner is set correctly assert detector.owner_user_id == self.user.id assert detector.owner_team_id is None assert detector.owner is not None assert detector.owner.identifier == self.user.get_actor_identifier() # Verify serialized response includes owner assert response.data["owner"] == { "email": self.user.email, "id": str(self.user.id), "name": self.user.get_username(), "type": "user", } def test_valid_creation_with_team_owner(self) -> None: # Create a team for testing team = self.create_team(organization=self.organization) # Test data with team owner data_with_team_owner = { **self.valid_data, "owner": f"team:{team.id}", } with self.tasks(): response = self.get_success_response( self.organization.slug, **data_with_team_owner, status_code=201, ) detector = Detector.objects.get(id=response.data["id"]) # Verify team owner is set correctly assert detector.owner_user_id is None assert detector.owner_team_id == team.id assert detector.owner is not None assert detector.owner.identifier == f"team:{team.id}" # Verify serialized response includes team owner assert response.data["owner"] == { "id": str(team.id), "name": team.slug, "type": "team", } def test_invalid_owner(self) -> None: # Test with invalid owner format data_with_invalid_owner = { **self.valid_data, "owner": "invalid:owner:format", } response = self.get_error_response( self.organization.slug, **data_with_invalid_owner, status_code=400, ) assert "owner" in response.data def test_owner_not_in_organization(self) -> None: # Create a user in another organization other_org = self.create_organization() other_user = self.create_user() self.create_member(organization=other_org, user=other_user) # Test with owner not in current organization data_with_invalid_owner = { **self.valid_data, "owner": other_user.get_actor_identifier(), } response = self.get_error_response( self.organization.slug, **data_with_invalid_owner, status_code=400, ) assert "owner" in response.data @with_feature("organizations:workflow-engine-metric-detector-limit") @mock.patch("sentry.quotas.backend.get_metric_detector_limit") def test_metric_detector_limit(self, mock_get_limit: mock.MagicMock) -> None: # Set limit to 2 detectors mock_get_limit.return_value = 2 # Create 2 metric detectors (1 active, 1 to be deleted) self.create_detector( project=self.project, name="Existing Detector 1", type=MetricIssue.slug, status=ObjectStatus.ACTIVE, ) self.create_detector( project=self.project, name="Existing Detector 2", type=MetricIssue.slug, status=ObjectStatus.PENDING_DELETION, ) # Create another metric detector, it should succeed with self.tasks(): response = self.get_success_response( self.organization.slug, **self.valid_data, status_code=201, ) detector = Detector.objects.get(id=response.data["id"]) assert detector.name == "Test Detector" # Create another metric detector, it should fail response = self.get_error_response( self.organization.slug, **self.valid_data, status_code=400, ) assert response.status_code == 400 @with_feature("organizations:workflow-engine-metric-detector-limit") @mock.patch("sentry.quotas.backend.get_metric_detector_limit") def test_metric_detector_limit_unlimited_plan(self, mock_get_limit: mock.MagicMock) -> None: # Set limit to -1 (unlimited) mock_get_limit.return_value = -1 # Create many metric detectors for i in range(5): self.create_detector( project=self.project, name=f"Existing Detector {i+1}", type=MetricIssue.slug, status=ObjectStatus.ACTIVE, ) # Create another detector, it should succeed with self.tasks(): response = self.get_success_response( self.organization.slug, **self.valid_data, status_code=201, ) mock_get_limit.assert_called_once_with(self.organization.id) detector = Detector.objects.get(id=response.data["id"]) assert detector.name == "Test Detector" @with_feature("organizations:workflow-engine-metric-detector-limit") @mock.patch("sentry.quotas.backend.get_metric_detector_limit") def test_metric_detector_limit_only_applies_to_metric_detectors( self, mock_get_limit: mock.MagicMock ) -> None: # Set limit to 1 metric detector mock_get_limit.return_value = 1 # Create a not-metric detector self.create_detector( project=self.project, name="Error Detector", type=ErrorGroupType.slug, status=ObjectStatus.ACTIVE, ) # Create 1 metric detector, it should succeed response = self.get_success_response( self.organization.slug, **self.valid_data, status_code=201, ) detector = Detector.objects.get(id=response.data["id"]) assert detector.name == "Test Detector" # Create another metric detector, it should fail response = self.get_error_response( self.organization.slug, **self.valid_data, status_code=400, ) assert response.status_code == 400 # Create another not-metric detector, it should succeed with self.tasks(): response = self.get_success_response( self.organization.slug, projectId=self.project.id, name="Error Detector", type=ErrorGroupType.slug, status_code=201, ) detector = Detector.objects.get(id=response.data["id"]) assert detector.type == ErrorGroupType.slug @region_silo_test @with_feature("organizations:incidents")
OrganizationDetectorIndexPostTest
python
pymupdf__PyMuPDF
wdev.py
{ "start": 194, "end": 8403 }
class ____: r''' Windows only. Finds locations of Visual Studio command-line tools. Assumes VS2019-style paths. Members and example values:: .year: 2019 .grade: Community .version: 14.28.29910 .directory: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community .vcvars: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat .cl: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\bin\Hostx64\x64\cl.exe .link: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.28.29910\bin\Hostx64\x64\link.exe .csc: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Roslyn\csc.exe .msbuild: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\MSBuild.exe .devenv: C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\devenv.com `.csc` is C# compiler; will be None if not found. ''' def __init__( self, *, year=None, grade=None, version=None, cpu=None, directory=None, verbose=False, ): ''' Args: year: None or, for example, `2019`. If None we use environment variable WDEV_VS_YEAR if set. grade: None or, for example, one of: * `Community` * `Professional` * `Enterprise` If None we use environment variable WDEV_VS_GRADE if set. version: None or, for example: `14.28.29910`. If None we use environment variable WDEV_VS_VERSION if set. cpu: None or a `WindowsCpu` instance. directory: Ignore year, grade, version and cpu and use this directory directly. verbose: . ''' if year is not None: year = str(year) # Allow specification as a number. def default(value, name): if value is None: name2 = f'WDEV_VS_{name.upper()}' value = os.environ.get(name2) if value is not None: _log(f'Setting {name} from environment variable {name2}: {value!r}') return value try: year = default(year, 'year') grade = default(grade, 'grade') version = default(version, 'version') if not cpu: cpu = WindowsCpu() if not directory: # Find `directory`. # pattern = _vs_pattern(year, grade) directories = glob.glob( pattern) if verbose: _log( f'Matches for: {pattern=}') _log( f'{directories=}') assert directories, f'No match found for {pattern=}.' directories.sort() directory = directories[-1] # Find `devenv`. # devenv = f'{directory}\\Common7\\IDE\\devenv.com' assert os.path.isfile( devenv), f'Does not exist: {devenv}' # Extract `year` and `grade` from `directory`. # # We use r'...' for regex strings because an extra level of escaping is # required for backslashes. # regex = rf'^C:\\Program Files.*\\Microsoft Visual Studio\\([^\\]+)\\([^\\]+)' m = re.match( regex, directory) assert m, f'No match: {regex=} {directory=}' year2 = m.group(1) grade2 = m.group(2) if year: assert year2 == year else: year = year2 if grade: assert grade2 == grade else: grade = grade2 # Find vcvars.bat. # vcvars = f'{directory}\\VC\\Auxiliary\\Build\\vcvars{cpu.bits}.bat' assert os.path.isfile( vcvars), f'No match for: {vcvars}' # Find cl.exe. # cl_pattern = f'{directory}\\VC\\Tools\\MSVC\\{version if version else "*"}\\bin\\Host{cpu.windows_name}\\{cpu.windows_name}\\cl.exe' cl_s = glob.glob( cl_pattern) assert cl_s, f'No match for: {cl_pattern}' cl_s.sort() cl = cl_s[ -1] # Extract `version` from cl.exe's path. # m = re.search( rf'\\VC\\Tools\\MSVC\\([^\\]+)\\bin\\Host{cpu.windows_name}\\{cpu.windows_name}\\cl.exe$', cl) assert m version2 = m.group(1) if version: assert version2 == version else: version = version2 assert version # Find link.exe. # link_pattern = f'{directory}\\VC\\Tools\\MSVC\\{version}\\bin\\Host{cpu.windows_name}\\{cpu.windows_name}\\link.exe' link_s = glob.glob( link_pattern) assert link_s, f'No match for: {link_pattern}' link_s.sort() link = link_s[ -1] # Find csc.exe. # csc = None for dirpath, dirnames, filenames in os.walk(directory): for filename in filenames: if filename == 'csc.exe': csc = os.path.join(dirpath, filename) #_log(f'{csc=}') #break # Find MSBuild.exe. # msbuild = None for dirpath, dirnames, filenames in os.walk(directory): for filename in filenames: if filename == 'MSBuild.exe': msbuild = os.path.join(dirpath, filename) #_log(f'{csc=}') #break self.cl = cl self.devenv = devenv self.directory = directory self.grade = grade self.link = link self.csc = csc self.msbuild = msbuild self.vcvars = vcvars self.version = version self.year = year self.cpu = cpu except Exception as e: raise Exception( f'Unable to find Visual Studio {year=} {grade=} {version=} {cpu=} {directory=}') from e def description_ml( self, indent=''): ''' Return multiline description of `self`. ''' ret = textwrap.dedent(f''' year: {self.year} grade: {self.grade} version: {self.version} directory: {self.directory} vcvars: {self.vcvars} cl: {self.cl} link: {self.link} csc: {self.csc} msbuild: {self.msbuild} devenv: {self.devenv} cpu: {self.cpu} ''') return textwrap.indent( ret, indent) def __repr__( self): items = list() for name in ( 'year', 'grade', 'version', 'directory', 'vcvars', 'cl', 'link', 'csc', 'msbuild', 'devenv', 'cpu', ): items.append(f'{name}={getattr(self, name)!r}') return ' '.join(items) def _vs_pattern(year=None, grade=None): return f'C:\\Program Files*\\Microsoft Visual Studio\\{year if year else "2*"}\\{grade if grade else "*"}' def windows_vs_multiple(year=None, grade=None, verbose=0): ''' Returns list of WindowsVS instances. ''' ret = list() directories = glob.glob(_vs_pattern(year, grade)) for directory in directories: vs = WindowsVS(directory=directory) if verbose: _log(vs.description_ml()) ret.append(vs) return ret
WindowsVS
python
getsentry__sentry
src/sentry/replays/models.py
{ "start": 1470, "end": 2739 }
class ____(Model): __relocation_scope__ = RelocationScope.Excluded project_id = BoundedBigIntegerField() replay_id = models.CharField(max_length=32, db_index=True) file_id = BoundedBigIntegerField(db_index=True) segment_id = BoundedIntegerField(db_column="sequence_id") date_added = models.DateTimeField(default=timezone.now, db_index=True) size = BoundedPositiveIntegerField(null=True) class Meta: app_label = "replays" db_table = "replays_replayrecordingsegment" unique_together = ( ("project_id", "replay_id", "file_id"), ("project_id", "replay_id", "segment_id"), ) __repr__ = sane_repr("replay_id", "segment_id", "file_id") def delete(self, *args, **kwargs): from sentry.models.files.file import File try: file = File.objects.get(id=self.file_id) except ObjectDoesNotExist: # It's possible that the File itself was deleted # before we were deleted when the object is in memory # This seems to be a case that happens during deletion # code. pass else: file.delete() rv = super().delete(*args, **kwargs) return rv
ReplayRecordingSegment
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vector_index.py
{ "start": 7589, "end": 7792 }
class ____(_QuantizerConfigCreate): cache: Optional[bool] bits: Optional[int] rescoreLimit: Optional[int] @staticmethod def quantizer_name() -> str: return "rq"
_RQConfigCreate
python
ray-project__ray
python/ray/serve/tests/test_cli_3.py
{ "start": 2096, "end": 2480 }
class ____: def __init__(self, h: DeploymentHandle): self._h = h async def __call__(self): return await self._h.remote() TestBuildFNode = global_f.bind() TestBuildDagNode = NoArgDriver.bind(TestBuildFNode) TestApp1Node = global_f.options(name="app1").bind() TestApp2Node = NoArgDriver.options(name="app2").bind(global_f.bind()) @serve.deployment
NoArgDriver
python
tensorflow__tensorflow
tensorflow/python/framework/ops.py
{ "start": 7032, "end": 9346 }
class ____(contextlib.AbstractContextManager[None]): def __init__(self, *args, **kwargs) -> None: pass def __enter__(self) -> None: pass def __exit__(self, type_arg, value_arg, traceback_arg) -> bool: return False # False values do not suppress exceptions def _as_graph_element(obj): """Convert `obj` to a graph element if possible, otherwise return `None`. Args: obj: Object to convert. Returns: The result of `obj._as_graph_element()` if that method is available; otherwise `None`. """ conv_fn = getattr(obj, "_as_graph_element", None) if conv_fn and callable(conv_fn): return conv_fn() return None # Deprecated - legacy purposes only. def is_dense_tensor_like(t) -> bool: return isinstance(t, core_tf_types.Tensor) def uid() -> int: """A unique (within this program execution) integer.""" return pywrap_tfe.TFE_Py_UID() def numpy_text(tensor, is_repr=False) -> str: """Human readable representation of a tensor's numpy value.""" if tensor.dtype.is_numpy_compatible: # pylint: disable=protected-access tensor_numpy = tensor._numpy() if is_repr: if np.isscalar(tensor_numpy) and not isinstance(tensor_numpy, bytes): # .item() converts the numpy scalars to python items. text = repr(tensor_numpy.item()) else: text = repr(tensor_numpy) else: text = str(tensor_numpy) # pylint: enable=protected-access else: text = "<unprintable>" if "\n" in text: text = "\n" + text return text def value_text(tensor, is_repr=False) -> AnyStr: """Either the NumPy value or a custom TensorFlow formatting of `tensor`. Custom formatting is used for custom device tensors, e.g. parallel tensors with multiple components on different devices. Args: tensor: The tensor to format. is_repr: Controls the style/verbosity of formatting. Returns: The formatted tensor. """ # pylint: disable=protected-access # friend access if tensor._prefer_custom_summarizer(): text = tensor._summarize_value() # pylint: enable=protected-access if is_repr: text = "value=" + text else: text = numpy_text(tensor, is_repr=is_repr) if is_repr: text = "numpy=" + text return text @tf_export("__internal__.SymbolicTensor")
NullContextmanager
python
tornadoweb__tornado
tornado/template.py
{ "start": 21047, "end": 21795 }
class ____(_Node): def __init__(self, name: str, reader: "_TemplateReader", line: int) -> None: self.name = name self.template_name = reader.name self.line = line def find_named_blocks( self, loader: Optional[BaseLoader], named_blocks: Dict[str, _NamedBlock] ) -> None: assert loader is not None included = loader.load(self.name, self.template_name) included.file.find_named_blocks(loader, named_blocks) def generate(self, writer: "_CodeWriter") -> None: assert writer.loader is not None included = writer.loader.load(self.name, self.template_name) with writer.include(included, self.line): included.file.body.generate(writer)
_IncludeBlock
python
numba__numba
numba/tests/test_cfunc.py
{ "start": 9894, "end": 13079 }
class ____(TestCase): c_source = """ typedef struct _big_struct { int i1; float f2; double d3; float af4[9]; } big_struct; typedef struct _error { int bits:4; } error; typedef double (*myfunc)(big_struct*, size_t); """ def get_ffi(self, src=c_source): from cffi import FFI ffi = FFI() ffi.cdef(src) return ffi def test_type_parsing(self): ffi = self.get_ffi() # Check struct typedef big_struct = ffi.typeof('big_struct') nbtype = cffi_support.map_type(big_struct, use_record_dtype=True) self.assertIsInstance(nbtype, types.Record) self.assertEqual(len(nbtype), 4) self.assertEqual(nbtype.typeof('i1'), types.int32) self.assertEqual(nbtype.typeof('f2'), types.float32) self.assertEqual(nbtype.typeof('d3'), types.float64) self.assertEqual( nbtype.typeof('af4'), types.NestedArray(dtype=types.float32, shape=(9,)), ) # Check function typedef myfunc = ffi.typeof('myfunc') sig = cffi_support.map_type(myfunc, use_record_dtype=True) self.assertIsInstance(sig, typing.Signature) self.assertEqual(sig.args[0], types.CPointer(nbtype)) self.assertEqual(sig.args[1], types.uintp) self.assertEqual(sig.return_type, types.float64) def test_cfunc_callback(self): ffi = self.get_ffi() big_struct = ffi.typeof('big_struct') nb_big_struct = cffi_support.map_type(big_struct, use_record_dtype=True) sig = cffi_support.map_type(ffi.typeof('myfunc'), use_record_dtype=True) @njit def calc(base): tmp = 0 for i in range(base.size): elem = base[i] tmp += elem.i1 * elem.f2 / elem.d3 tmp += base[i].af4.sum() return tmp @cfunc(sig) def foo(ptr, n): base = carray(ptr, n) return calc(base) # Make data mydata = ffi.new('big_struct[3]') ptr = ffi.cast('big_struct*', mydata) for i in range(3): ptr[i].i1 = i * 123 ptr[i].f2 = i * 213 ptr[i].d3 = (1 + i) * 213 for j in range(9): ptr[i].af4[j] = i * 10 + j # Address of my data addr = int(ffi.cast('size_t', ptr)) got = foo.ctypes(addr, 3) # Make numpy array from the cffi buffer array = np.ndarray( buffer=ffi.buffer(mydata), dtype=numpy_support.as_dtype(nb_big_struct), shape=3, ) expect = calc(array) self.assertEqual(got, expect) def test_unsupport_bitsize(self): ffi = self.get_ffi() with self.assertRaises(ValueError) as raises: cffi_support.map_type( ffi.typeof('error'), use_record_dtype=True, ) # When bitsize is provided, bitshift defaults to 0. self.assertEqual( "field 'bits' has bitshift, this is not supported", str(raises.exception) ) if __name__ == "__main__": unittest.main()
TestCffiStruct
python
getsentry__sentry
tests/sentry/api/endpoints/test_organization_spans_fields.py
{ "start": 5124, "end": 27185 }
class ____(BaseSpansTestCase, APITestCase): view = "sentry-api-0-organization-spans-fields-values" def setUp(self) -> None: super().setUp() self.login_as(user=self.user) def do_request(self, key: str, query=None, features=None, **kwargs): if features is None: features = ["organizations:performance-trace-explorer"] if query is None: query = {} query["dataset"] = "spans" query["type"] = "string" with self.feature(features): return self.client.get( reverse( self.view, kwargs={ "organization_id_or_slug": self.organization.slug, "key": key, }, ), query, format="json", **kwargs, ) def test_no_feature(self) -> None: response = self.do_request("tag", features=[]) assert response.status_code == 404, response.data def test_no_project(self) -> None: response = self.do_request("tag") assert response.status_code == 200, response.data assert response.data == [] def test_tags_keys(self) -> None: timestamp = before_now(days=0, minutes=10).replace(microsecond=0) for tag in ["foo", "bar", "baz"]: self.store_segment( self.project.id, uuid4().hex, uuid4().hex, span_id=uuid4().hex[:16], organization_id=self.organization.id, parent_span_id=None, timestamp=timestamp, transaction="foo", duration=100, exclusive_time=100, tags={"tag": tag}, is_eap=True, ) response = self.do_request("tag") assert response.status_code == 200, response.data assert response.data == [ { "count": mock.ANY, "key": "tag", "value": "bar", "name": "bar", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": "tag", "value": "baz", "name": "baz", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": "tag", "value": "foo", "name": "foo", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, ] def test_transaction_keys_autocomplete(self) -> None: timestamp = before_now(days=0, minutes=10).replace(microsecond=0) for transaction in ["foo", "*bar", "*baz"]: self.store_segment( self.project.id, uuid4().hex, uuid4().hex, span_id=uuid4().hex[:16], organization_id=self.organization.id, parent_span_id=None, timestamp=timestamp, transaction=transaction, duration=100, exclusive_time=100, is_eap=True, ) key = "transaction" response = self.do_request(key) assert response.status_code == 200, response.data assert response.data == [ { "count": mock.ANY, "key": key, "value": "*bar", "name": "*bar", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "*baz", "name": "*baz", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "foo", "name": "foo", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, ] def test_transaction_keys_autocomplete_substring(self) -> None: timestamp = before_now(days=0, minutes=10).replace(microsecond=0) for transaction in ["foo", "*bar", "*baz"]: self.store_segment( self.project.id, uuid4().hex, uuid4().hex, span_id=uuid4().hex[:16], organization_id=self.organization.id, parent_span_id=None, timestamp=timestamp, transaction=transaction, duration=100, exclusive_time=100, is_eap=True, ) key = "transaction" response = self.do_request(key, query={"query": "b"}) assert response.status_code == 200, response.data assert response.data == [ { "count": mock.ANY, "key": key, "value": "*bar", "name": "*bar", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "*baz", "name": "*baz", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, ] def test_transaction_keys_autocomplete_substring_with_asterisk(self) -> None: timestamp = before_now(days=0, minutes=10).replace(microsecond=0) for transaction in ["foo", "*bar", "*baz"]: self.store_segment( self.project.id, uuid4().hex, uuid4().hex, span_id=uuid4().hex[:16], organization_id=self.organization.id, parent_span_id=None, timestamp=timestamp, transaction=transaction, duration=100, exclusive_time=100, is_eap=True, ) key = "transaction" response = self.do_request(key, query={"query": r"\*b"}) assert response.status_code == 200, response.data assert response.data == [ { "count": mock.ANY, "key": key, "value": "*bar", "name": "*bar", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "*baz", "name": "*baz", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, ] def test_tags_keys_autocomplete(self) -> None: timestamp = before_now(days=0, minutes=10).replace(microsecond=0) for tag in ["foo", "*bar", "*baz"]: self.store_segment( self.project.id, uuid4().hex, uuid4().hex, span_id=uuid4().hex[:16], organization_id=self.organization.id, parent_span_id=None, timestamp=timestamp, transaction="transaction", duration=100, exclusive_time=100, tags={"tag": tag}, is_eap=True, ) key = "tag" response = self.do_request(key) assert response.status_code == 200, response.data assert response.data == [ { "count": mock.ANY, "key": key, "value": "*bar", "name": "*bar", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "*baz", "name": "*baz", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "foo", "name": "foo", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, ] def test_tags_keys_autocomplete_substring(self) -> None: timestamp = before_now(days=0, minutes=10).replace(microsecond=0) for tag in ["foo", "*bar", "*baz"]: self.store_segment( self.project.id, uuid4().hex, uuid4().hex, span_id=uuid4().hex[:16], organization_id=self.organization.id, parent_span_id=None, timestamp=timestamp, transaction="transaction", duration=100, exclusive_time=100, tags={"tag": tag}, is_eap=True, ) key = "tag" response = self.do_request(key, query={"query": "b"}) assert response.status_code == 200, response.data assert response.data == [ { "count": mock.ANY, "key": key, "value": "*bar", "name": "*bar", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "*baz", "name": "*baz", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, ] def test_tags_keys_autocomplete_substring_with_asterisks(self) -> None: timestamp = before_now(days=0, minutes=10).replace(microsecond=0) for tag in ["foo", "*bar", "*baz"]: self.store_segment( self.project.id, uuid4().hex, uuid4().hex, span_id=uuid4().hex[:16], organization_id=self.organization.id, parent_span_id=None, timestamp=timestamp, transaction="transaction", duration=100, exclusive_time=100, tags={"tag": tag}, is_eap=True, ) key = "tag" response = self.do_request(key, query={"query": r"\*b"}) assert response.status_code == 200, response.data assert response.data == [ { "count": mock.ANY, "key": key, "value": "*bar", "name": "*bar", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "*baz", "name": "*baz", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, ] def test_tags_keys_autocomplete_noop(self) -> None: timestamp = before_now(days=0, minutes=10).replace(microsecond=0) for tag in ["foo", "bar", "baz"]: self.store_segment( self.project.id, uuid4().hex, uuid4().hex, span_id=uuid4().hex[:16], organization_id=self.organization.id, parent_span_id=None, timestamp=timestamp, transaction=tag, duration=100, exclusive_time=100, tags={"tag": tag}, is_eap=True, ) for key in [ "span.duration", "span.self_time", "timestamp", "id", "span_id", "parent_span", "parent_span_id", "trace", "trace_id", "transaction.id", "transaction_id", "segment.id", "segment_id", "profile.id", "profile_id", "replay.id", "replay_id", ]: response = self.do_request(key) assert response.status_code == 200, response.data assert response.data == [], key def test_tags_keys_autocomplete_project(self) -> None: base_id = 9223372036854775000 self.create_project(id=base_id + 100, name="foo") self.create_project(id=base_id + 299, name="bar") self.create_project(id=base_id + 399, name="baz") features = [ "organizations:performance-trace-explorer", ] for key in ["project", "project.name"]: response = self.do_request(key, features=features) assert response.status_code == 200, response.data assert sorted(response.data, key=lambda v: v["value"]) == [ { "count": mock.ANY, "key": key, "value": "bar", "name": "bar", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "baz", "name": "baz", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "foo", "name": "foo", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, ] response = self.do_request(key, query={"query": "ba"}, features=features) assert response.status_code == 200, response.data assert sorted(response.data, key=lambda v: v["value"]) == [ { "count": mock.ANY, "key": key, "value": "bar", "name": "bar", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "baz", "name": "baz", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, ] key = "project.id" response = self.do_request(key, features=features) assert response.status_code == 200, response.data assert sorted(response.data, key=lambda v: v["value"]) == [ { "count": mock.ANY, "key": key, "value": "9223372036854775100", "name": "9223372036854775100", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "9223372036854775299", "name": "9223372036854775299", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "9223372036854775399", "name": "9223372036854775399", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, ] response = self.do_request(key, query={"query": "99"}, features=features) assert response.status_code == 200, response.data assert sorted(response.data, key=lambda v: v["value"]) == [ { "count": mock.ANY, "key": key, "value": "9223372036854775299", "name": "9223372036854775299", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "9223372036854775399", "name": "9223372036854775399", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, ] def test_tags_keys_autocomplete_span_status(self) -> None: timestamp = before_now(days=0, minutes=10).replace(microsecond=0) for status in ["ok", "internal_error", "invalid_argument"]: self.store_segment( self.project.id, uuid4().hex, uuid4().hex, span_id=uuid4().hex[:16], organization_id=self.organization.id, parent_span_id=None, timestamp=timestamp, transaction="foo", status=status, is_eap=True, ) response = self.do_request("span.status") assert response.status_code == 200, response.data assert response.data == [ { "count": mock.ANY, "key": "span.status", "value": "internal_error", "name": "internal_error", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": "span.status", "value": "invalid_argument", "name": "invalid_argument", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": "span.status", "value": "ok", "name": "ok", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, ] response = self.do_request("span.status", query={"query": "in"}) assert response.status_code == 200, response.data assert response.data == [ { "count": mock.ANY, "key": "span.status", "value": "internal_error", "name": "internal_error", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": "span.status", "value": "invalid_argument", "name": "invalid_argument", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, ] def test_measurements_autocomplete(self) -> None: keys = [ "measurements.app_start_cold", "measurements.app_start_warm", "measurements.frames_frozen", "measurements.frames_frozen_rate", "measurements.frames_slow", "measurements.frames_slow_rate", "measurements.frames_total", "measurements.time_to_initial_display", "measurements.time_to_full_display", "measurements.stall_count", "measurements.stall_percentage", "measurements.stall_stall_longest_time", "measurements.stall_stall_total_time", "measurements.cls", "measurements.fcp", "measurements.fid", "measurements.fp", "measurements.inp", "measurements.lcp", "measurements.ttfb", "measurements.ttfb.requesttime", "measurements.score.cls", "measurements.score.fcp", "measurements.score.fid", "measurements.score.inp", "measurements.score.lcp", "measurements.score.ttfb", "measurements.score.total", "measurements.score.weight.cls", "measurements.score.weight.fcp", "measurements.score.weight.fid", "measurements.score.weight.inp", "measurements.score.weight.lcp", "measurements.score.weight.ttfb", "measurements.cache.item_size", "measurements.messaging.message.body.size", "measurements.messaging.message.receive.latency", "measurements.messaging.message.retry.count", "measurements.http.response_content_length", ] self.project for key in keys: response = self.do_request(key) assert response.status_code == 200, response.data assert response.data == [] @mock.patch( "sentry.api.endpoints.organization_spans_fields.EAPSpanFieldValuesAutocompletionExecutor.execute", side_effect=InvalidSearchQuery, ) def test_invalid_query(self, mock_executor: mock.MagicMock) -> None: timestamp = before_now(days=0, minutes=10).replace(microsecond=0) self.store_segment( self.project.id, uuid4().hex, uuid4().hex, span_id=uuid4().hex[:16], organization_id=self.organization.id, parent_span_id=None, timestamp=timestamp, transaction="foo", duration=100, exclusive_time=100, tags={"tag": "foo"}, is_eap=True, ) response = self.do_request("tag") assert response.status_code == 400, response.data def test_boolean_autocomplete(self) -> None: keys = ["is_transaction"] self.project for key in keys: response = self.do_request(key) assert response.status_code == 200, response.data assert response.data == [ { "count": mock.ANY, "key": key, "value": "false", "name": "false", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, { "count": mock.ANY, "key": key, "value": "true", "name": "true", "firstSeen": mock.ANY, "lastSeen": mock.ANY, }, ]
OrganizationSpansTagKeyValuesEndpointTest
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 8207, "end": 8420 }
class ____(sgqlc.types.Enum): """ See source code for more info. """ __schema__ = graphql_schema __choices__ = ("CREATED_AT", "CUSTOMER_NAME", "HOST_NAME")
EnterpriseServerInstallationOrderField
python
Netflix__metaflow
metaflow/plugins/aws/batch/batch.py
{ "start": 1227, "end": 20395 }
class ____(object): def __init__(self, metadata, environment, flow_datastore=None): self.metadata = metadata self.environment = environment self.flow_datastore = flow_datastore self._client = BatchClient() atexit.register(lambda: self.job.kill() if hasattr(self, "job") else None) def _command( self, environment, code_package_metadata, code_package_url, step_name, step_cmds, task_spec, offload_command_to_s3, ): mflog_expr = export_mflog_env_vars( datastore_type="s3", stdout_path=STDOUT_PATH, stderr_path=STDERR_PATH, **task_spec ) init_cmds = environment.get_package_commands( code_package_url, "s3", code_package_metadata ) init_expr = " && ".join(init_cmds) step_expr = bash_capture_logs( " && ".join(environment.bootstrap_commands(step_name, "s3") + step_cmds) ) # construct an entry point that # 1) initializes the mflog environment (mflog_expr) # 2) bootstraps a metaflow environment (init_expr) # 3) executes a task (step_expr) # the `true` command is to make sure that the generated command # plays well with docker containers which have entrypoint set as # eval $@ cmd_str = "true && mkdir -p %s && %s && %s && %s; " % ( LOGS_DIR, mflog_expr, init_expr, step_expr, ) # after the task has finished, we save its exit code (fail/success) # and persist the final logs. The whole entrypoint should exit # with the exit code (c) of the task. # # Note that if step_expr OOMs, this tail expression is never executed. # We lose the last logs in this scenario (although they are visible # still through AWS CloudWatch console). cmd_str += "c=$?; %s; exit $c" % BASH_SAVE_LOGS command = shlex.split('bash -c "%s"' % cmd_str) if not offload_command_to_s3: return command # If S3 upload is enabled, we need to modify the command after it's created if self.flow_datastore is None: raise MetaflowException( "Can not offload Batch command to S3 without a datastore configured." ) from metaflow.plugins.aws.aws_utils import parse_s3_full_path # Get the command that was created # Upload the command to S3 during deployment try: command_bytes = cmd_str.encode("utf-8") result_paths = self.flow_datastore.save_data([command_bytes], len_hint=1) s3_path, _key = result_paths[0] bucket, s3_object = parse_s3_full_path(s3_path) download_script = "{python} -c '{script}'".format( python=self.environment._python(), script='import boto3, os; ep=os.getenv(\\"METAFLOW_S3_ENDPOINT_URL\\"); boto3.client(\\"s3\\", **({\\"endpoint_url\\":ep} if ep else {})).download_file(\\"%s\\", \\"%s\\", \\"/tmp/step_command.sh\\")' % (bucket, s3_object), ) download_cmd = ( f"{self.environment._get_install_dependencies_cmd('s3')} && " # required for boto3 due to the original dependencies cmd getting packaged, and not being downloaded in time. f"{download_script} && " f"chmod +x /tmp/step_command.sh && " f"bash /tmp/step_command.sh" ) new_cmd = shlex.split('bash -c "%s"' % download_cmd) return new_cmd except Exception as e: print(f"Warning: Failed to upload command to S3: {e}") print("Falling back to inline command") def _search_jobs(self, flow_name, run_id, user): if user is None: regex = "-{flow_name}-".format(flow_name=flow_name) else: regex = "{user}-{flow_name}-".format(user=user, flow_name=flow_name) jobs = [] for job in self._client.unfinished_jobs(): if regex in job["jobName"]: jobs.append(job["jobId"]) if run_id is not None: run_id = run_id[run_id.startswith("sfn-") and len("sfn-") :] for job in self._client.describe_jobs(jobs): parameters = job["parameters"] match = ( (user is None or parameters["metaflow.user"] == user) and (parameters["metaflow.flow_name"] == flow_name) and (run_id is None or parameters["metaflow.run_id"] == run_id) ) if match: yield job def _job_name(self, user, flow_name, run_id, step_name, task_id, retry_count): return "{user}-{flow_name}-{run_id}-{step_name}-{task_id}-{retry_count}".format( user=user, flow_name=flow_name, run_id=str(run_id) if run_id is not None else "", step_name=step_name, task_id=str(task_id) if task_id is not None else "", retry_count=str(retry_count) if retry_count is not None else "", ) def list_jobs(self, flow_name, run_id, user, echo): jobs = self._search_jobs(flow_name, run_id, user) found = False for job in jobs: found = True echo( "{name} [{id}] ({status})".format( name=job["jobName"], id=job["jobId"], status=job["status"] ) ) if not found: echo("No running AWS Batch jobs found.") def kill_jobs(self, flow_name, run_id, user, echo): jobs = self._search_jobs(flow_name, run_id, user) found = False for job in jobs: found = True try: self._client.attach_job(job["jobId"]).kill() echo( "Killing AWS Batch job: {name} [{id}] ({status})".format( name=job["jobName"], id=job["jobId"], status=job["status"], ) ) except Exception as e: echo( "Failed to terminate AWS Batch job %s [%s]" % (job["jobId"], repr(e)) ) if not found: echo("No running AWS Batch jobs found.") def create_job( self, step_name, step_cli, task_spec, code_package_metadata, code_package_sha, code_package_url, code_package_ds, image, queue, iam_role=None, execution_role=None, cpu=None, gpu=None, memory=None, run_time_limit=None, shared_memory=None, max_swap=None, swappiness=None, inferentia=None, efa=None, env={}, attrs={}, host_volumes=None, efs_volumes=None, use_tmpfs=None, aws_batch_tags=None, tmpfs_tempdir=None, tmpfs_size=None, tmpfs_path=None, num_parallel=0, ephemeral_storage=None, log_driver=None, log_options=None, offload_command_to_s3=False, ): job_name = self._job_name( attrs.get("metaflow.user"), attrs.get("metaflow.flow_name"), attrs.get("metaflow.run_id"), attrs.get("metaflow.step_name"), attrs.get("metaflow.task_id"), attrs.get("metaflow.retry_count"), ) job = ( self._client.job() .job_name(job_name) .job_queue(queue) .command( self._command( self.environment, code_package_metadata, code_package_url, step_name, [step_cli], task_spec, offload_command_to_s3, ) ) .image(image) .iam_role(iam_role) .execution_role(execution_role) .cpu(cpu) .gpu(gpu) .memory(memory) .shared_memory(shared_memory) .max_swap(max_swap) .swappiness(swappiness) .inferentia(inferentia) .efa(efa) .timeout_in_secs(run_time_limit) .job_def( image, iam_role, queue, execution_role, shared_memory, max_swap, swappiness, inferentia, efa, memory=memory, host_volumes=host_volumes, efs_volumes=efs_volumes, use_tmpfs=use_tmpfs, tmpfs_tempdir=tmpfs_tempdir, tmpfs_size=tmpfs_size, tmpfs_path=tmpfs_path, num_parallel=num_parallel, ephemeral_storage=ephemeral_storage, log_driver=log_driver, log_options=log_options, ) .task_id(attrs.get("metaflow.task_id")) .environment_variable("AWS_DEFAULT_REGION", self._client.region()) .environment_variable("METAFLOW_CODE_METADATA", code_package_metadata) .environment_variable("METAFLOW_CODE_SHA", code_package_sha) .environment_variable("METAFLOW_CODE_URL", code_package_url) .environment_variable("METAFLOW_CODE_DS", code_package_ds) .environment_variable("METAFLOW_USER", attrs["metaflow.user"]) .environment_variable("METAFLOW_SERVICE_URL", SERVICE_INTERNAL_URL) .environment_variable( "METAFLOW_SERVICE_HEADERS", json.dumps(SERVICE_HEADERS) ) .environment_variable("METAFLOW_DATASTORE_SYSROOT_S3", DATASTORE_SYSROOT_S3) .environment_variable("METAFLOW_DATATOOLS_S3ROOT", DATATOOLS_S3ROOT) .environment_variable("METAFLOW_DEFAULT_DATASTORE", "s3") .environment_variable("METAFLOW_DEFAULT_METADATA", DEFAULT_METADATA) .environment_variable("METAFLOW_CARD_S3ROOT", CARD_S3ROOT) .environment_variable("METAFLOW_OTEL_ENDPOINT", OTEL_ENDPOINT) .environment_variable("METAFLOW_RUNTIME_ENVIRONMENT", "aws-batch") ) # Temporary passing of *some* environment variables. Do not rely on this # mechanism as it will be removed in the near future for k, v in config_values(): if k.startswith("METAFLOW_CONDA_") or k.startswith("METAFLOW_DEBUG_"): job.environment_variable(k, v) if DEFAULT_SECRETS_BACKEND_TYPE is not None: job.environment_variable( "METAFLOW_DEFAULT_SECRETS_BACKEND_TYPE", DEFAULT_SECRETS_BACKEND_TYPE ) if AWS_SECRETS_MANAGER_DEFAULT_REGION is not None: job.environment_variable( "METAFLOW_AWS_SECRETS_MANAGER_DEFAULT_REGION", AWS_SECRETS_MANAGER_DEFAULT_REGION, ) tmpfs_enabled = use_tmpfs or (tmpfs_size and not use_tmpfs) if tmpfs_enabled and tmpfs_tempdir: job.environment_variable("METAFLOW_TEMPDIR", tmpfs_path) if S3_SERVER_SIDE_ENCRYPTION is not None: job.environment_variable( "METAFLOW_S3_SERVER_SIDE_ENCRYPTION", S3_SERVER_SIDE_ENCRYPTION ) # Skip setting METAFLOW_DATASTORE_SYSROOT_LOCAL because metadata sync between the local user # instance and the remote AWS Batch instance assumes metadata is stored in DATASTORE_LOCAL_DIR # on the remote AWS Batch instance; this happens when METAFLOW_DATASTORE_SYSROOT_LOCAL # is NOT set (see get_datastore_root_from_config in datastore/local.py). # add METAFLOW_S3_ENDPOINT_URL if S3_ENDPOINT_URL is not None: job.environment_variable("METAFLOW_S3_ENDPOINT_URL", S3_ENDPOINT_URL) for name, value in env.items(): job.environment_variable(name, value) if attrs: for key, value in attrs.items(): job.parameter(key, value) # Tags for AWS Batch job (for say cost attribution) if BATCH_EMIT_TAGS: job.tag("app", "metaflow") for key in [ "metaflow.flow_name", "metaflow.run_id", "metaflow.step_name", "metaflow.run_id.$", "metaflow.production_token", ]: if key in attrs: job.tag(key, attrs.get(key)) # As some values can be affected by users, sanitize them so they adhere to AWS tagging restrictions. for key in [ "metaflow.version", "metaflow.user", "metaflow.owner", ]: if key in attrs: k, v = sanitize_batch_tag(key, attrs.get(key)) job.tag(k, v) if aws_batch_tags is not None: for key, value in aws_batch_tags.items(): job.tag(key, value) return job def launch_job( self, step_name, step_cli, task_spec, code_package_metadata, code_package_sha, code_package_url, code_package_ds, image, queue, iam_role=None, execution_role=None, # for FARGATE compatibility cpu=None, gpu=None, memory=None, run_time_limit=None, shared_memory=None, max_swap=None, swappiness=None, inferentia=None, efa=None, host_volumes=None, efs_volumes=None, use_tmpfs=None, aws_batch_tags=None, tmpfs_tempdir=None, tmpfs_size=None, tmpfs_path=None, num_parallel=0, env={}, attrs={}, ephemeral_storage=None, log_driver=None, log_options=None, ): if queue is None: queue = next(self._client.active_job_queues(), None) if queue is None: raise BatchException( "Unable to launch AWS Batch job. No job queue " " specified and no valid & enabled queue found." ) job = self.create_job( step_name, step_cli, task_spec, code_package_metadata, code_package_sha, code_package_url, code_package_ds, image, queue, iam_role, execution_role, cpu, gpu, memory, run_time_limit, shared_memory, max_swap, swappiness, inferentia, efa, env=env, attrs=attrs, host_volumes=host_volumes, efs_volumes=efs_volumes, use_tmpfs=use_tmpfs, aws_batch_tags=aws_batch_tags, tmpfs_tempdir=tmpfs_tempdir, tmpfs_size=tmpfs_size, tmpfs_path=tmpfs_path, num_parallel=num_parallel, ephemeral_storage=ephemeral_storage, log_driver=log_driver, log_options=log_options, ) self.num_parallel = num_parallel self.job = job.execute() def wait(self, stdout_location, stderr_location, echo=None): def wait_for_launch(job, child_jobs): status = job.status echo( "Task is starting (status %s)..." % status, "stderr", batch_id=job.id, ) t = time.time() while True: if status != job.status or (time.time() - t) > 30: if not child_jobs: child_statuses = "" else: status_keys = set( [child_job.status for child_job in child_jobs] ) status_counts = [ ( status, len( [ child_job.status == status for child_job in child_jobs ] ), ) for status in status_keys ] child_statuses = " (parallel node status: [{}])".format( ", ".join( [ "{}:{}".format(status, num) for (status, num) in sorted(status_counts) ] ) ) status = job.status echo( "Task is starting (status %s)... %s" % (status, child_statuses), "stderr", batch_id=job.id, ) t = time.time() if job.is_running or job.is_done or job.is_crashed: break select.poll().poll(200) prefix = b"[%s] " % util.to_bytes(self.job.id) stdout_tail = S3Tail(stdout_location) stderr_tail = S3Tail(stderr_location) child_jobs = [] if self.num_parallel > 1: for node in range(1, self.num_parallel): child_job = copy.copy(self.job) child_job._id = child_job._id + "#{}".format(node) child_jobs.append(child_job) # 1) Loop until the job has started wait_for_launch(self.job, child_jobs) # 2) Tail logs until the job has finished tail_logs( prefix=prefix, stdout_tail=stdout_tail, stderr_tail=stderr_tail, echo=echo, has_log_updates=lambda: self.job.is_running, ) # In case of hard crashes (OOM), the final save_logs won't happen. # We can fetch the remaining logs from AWS CloudWatch and persist them # to Amazon S3. if self.job.is_crashed: msg = next( msg for msg in [ self.job.reason, self.job.status_reason, "Task crashed.", ] if msg is not None ) raise BatchException( "%s " "This could be a transient error. " "Use @retry to retry." % msg ) else: if self.job.is_running: # Kill the job if it is still running by throwing an exception. raise BatchException("Task failed!") echo( "Task finished with exit code %s." % self.job.status_code, "stderr", batch_id=self.job.id, )
Batch
python
realpython__materials
django-vue-graphql/source_code_final/back_end/blog/admin.py
{ "start": 258, "end": 910 }
class ____(admin.ModelAdmin): model = Post list_display = ( "id", "title", "subtitle", "slug", "publish_date", "published", ) list_filter = ( "published", "publish_date", ) list_editable = ( "title", "subtitle", "slug", "publish_date", "published", ) search_fields = ( "title", "subtitle", "slug", "body", ) prepopulated_fields = { "slug": ( "title", "subtitle", ) } date_hierarchy = "publish_date" save_on_top = True
PostAdmin
python
more-itertools__more-itertools
tests/test_recipes.py
{ "start": 6046, "end": 6376 }
class ____(TestCase): def test_basic(self): iterable = range(2) for func in (mi.pad_none, mi.padnone): with self.subTest(func=func): p = func(iterable) self.assertEqual( [0, 1, None, None], [next(p) for _ in range(4)] )
PadnoneTests
python
getsentry__sentry-python
tests/integrations/grpc/grpc_test_service_pb2_grpc.py
{ "start": 218, "end": 1738 }
class ____(object): """Missing associated documentation comment in .proto file.""" def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.TestServe = channel.unary_unary( '/grpc_test_server.gRPCTestService/TestServe', request_serializer=grpc__test__service__pb2.gRPCTestMessage.SerializeToString, response_deserializer=grpc__test__service__pb2.gRPCTestMessage.FromString, ) self.TestUnaryStream = channel.unary_stream( '/grpc_test_server.gRPCTestService/TestUnaryStream', request_serializer=grpc__test__service__pb2.gRPCTestMessage.SerializeToString, response_deserializer=grpc__test__service__pb2.gRPCTestMessage.FromString, ) self.TestStreamStream = channel.stream_stream( '/grpc_test_server.gRPCTestService/TestStreamStream', request_serializer=grpc__test__service__pb2.gRPCTestMessage.SerializeToString, response_deserializer=grpc__test__service__pb2.gRPCTestMessage.FromString, ) self.TestStreamUnary = channel.stream_unary( '/grpc_test_server.gRPCTestService/TestStreamUnary', request_serializer=grpc__test__service__pb2.gRPCTestMessage.SerializeToString, response_deserializer=grpc__test__service__pb2.gRPCTestMessage.FromString, )
gRPCTestServiceStub
python
huggingface__transformers
src/transformers/models/ernie4_5/modeling_ernie4_5.py
{ "start": 14952, "end": 15508 }
class ____(PreTrainedModel): config: Ernie4_5Config base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["Ernie4_5DecoderLayer"] _skip_keys_device_placement = ["past_key_values"] _supports_flash_attn = True _supports_sdpa = True _supports_flex_attn = True _can_compile_fullgraph = True _supports_attention_backend = True _can_record_outputs = { "hidden_states": Ernie4_5DecoderLayer, "attentions": Ernie4_5Attention, } @auto_docstring
Ernie4_5PreTrainedModel
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_cloud_batch.py
{ "start": 1384, "end": 3576 }
class ____: @mock.patch(CLOUD_BATCH_HOOK_PATH) def test_execute(self, mock): mock.return_value.wait_for_job.return_value = JOB operator = CloudBatchSubmitJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, job=JOB ) completed_job = operator.execute(context=mock.MagicMock()) assert completed_job["name"] == JOB_NAME mock.return_value.submit_batch_job.assert_called_with( job_name=JOB_NAME, job=JOB, region=REGION, project_id=PROJECT_ID ) mock.return_value.wait_for_job.assert_called() @mock.patch(CLOUD_BATCH_HOOK_PATH) def test_execute_deferrable(self, mock): operator = CloudBatchSubmitJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, job=JOB, deferrable=True ) with pytest.raises(expected_exception=TaskDeferred): operator.execute(context=mock.MagicMock()) @mock.patch(CLOUD_BATCH_HOOK_PATH) def test_execute_complete(self, mock): mock.return_value.get_job.return_value = JOB operator = CloudBatchSubmitJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, job=JOB, deferrable=True ) event = {"status": "success", "job_name": JOB_NAME, "message": "test error"} completed_job = operator.execute_complete(context=mock.MagicMock(), event=event) assert completed_job["name"] == JOB_NAME mock.return_value.get_job.assert_called_once_with(job_name=JOB_NAME) @mock.patch(CLOUD_BATCH_HOOK_PATH) def test_execute_complete_exception(self, mock): operator = CloudBatchSubmitJobOperator( task_id=TASK_ID, project_id=PROJECT_ID, region=REGION, job_name=JOB_NAME, job=JOB, deferrable=True ) event = {"status": "error", "job_name": JOB_NAME, "message": "test error"} with pytest.raises( expected_exception=AirflowException, match="Unexpected error in the operation: test error" ): operator.execute_complete(context=mock.MagicMock(), event=event)
TestCloudBatchSubmitJobOperator
python
ray-project__ray
rllib/env/tests/test_multi_agent_env.py
{ "start": 2930, "end": 5306 }
class ____(MultiAgentEnv): """Env for testing when the env terminates (after agent 0 does).""" def __init__(self): super().__init__() self.envs = [MockEnv(3), MockEnv(5)] self.agents = list(range(len(self.envs))) self.terminateds = set() self.truncateds = set() self.last_obs = {} self.last_rew = {} self.last_terminated = {} self.last_truncated = {} self.last_info = {} self.i = 0 self.observation_space = gym.spaces.Discrete(10) self.action_space = gym.spaces.Discrete(2) def reset(self, *, seed=None, options=None): self.terminateds = set() self.truncateds = set() self.last_obs = {} self.last_rew = {} self.last_terminated = {} self.last_truncated = {} self.last_info = {} self.i = 0 for i, a in enumerate(self.envs): self.last_obs[i], self.last_info[i] = a.reset() self.last_rew[i] = 0 self.last_terminated[i] = False self.last_truncated[i] = False obs_dict = {self.i: self.last_obs[self.i]} info_dict = {self.i: self.last_info[self.i]} self.i = (self.i + 1) % len(self.envs) return obs_dict, info_dict def step(self, action_dict): assert len(self.terminateds) != len(self.envs) for i, action in action_dict.items(): ( self.last_obs[i], self.last_rew[i], self.last_terminated[i], self.last_truncated[i], self.last_info[i], ) = self.envs[i].step(action) obs = {self.i: self.last_obs[self.i]} rew = {self.i: self.last_rew[self.i]} terminated = {self.i: self.last_terminated[self.i]} truncated = {self.i: self.last_truncated[self.i]} info = {self.i: self.last_info[self.i]} if terminated[self.i]: rew[self.i] = 0 self.terminateds.add(self.i) if truncated[self.i]: rew[self.i] = 0 self.truncateds.add(self.i) self.i = (self.i + 1) % len(self.envs) terminated["__all__"] = len(self.terminateds) == len(self.envs) - 1 truncated["__all__"] = len(self.truncateds) == len(self.envs) - 1 return obs, rew, terminated, truncated, info
EarlyDoneMultiAgent