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
tensorflow__tensorflow
tensorflow/python/training/saver_test.py
{ "start": 48912, "end": 54248 }
class ____(SaveRestoreShardedTest): _WRITE_VERSION = saver_pb2.SaverDef.V2 def testIterators(self): save_path = os.path.join(self.get_temp_dir(), "sharded_iterators") # Build a graph with 2 parameter nodes on different devices and save. with session.Session( target="", config=config_pb2.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): ds0 = dataset_ops.Dataset.range(10) it0 = dataset_ops.make_initializable_iterator(ds0) get_next0 = it0.get_next() saveable0 = iterator_ops._IteratorSaveable( it0._iterator_resource, name="saveable_it0") with sess.graph.device("/cpu:1"): ds1 = dataset_ops.Dataset.range(20) it1 = dataset_ops.make_initializable_iterator(ds1) get_next1 = it1.get_next() saveable1 = iterator_ops._IteratorSaveable( it1._iterator_resource, name="saveable_it1") saver = saver_module.Saver({ "it0": saveable0, "it1": saveable1 }, write_version=self._WRITE_VERSION, sharded=True) self.evaluate(it0.initializer) self.evaluate(it1.initializer) self.assertEqual(0, self.evaluate(get_next0)) self.assertEqual(1, self.evaluate(get_next0)) self.assertEqual(0, self.evaluate(get_next1)) val = saver.save(sess, save_path) self.assertEqual(save_path, val) data_files = glob.glob(save_path + ".data*") self.assertEqual(2, len(data_files)) # Restore with session.Session( target="", config=config_pb2.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): ds0 = dataset_ops.Dataset.range(10) it0 = dataset_ops.make_initializable_iterator(ds0) get_next0 = it0.get_next() saveable0 = iterator_ops._IteratorSaveable( it0._iterator_resource, name="saveable_it0") with sess.graph.device("/cpu:1"): ds1 = dataset_ops.Dataset.range(20) it1 = dataset_ops.make_initializable_iterator(ds1) get_next1 = it1.get_next() saveable1 = iterator_ops._IteratorSaveable( it1._iterator_resource, name="saveable_it1") saver = saver_module.Saver({ "it0": saveable0, "it1": saveable1 }, write_version=self._WRITE_VERSION, sharded=True) self.evaluate(it0.initializer) self.evaluate(it1.initializer) saver.restore(sess, save_path) self.assertEqual(2, self.evaluate(get_next0)) self.assertEqual(1, self.evaluate(get_next1)) def testIteratorsUnshardedRestore(self): save_path = os.path.join(self.get_temp_dir(), "restore_unsharded_iterators") # Build a graph with 2 parameter nodes on different devices and save. with session.Session( target="", config=config_pb2.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): ds0 = dataset_ops.Dataset.range(10) it0 = dataset_ops.make_initializable_iterator(ds0) get_next0 = it0.get_next() saveable0 = iterator_ops._IteratorSaveable( it0._iterator_resource, name="saveable_it0") with sess.graph.device("/cpu:1"): ds1 = dataset_ops.Dataset.range(20) it1 = dataset_ops.make_initializable_iterator(ds1) get_next1 = it1.get_next() saveable1 = iterator_ops._IteratorSaveable( it1._iterator_resource, name="saveable_it1") saver = saver_module.Saver({ "it0": saveable0, "it1": saveable1 }, write_version=self._WRITE_VERSION, sharded=True) self.evaluate(it0.initializer) self.evaluate(it1.initializer) self.assertEqual(0, self.evaluate(get_next0)) self.assertEqual(1, self.evaluate(get_next0)) self.assertEqual(0, self.evaluate(get_next1)) val = saver.save(sess, save_path) self.assertEqual(save_path, val) data_files = glob.glob(save_path + ".data*") self.assertEqual(2, len(data_files)) # Restore with session.Session( target="", config=config_pb2.ConfigProto(device_count={"CPU": 2})) as sess: with sess.graph.device("/cpu:0"): ds0 = dataset_ops.Dataset.range(10) it0 = dataset_ops.make_initializable_iterator(ds0) get_next0 = it0.get_next() saveable0 = iterator_ops._IteratorSaveable( it0._iterator_resource, name="saveable_it0") with sess.graph.device("/cpu:1"): ds1 = dataset_ops.Dataset.range(20) it1 = dataset_ops.make_initializable_iterator(ds1) get_next1 = it1.get_next() saveable1 = iterator_ops._IteratorSaveable( it1._iterator_resource, name="saveable_it1") saver = saver_module.Saver({ "it0": saveable0, "it1": saveable1 }, write_version=self._WRITE_VERSION, sharded=False) self.evaluate(it0.initializer) self.evaluate(it1.initializer) saver.restore(sess, save_path) self.assertEqual(2, self.evaluate(get_next0)) self.assertEqual(1, self.evaluate(get_next1))
SaveRestoreShardedTestV2
python
gevent__gevent
src/greentest/3.10/test_ssl.py
{ "start": 204134, "end": 210459 }
class ____(unittest.TestCase): def keylog_lines(self, fname=os_helper.TESTFN): with open(fname) as f: return len(list(f)) @requires_keylog @unittest.skipIf(Py_DEBUG_WIN32, "Avoid mixing debug/release CRT on Windows") def test_keylog_defaults(self): self.addCleanup(os_helper.unlink, os_helper.TESTFN) ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) self.assertEqual(ctx.keylog_filename, None) self.assertFalse(os.path.isfile(os_helper.TESTFN)) ctx.keylog_filename = os_helper.TESTFN self.assertEqual(ctx.keylog_filename, os_helper.TESTFN) self.assertTrue(os.path.isfile(os_helper.TESTFN)) self.assertEqual(self.keylog_lines(), 1) ctx.keylog_filename = None self.assertEqual(ctx.keylog_filename, None) with self.assertRaises((IsADirectoryError, PermissionError)): # Windows raises PermissionError ctx.keylog_filename = os.path.dirname( os.path.abspath(os_helper.TESTFN)) with self.assertRaises(TypeError): ctx.keylog_filename = 1 @requires_keylog @unittest.skipIf(Py_DEBUG_WIN32, "Avoid mixing debug/release CRT on Windows") def test_keylog_filename(self): self.addCleanup(os_helper.unlink, os_helper.TESTFN) client_context, server_context, hostname = testing_context() client_context.keylog_filename = os_helper.TESTFN server = ThreadedEchoServer(context=server_context, chatty=False) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) # header, 5 lines for TLS 1.3 self.assertEqual(self.keylog_lines(), 6) client_context.keylog_filename = None server_context.keylog_filename = os_helper.TESTFN server = ThreadedEchoServer(context=server_context, chatty=False) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) self.assertGreaterEqual(self.keylog_lines(), 11) client_context.keylog_filename = os_helper.TESTFN server_context.keylog_filename = os_helper.TESTFN server = ThreadedEchoServer(context=server_context, chatty=False) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) self.assertGreaterEqual(self.keylog_lines(), 21) client_context.keylog_filename = None server_context.keylog_filename = None @requires_keylog @unittest.skipIf(sys.flags.ignore_environment, "test is not compatible with ignore_environment") @unittest.skipIf(Py_DEBUG_WIN32, "Avoid mixing debug/release CRT on Windows") def test_keylog_env(self): self.addCleanup(os_helper.unlink, os_helper.TESTFN) with unittest.mock.patch.dict(os.environ): os.environ['SSLKEYLOGFILE'] = os_helper.TESTFN self.assertEqual(os.environ['SSLKEYLOGFILE'], os_helper.TESTFN) ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) self.assertEqual(ctx.keylog_filename, None) ctx = ssl.create_default_context() self.assertEqual(ctx.keylog_filename, os_helper.TESTFN) ctx = ssl._create_stdlib_context() self.assertEqual(ctx.keylog_filename, os_helper.TESTFN) def test_msg_callback(self): client_context, server_context, hostname = testing_context() def msg_cb(conn, direction, version, content_type, msg_type, data): pass self.assertIs(client_context._msg_callback, None) client_context._msg_callback = msg_cb self.assertIs(client_context._msg_callback, msg_cb) with self.assertRaises(TypeError): client_context._msg_callback = object() def test_msg_callback_tls12(self): client_context, server_context, hostname = testing_context() client_context.maximum_version = ssl.TLSVersion.TLSv1_2 msg = [] def msg_cb(conn, direction, version, content_type, msg_type, data): self.assertIsInstance(conn, ssl.SSLSocket) self.assertIsInstance(data, bytes) self.assertIn(direction, {'read', 'write'}) msg.append((direction, version, content_type, msg_type)) client_context._msg_callback = msg_cb server = ThreadedEchoServer(context=server_context, chatty=False) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) self.assertIn( ("read", TLSVersion.TLSv1_2, _TLSContentType.HANDSHAKE, _TLSMessageType.SERVER_KEY_EXCHANGE), msg ) self.assertIn( ("write", TLSVersion.TLSv1_2, _TLSContentType.CHANGE_CIPHER_SPEC, _TLSMessageType.CHANGE_CIPHER_SPEC), msg ) def test_msg_callback_deadlock_bpo43577(self): client_context, server_context, hostname = testing_context() server_context2 = testing_context()[1] def msg_cb(conn, direction, version, content_type, msg_type, data): pass def sni_cb(sock, servername, ctx): sock.context = server_context2 server_context._msg_callback = msg_cb server_context.sni_callback = sni_cb server = ThreadedEchoServer(context=server_context, chatty=False) with server: with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) with client_context.wrap_socket(socket.socket(), server_hostname=hostname) as s: s.connect((HOST, server.port)) def set_socket_so_linger_on_with_zero_timeout(sock): sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0))
TestSSLDebug
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/solids.py
{ "start": 20265, "end": 20466 }
class ____(graphene.Union): class Meta: types = (GrapheneSolidStepStatsConnection, GrapheneSolidStepStatsUnavailableError) name = "SolidStepStatsOrError"
GrapheneSolidStepStatsOrError
python
google__jax
jax/_src/state/indexing.py
{ "start": 1033, "end": 4886 }
class ____: """A slice with a start index and a size. Both start index and size can either be static, i.e. known at tracing and compilation time, or dynamic. """ start: int | Array size: int | Array stride: int = 1 def __post_init__(self): if self.stride < 0: raise ValueError("`stride` must be >= 0.") @property def is_dynamic_start(self): return not core.is_dim(self.start) @property def is_dynamic_size(self): return not core.is_dim(self.size) def tree_flatten(self): # If `start` is statically known, we treat it as static information xs = () data = () xs += (self.start,) if self.is_dynamic_start else (None,) data += (None,) if self.is_dynamic_start else (self.start,) xs += (self.size,) if self.is_dynamic_size else (None,) data += (None,) if self.is_dynamic_size else (self.size,) data += (self.stride,) return xs, data @classmethod def tree_unflatten(cls, aux_data, children) -> Slice: start, size = ( a if a is not None else b for a, b in zip(children, aux_data[:2]) ) return cls(start, size, aux_data[2]) @classmethod def from_slice(cls, slc: slice, size: int) -> Slice: start, step, size = core.canonicalize_slice(slc, size) if step < 1: raise ValueError(f"slice must have a step >= 1 (found: {step})") return cls(start, size, step) def _pp_slice(context: core.JaxprPpContext, dim, slc: Slice) -> str: start, size = slc.start, slc.size if isinstance(start, core.Var): start_str = core.pp_var(start, context) size_str = ( core.pp_var(size, context) if isinstance(size, core.Var) else str(size) ) return f"{start_str}:{start_str}+{size_str}" else: start_str = str(start) if start == 0: start_str = "" if isinstance(size, core.Var): size_str = core.pp_var(size, context) if start_str: return f"{start_str}:{start_str}+{size_str}" else: return f":{size_str}" else: end = start + size end_str = "" if end == dim else str(end) return f"{start_str}:{end_str}" def dslice( start: int | Array | None, size: int | Array | None = None, stride: int | None = None, ) -> slice | Slice: """Constructs a ``Slice`` from a start index and a size. The semantics of ``dslice`` mirror those of the builtin ``slice`` type: * ``dslice(None)`` is ``:`` * ``dslice(j)`` is ``:j`` * ``dslice(i, j)`` is ``i:i+j`` * ``dslice(i, j, stride)`` is ``i:i+j:stride`` """ if start is None: return slice(None) if stride is None: stride = 1 if not isinstance(stride, int): raise ValueError("Non-static stride in `dslice`") if size is None: if not isinstance(start, int): raise ValueError("Non-static `dslice`") return Slice(0, start, stride) return Slice(start, size, stride) ds = dslice # Handy alias IntIndexer = Union[int, Array] DimIndexer = Union[IntIndexer, Slice] def unpack_ndindexer(indexer: NDIndexer) -> tuple[tuple[bool, ...], tuple[Slice, ...], tuple[IntIndexer, ...]]: # TODO(slebedev): Flip this to be ``is_slice_indexing`` and update callers. is_int_indexing = [not isinstance(i, Slice) for i in indexer.indices] slice_indexers, int_indexers = partition_list( is_int_indexing, indexer.indices) return tuple(is_int_indexing), tuple(slice_indexers), tuple(int_indexers) # type: ignore def _maybe_concretize(x: Any): # This is roughly the same logic as core.concrete_or_error, but we avoid # calling that because constructing the ConcretizationTypeError can be # expensive as the size of the tracing context (i.e. the jaxpr) grows. return core.to_concrete_value(x) @tree_util.register_pytree_node_class @dataclasses.dataclass
Slice
python
PyCQA__pylint
tests/functional/ext/docparams/missing_param_doc.py
{ "start": 3915, "end": 4580 }
class ____: """ Methods decorated with `typing.overload` are excluded from the docparam checks. For example: `missing-param-doc` and `missing-type-doc`. """ def __init__(self, word): self.word = word @overload def starts_with(self, letter: None) -> None: ... @overload def starts_with(self, letter: str) -> bool: ... def starts_with(self, letter: Union[str, None]) -> Union[bool, None]: """ Returns: True if `self.word` begins with `letter` Args: letter: str """ if self.word: return self.word.startswith(letter) return None
Word
python
sqlalchemy__sqlalchemy
test/ext/declarative/test_reflection.py
{ "start": 15798, "end": 18440 }
class ____(DeferredInhReflectBase): @classmethod def define_tables(cls, metadata): Table( "foo", metadata, Column( "id", Integer, primary_key=True, test_needs_autoincrement=True ), Column("type", String(32)), Column("data", String(30)), test_needs_fk=True, ) Table( "bar", metadata, Column("id", Integer, ForeignKey("foo.id"), primary_key=True), Column("bar_data", String(30)), test_needs_fk=True, ) def test_basic(self): class Foo(DeferredReflection, ComparableEntity, Base): __tablename__ = "foo" __mapper_args__ = { "polymorphic_on": "type", "polymorphic_identity": "foo", } class Bar(Foo): __tablename__ = "bar" __mapper_args__ = {"polymorphic_identity": "bar"} DeferredReflection.prepare(testing.db) self._roundtrip() def test_add_subclass_column(self): class Foo(DeferredReflection, ComparableEntity, Base): __tablename__ = "foo" __mapper_args__ = { "polymorphic_on": "type", "polymorphic_identity": "foo", } class Bar(Foo): __tablename__ = "bar" __mapper_args__ = {"polymorphic_identity": "bar"} bar_data = Column(String(30)) DeferredReflection.prepare(testing.db) self._roundtrip() def test_add_pk_column(self): class Foo(DeferredReflection, ComparableEntity, Base): __tablename__ = "foo" __mapper_args__ = { "polymorphic_on": "type", "polymorphic_identity": "foo", } id = Column(Integer, primary_key=True) class Bar(Foo): __tablename__ = "bar" __mapper_args__ = {"polymorphic_identity": "bar"} DeferredReflection.prepare(testing.db) self._roundtrip() def test_add_fk_pk_column(self): class Foo(DeferredReflection, ComparableEntity, Base): __tablename__ = "foo" __mapper_args__ = { "polymorphic_on": "type", "polymorphic_identity": "foo", } class Bar(Foo): __tablename__ = "bar" __mapper_args__ = {"polymorphic_identity": "bar"} id = Column(Integer, ForeignKey("foo.id"), primary_key=True) DeferredReflection.prepare(testing.db) self._roundtrip()
DeferredJoinedInhReflectionTest
python
pytest-dev__pytest
src/_pytest/capture.py
{ "start": 18958, "end": 22194 }
class ____(Generic[AnyStr]): _state = None _in_suspended = False def __init__( self, in_: CaptureBase[AnyStr] | None, out: CaptureBase[AnyStr] | None, err: CaptureBase[AnyStr] | None, ) -> None: self.in_: CaptureBase[AnyStr] | None = in_ self.out: CaptureBase[AnyStr] | None = out self.err: CaptureBase[AnyStr] | None = err def __repr__(self) -> str: return ( f"<MultiCapture out={self.out!r} err={self.err!r} in_={self.in_!r} " f"_state={self._state!r} _in_suspended={self._in_suspended!r}>" ) def start_capturing(self) -> None: self._state = "started" if self.in_: self.in_.start() if self.out: self.out.start() if self.err: self.err.start() def pop_outerr_to_orig(self) -> tuple[AnyStr, AnyStr]: """Pop current snapshot out/err capture and flush to orig streams.""" out, err = self.readouterr() if out: assert self.out is not None self.out.writeorg(out) if err: assert self.err is not None self.err.writeorg(err) return out, err def suspend_capturing(self, in_: bool = False) -> None: self._state = "suspended" if self.out: self.out.suspend() if self.err: self.err.suspend() if in_ and self.in_: self.in_.suspend() self._in_suspended = True def resume_capturing(self) -> None: self._state = "started" if self.out: self.out.resume() if self.err: self.err.resume() if self._in_suspended: assert self.in_ is not None self.in_.resume() self._in_suspended = False def stop_capturing(self) -> None: """Stop capturing and reset capturing streams.""" if self._state == "stopped": raise ValueError("was already stopped") self._state = "stopped" if self.out: self.out.done() if self.err: self.err.done() if self.in_: self.in_.done() def is_started(self) -> bool: """Whether actively capturing -- not suspended or stopped.""" return self._state == "started" def readouterr(self) -> CaptureResult[AnyStr]: out = self.out.snap() if self.out else "" err = self.err.snap() if self.err else "" # TODO: This type error is real, need to fix. return CaptureResult(out, err) # type: ignore[arg-type] def _get_multicapture(method: _CaptureMethod) -> MultiCapture[str]: if method == "fd": return MultiCapture(in_=FDCapture(0), out=FDCapture(1), err=FDCapture(2)) elif method == "sys": return MultiCapture(in_=SysCapture(0), out=SysCapture(1), err=SysCapture(2)) elif method == "no": return MultiCapture(in_=None, out=None, err=None) elif method == "tee-sys": return MultiCapture( in_=None, out=SysCapture(1, tee=True), err=SysCapture(2, tee=True) ) raise ValueError(f"unknown capturing method: {method!r}") # CaptureManager and CaptureFixture
MultiCapture
python
django-haystack__django-haystack
test_haystack/whoosh_tests/test_whoosh_backend.py
{ "start": 41795, "end": 43167 }
class ____(WhooshTestCase): fixtures = ["bulk_data.json"] def setUp(self): super().setUp() # Stow. self.old_ui = connections["whoosh"].get_unified_index() self.ui = UnifiedIndex() self.wmmi = WhooshMockSearchIndex() self.wamsi = WhooshAnotherMockSearchIndex() self.ui.build(indexes=[self.wmmi, self.wamsi]) self.sb = connections["whoosh"].get_backend() connections["whoosh"]._index = self.ui self.sb.setup() self.raw_whoosh = self.sb.index self.parser = QueryParser(self.sb.content_field_name, schema=self.sb.schema) self.sb.delete_index() self.wmmi.update(using="whoosh") self.wamsi.update(using="whoosh") self.sqs = SearchQuerySet("whoosh") def tearDown(self): connections["whoosh"]._index = self.old_ui super().tearDown() def test_searchquerysets_with_models(self): sqs = self.sqs.all() self.assertEqual(sqs.query.build_query(), "*") self.assertEqual(len(sqs), 25) sqs = self.sqs.models(MockModel) self.assertEqual(sqs.query.build_query(), "*") self.assertEqual(len(sqs), 23) sqs = self.sqs.models(AnotherMockModel) self.assertEqual(sqs.query.build_query(), "*") self.assertEqual(len(sqs), 2)
LiveWhooshMultiSearchQuerySetTestCase
python
kamyu104__LeetCode-Solutions
Python/invert-binary-tree.py
{ "start": 1714, "end": 2006 }
class ____(object): # @param {TreeNode} root # @return {TreeNode} def invertTree(self, root): if root is not None: root.left, root.right = self.invertTree(root.right), \ self.invertTree(root.left) return root
Solution3
python
jazzband__django-formtools
tests/tests.py
{ "start": 1196, "end": 6838 }
class ____(TestCase): def setUp(self): super().setUp() # Create a FormPreview instance to share between tests self.preview = preview.FormPreview(TestForm) input_template = '<input type="hidden" name="%s" value="%s" />' self.input = input_template % (self.preview.unused_name('stage'), "%d") self.test_data = {'field1': 'foo', 'field1_': 'asdf'} def test_parse_params_takes_request_object(self): """ FormPreview.parse_params takes a request object as the first argument. """ response = self.client.get('/preview/') state = response.context['state'] self.assertIsNotNone(state.get('user') is not None) def test_unused_name(self): """ Verifies name mangling to get uniue field name. """ self.assertEqual(self.preview.unused_name('field1'), 'field1__') def test_form_get(self): """ Test formtools.preview form retrieval. Use the client library to see if we can successfully retrieve the form (mostly testing the setup ROOT_URLCONF process). Verify that an additional hidden input field is created to manage the stage. """ response = self.client.get('/preview/') stage = self.input % 1 self.assertContains(response, stage, 1) self.assertEqual(response.context['custom_context'], True) self.assertEqual(response.context['form'].initial, {'field1': 'Works!'}) def test_form_preview(self): """ Test formtools.preview form preview rendering. Use the client library to POST to the form to see if a preview is returned. If we do get a form back check that the hidden value is correctly managing the state of the form. """ # Pass strings for form submittal and add stage variable to # show we previously saw first stage of the form. self.test_data.update({'stage': 1, 'date1': datetime.date(2006, 10, 25)}) response = self.client.post('/preview/', self.test_data) # Check to confirm stage is set to 2 in output form. stage = self.input % 2 self.assertContains(response, stage, 1) def test_form_submit(self): """ Test formtools.preview form submittal. Use the client library to POST to the form with stage set to 3 to see if our forms done() method is called. Check first without the security hash, verify failure, retry with security hash and verify success. """ # Pass strings for form submittal and add stage variable to # show we previously saw first stage of the form. self.test_data.update({'stage': 2, 'date1': datetime.date(2006, 10, 25)}) response = self.client.post('/preview/', self.test_data) self.assertNotEqual(response.content, success_string_encoded) hash = self.preview.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash}) response = self.client.post('/preview/', self.test_data) self.assertEqual(response.content, success_string_encoded) def test_bool_submit(self): """ Test formtools.preview form submittal when form contains: BooleanField(required=False) Ticket: #6209 - When an unchecked BooleanField is previewed, the preview form's hash would be computed with no value for ``bool1``. However, when the preview form is rendered, the unchecked hidden BooleanField would be rendered with the string value 'False'. So when the preview form is resubmitted, the hash would be computed with the value 'False' for ``bool1``. We need to make sure the hashes are the same in both cases. """ self.test_data.update({'stage': 2}) hash = self.preview.security_hash(None, TestForm(self.test_data)) self.test_data.update({'hash': hash, 'bool1': 'False'}) with warnings.catch_warnings(record=True): response = self.client.post('/preview/', self.test_data) self.assertEqual(response.content, success_string_encoded) def test_form_submit_good_hash(self): """ Test formtools.preview form submittal, using a correct hash """ # Pass strings for form submittal and add stage variable to # show we previously saw first stage of the form. self.test_data.update({'stage': 2}) response = self.client.post('/preview/', self.test_data) self.assertNotEqual(response.content, success_string_encoded) hash = utils.form_hmac(TestForm(self.test_data)) self.test_data.update({'hash': hash}) response = self.client.post('/preview/', self.test_data) self.assertEqual(response.content, success_string_encoded) def test_form_submit_bad_hash(self): """ Test formtools.preview form submittal does not proceed if the hash is incorrect. """ # Pass strings for form submittal and add stage variable to # show we previously saw first stage of the form. self.test_data.update({'stage': 2}) response = self.client.post('/preview/', self.test_data) self.assertEqual(response.status_code, 200) self.assertNotEqual(response.content, success_string_encoded) hash = utils.form_hmac(TestForm(self.test_data)) + "bad" self.test_data.update({'hash': hash}) response = self.client.post('/previewpreview/', self.test_data) self.assertNotEqual(response.content, success_string_encoded)
PreviewTests
python
apache__airflow
scripts/ci/prek/upgrade_important_versions.py
{ "start": 11405, "end": 25819 }
class ____(Enum): UNQUOTED = 0 SINGLE_QUOTED = 1 DOUBLE_QUOTED = 2 REVERSE_SINGLE_QUOTED = 3 REVERSE_DOUBLE_QUOTED = 4 PIP_PATTERNS: list[tuple[re.Pattern, Quoting]] = [ (re.compile(r"(AIRFLOW_PIP_VERSION=)([0-9.abrc]+)"), Quoting.UNQUOTED), (re.compile(r"(python -m pip install --upgrade pip==)([0-9.abrc]+)"), Quoting.UNQUOTED), (re.compile(r"(AIRFLOW_PIP_VERSION = )(\"[0-9.abrc]+\")"), Quoting.DOUBLE_QUOTED), (re.compile(r"(PIP_VERSION = )(\"[0-9.abrc]+\")"), Quoting.DOUBLE_QUOTED), (re.compile(r"(PIP_VERSION=)(\"[0-9.abrc]+\")"), Quoting.DOUBLE_QUOTED), (re.compile(r"(\| *`AIRFLOW_PIP_VERSION` *\| *)(`[0-9.abrc]+`)( *\|)"), Quoting.REVERSE_SINGLE_QUOTED), ] PYTHON_PATTERNS: list[tuple[str, Quoting]] = [ (r"(\"{python_major_minor}\": \")([0-9.abrc]+)(\")", Quoting.UNQUOTED), ] GOLANG_PATTERNS: list[tuple[re.Pattern, Quoting]] = [ (re.compile(r"(GOLANG_MAJOR_MINOR_VERSION=)(\"[0-9.abrc]+\")"), Quoting.DOUBLE_QUOTED), ( re.compile(r"(\| *`GOLANG_MAJOR_MINOR_VERSION` *\| *)(`[0-9.abrc]+`)( *\|)"), Quoting.REVERSE_SINGLE_QUOTED, ), ] AIRFLOW_IMAGE_PYTHON_PATTERNS: list[tuple[re.Pattern, Quoting]] = [ (re.compile(r"(AIRFLOW_PYTHON_VERSION=)(\"[0-9.abrc]+\")"), Quoting.DOUBLE_QUOTED), ( re.compile(r"(\| ``AIRFLOW_PYTHON_VERSION`` *\| )(``[0-9.abrc]+``)( *\|)"), Quoting.REVERSE_DOUBLE_QUOTED, ), ] UV_PATTERNS: list[tuple[re.Pattern, Quoting]] = [ (re.compile(r"(AIRFLOW_UV_VERSION=)([0-9.abrc]+)"), Quoting.UNQUOTED), (re.compile(r"(uv>=)([0-9.abrc]+)"), Quoting.UNQUOTED), (re.compile(r"(AIRFLOW_UV_VERSION = )(\"[0-9.abrc]+\")"), Quoting.DOUBLE_QUOTED), (re.compile(r"^(\s*UV_VERSION = )(\"[0-9.abrc]+\")", re.MULTILINE), Quoting.DOUBLE_QUOTED), (re.compile(r"^(\s*UV_VERSION=)(\"[0-9.abrc]+\")", re.MULTILINE), Quoting.DOUBLE_QUOTED), (re.compile(r"(\| *`AIRFLOW_UV_VERSION` *\| *)(`[0-9.abrd]+`)( *\|)"), Quoting.REVERSE_SINGLE_QUOTED), ( re.compile( r"(\")([0-9.abrc]+)(\" {2}# Keep this comment to " r"allow automatic replacement of uv version)" ), Quoting.UNQUOTED, ), ] PREK_PATTERNS: list[tuple[re.Pattern, Quoting]] = [ (re.compile(r"(AIRFLOW_PREK_VERSION=)([0-9.abrc]+)"), Quoting.UNQUOTED), (re.compile(r"(AIRFLOW_PREK_VERSION = )(\"[0-9.abrc]+\")"), Quoting.DOUBLE_QUOTED), (re.compile(r"(prek>=)([0-9.abrc]+)"), Quoting.UNQUOTED), (re.compile(r"(PREK_VERSION = )(\"[0-9.abrc]+\")"), Quoting.DOUBLE_QUOTED), (re.compile(r"(PREK_VERSION=)(\"[0-9.abrc]+\")"), Quoting.DOUBLE_QUOTED), ( re.compile(r"(\| *`AIRFLOW_PREK_VERSION` *\| *)(`[0-9.abrc]+`)( *\|)"), Quoting.REVERSE_SINGLE_QUOTED, ), ( re.compile( r"(\")([0-9.abrc]+)(\" {2}# Keep this comment to allow automatic " r"replacement of prek version)" ), Quoting.UNQUOTED, ), ] NODE_LTS_PATTERNS: list[tuple[re.Pattern, Quoting]] = [ (re.compile(r"(^ {2}node: )([0-9.abrc]+)^"), Quoting.UNQUOTED), ] def get_replacement(value: str, quoting: Quoting) -> str: if quoting == Quoting.DOUBLE_QUOTED: return f'"{value}"' if quoting == Quoting.SINGLE_QUOTED: return f"'{value}'" if quoting == Quoting.REVERSE_SINGLE_QUOTED: return f"`{value}`" if quoting == Quoting.REVERSE_DOUBLE_QUOTED: return f"``{value}``" return value def get_env_bool(name: str, default: bool = True) -> bool: """Get boolean value from environment variable.""" default_str = str(default).lower() upgrade_all_str = str(UPGRADE_ALL_BY_DEFAULT).lower() fallback = upgrade_all_str if name.startswith("UPGRADE_") else default_str return os.environ.get(name, fallback).lower() == "true" VERBOSE: bool = os.environ.get("VERBOSE", "false") == "true" UPGRADE_ALL_BY_DEFAULT: bool = os.environ.get("UPGRADE_ALL_BY_DEFAULT", "true") == "true" if UPGRADE_ALL_BY_DEFAULT and VERBOSE: console.print("[bright_blue]Upgrading all important versions") # Package upgrade flags UPGRADE_GITPYTHON: bool = get_env_bool("UPGRADE_GITPYTHON") UPGRADE_GOLANG: bool = get_env_bool("UPGRADE_GOLANG") UPGRADE_HATCH: bool = get_env_bool("UPGRADE_HATCH") UPGRADE_MPROCS: bool = get_env_bool("UPGRADE_MPROCS") UPGRADE_NODE_LTS: bool = get_env_bool("UPGRADE_NODE_LTS") UPGRADE_PIP: bool = get_env_bool("UPGRADE_PIP") UPGRADE_PREK: bool = get_env_bool("UPGRADE_PREK") UPGRADE_PYTHON: bool = get_env_bool("UPGRADE_PYTHON") UPGRADE_PYYAML: bool = get_env_bool("UPGRADE_PYYAML") UPGRADE_RICH: bool = get_env_bool("UPGRADE_RICH") UPGRADE_RUFF: bool = get_env_bool("UPGRADE_RUFF") UPGRADE_UV: bool = get_env_bool("UPGRADE_UV") UPGRADE_MYPY: bool = get_env_bool("UPGRADE_MYPY") UPGRADE_PROTOC: bool = get_env_bool("UPGRADE_PROTOC") ALL_PYTHON_MAJOR_MINOR_VERSIONS = ["3.10", "3.11", "3.12", "3.13"] DEFAULT_PROD_IMAGE_PYTHON_VERSION = "3.12" def replace_version(pattern: re.Pattern[str], version: str, text: str, keep_total_length: bool = True) -> str: # Assume that the pattern has up to 3 replacement groups: # 1. Prefix # 2. Original version # 3. Suffix # # (prefix)(version)(suffix) # In case "keep_total_length" is set to True, the replacement will be padded with spaces to match # the original length def replacer(match): prefix = match.group(1) postfix = match.group(3) if len(match.groups()) > 2 else "" if not keep_total_length: return prefix + version + postfix original_length = len(match.group(2)) new_length = len(version) diff = new_length - original_length if diff <= 0: postfix = " " * -diff + postfix else: postfix = postfix[diff:] padded_replacement = prefix + version + postfix return padded_replacement.strip() return re.sub(pattern, replacer, text) def apply_simple_regex_replacements( text: str, version: str, patterns: list[tuple[str, str]], ) -> str: """Apply a list of simple regex replacements where the version is substituted.""" result = text for pattern, replacement_template in patterns: result = re.sub(pattern, replacement_template.format(version=version), result) return result def apply_pattern_replacements( text: str, version: str, patterns: list[tuple[re.Pattern, Quoting]], keep_length: bool, ) -> str: """Apply pattern-based replacements with quoting.""" result = text for line_pattern, quoting in patterns: result = replace_version(line_pattern, get_replacement(version, quoting), result, keep_length) return result # Configuration for packages that follow simple version constant patterns SIMPLE_VERSION_PATTERNS = { "hatch": [ (r"(HATCH_VERSION = )(\"[0-9.abrc]+\")", 'HATCH_VERSION = "{version}"'), (r"(HATCH_VERSION=)(\"[0-9.abrc]+\")", 'HATCH_VERSION="{version}"'), (r"(hatch==)([0-9.abrc]+)", "hatch=={version}"), (r"(hatch>=)([0-9.abrc]+)", "hatch>={version}"), ], "pyyaml": [ (r"(PYYAML_VERSION = )(\"[0-9.abrc]+\")", 'PYYAML_VERSION = "{version}"'), (r"(PYYAML_VERSION=)(\"[0-9.abrc]+\")", 'PYYAML_VERSION="{version}"'), (r"(pyyaml>=)(\"[0-9.abrc]+\")", 'pyyaml>="{version}"'), (r"(pyyaml>=)([0-9.abrc]+)", "pyyaml>={version}"), ], "gitpython": [ (r"(GITPYTHON_VERSION = )(\"[0-9.abrc]+\")", 'GITPYTHON_VERSION = "{version}"'), (r"(GITPYTHON_VERSION=)(\"[0-9.abrc]+\")", 'GITPYTHON_VERSION="{version}"'), ], "rich": [ (r"(RICH_VERSION = )(\"[0-9.abrc]+\")", 'RICH_VERSION = "{version}"'), (r"(RICH_VERSION=)(\"[0-9.abrc]+\")", 'RICH_VERSION="{version}"'), ], "ruff": [ (r"(ruff==)([0-9.abrc]+)", "ruff=={version}"), (r"(ruff>=)([0-9.abrc]+)", "ruff>={version}"), ], "mypy": [ (r"(mypy==)([0-9.]+)", "mypy=={version}"), ], "protoc": [ (r"(rvolosatovs/protoc:)(v[0-9.]+)", "rvolosatovs/protoc:{version}"), ], "mprocs": [ (r"(ARG MPROCS_VERSION=)(\"[0-9.]+\")", 'ARG MPROCS_VERSION="{version}"'), ], } # Configuration mapping pattern variables to their patterns and upgrade flags PATTERN_REGISTRY = { "pip": (PIP_PATTERNS, UPGRADE_PIP), "golang": (GOLANG_PATTERNS, UPGRADE_GOLANG), "uv": (UV_PATTERNS, UPGRADE_UV), "prek": (PREK_PATTERNS, UPGRADE_PREK), "node_lts": (NODE_LTS_PATTERNS, UPGRADE_NODE_LTS), } def fetch_all_package_versions() -> dict[str, str]: """Fetch latest versions for all packages that need to be upgraded.""" return { "golang": get_latest_golang_version() if UPGRADE_GOLANG else "", "pip": get_latest_pypi_version("pip", UPGRADE_PIP), "uv": get_latest_pypi_version("uv", UPGRADE_UV), "prek": get_latest_pypi_version("prek", UPGRADE_PREK), "hatch": get_latest_pypi_version("hatch", UPGRADE_HATCH), "pyyaml": get_latest_pypi_version("PyYAML", UPGRADE_PYYAML), "gitpython": get_latest_pypi_version("GitPython", UPGRADE_GITPYTHON), "ruff": get_latest_pypi_version("ruff", UPGRADE_RUFF), "rich": get_latest_pypi_version("rich", UPGRADE_RICH), "mypy": get_latest_pypi_version("mypy", UPGRADE_MYPY), "node_lts": get_latest_lts_node_version() if UPGRADE_NODE_LTS else "", "protoc": get_latest_image_version("rvolosatovs/protoc") if UPGRADE_PROTOC else "", "mprocs": get_latest_github_release_version("pvolok/mprocs") if UPGRADE_MPROCS else "", } def log_special_versions(versions: dict[str, str]) -> None: """Log versions that need special attention.""" if UPGRADE_MYPY and versions["mypy"]: console.print(f"[bright_blue]Latest mypy version: {versions['mypy']}") if UPGRADE_PROTOC and versions["protoc"]: console.print(f"[bright_blue]Latest protoc image version: {versions['protoc']}") def fetch_python_versions() -> dict[str, str]: """Fetch latest Python versions for all supported major.minor versions.""" latest_python_versions: dict[str, str] = {} if not UPGRADE_PYTHON: return latest_python_versions all_python_versions = get_all_python_versions() for python_major_minor_version in ALL_PYTHON_MAJOR_MINOR_VERSIONS: latest_python_versions[python_major_minor_version] = get_latest_python_version( python_major_minor_version, all_python_versions ) if python_major_minor_version == DEFAULT_PROD_IMAGE_PYTHON_VERSION: console.print( f"[bright_blue]Latest image python {python_major_minor_version} " f"version: {latest_python_versions[python_major_minor_version]}" ) return latest_python_versions def update_file_with_versions( file_content: str, keep_length: bool, versions: dict[str, str], latest_python_versions: dict[str, str], ) -> str: """Update file content with all version replacements.""" new_content = file_content # Apply pattern-based replacements using registry for package_name, (patterns, should_upgrade) in PATTERN_REGISTRY.items(): version = versions.get(package_name, "") if should_upgrade and version: new_content = apply_pattern_replacements(new_content, version, patterns, keep_length) # Handle Python version updates (special case due to multiple versions) if UPGRADE_PYTHON: for python_major_minor_version in ALL_PYTHON_MAJOR_MINOR_VERSIONS: latest_python_version = latest_python_versions[python_major_minor_version] for line_format, quoting in PYTHON_PATTERNS: line_pattern = re.compile(line_format.format(python_major_minor=python_major_minor_version)) new_content = replace_version( line_pattern, get_replacement(latest_python_version, quoting), new_content, keep_length, ) if python_major_minor_version == DEFAULT_PROD_IMAGE_PYTHON_VERSION: new_content = apply_pattern_replacements( new_content, latest_python_version, AIRFLOW_IMAGE_PYTHON_PATTERNS, keep_length ) # Apply simple regex replacements for package_name, patterns in SIMPLE_VERSION_PATTERNS.items(): should_upgrade = globals().get(f"UPGRADE_{package_name.upper()}", False) version = versions.get(package_name, "") if should_upgrade and version: new_content = apply_simple_regex_replacements(new_content, version, patterns) return new_content def process_all_files(versions: dict[str, str], latest_python_versions: dict[str, str]) -> bool: """ Process all files and apply version updates. Returns: True if any files were changed, False otherwise. """ changed = False for file_to_update, keep_length in FILES_TO_UPDATE: console.print(f"[bright_blue]Updating {file_to_update}") file_content = file_to_update.read_text() new_content = update_file_with_versions(file_content, keep_length, versions, latest_python_versions) if new_content != file_content: file_to_update.write_text(new_content) console.print(f"[bright_blue]Updated {file_to_update}") changed = True return changed def sync_breeze_lock_file() -> None: """Run uv sync to update breeze's lock file.""" console.print("[bright_blue]Running breeze's uv sync to update the lock file") copy_env = os.environ.copy() del copy_env["VIRTUAL_ENV"] subprocess.run( ["uv", "sync", "--resolution", "highest", "--upgrade"], check=True, cwd=AIRFLOW_ROOT_PATH / "dev" / "breeze", env=copy_env, ) def main() -> None: """Main entry point for the version upgrade script.""" retrieve_gh_token(description="airflow-upgrade-important-versions", scopes="public_repo") versions = fetch_all_package_versions() log_special_versions(versions) latest_python_versions = fetch_python_versions() changed = process_all_files(versions, latest_python_versions) if changed: sync_breeze_lock_file() if not os.environ.get("CI"): console.print("[bright_blue]Please commit the changes") sys.exit(1) if __name__ == "__main__": main()
Quoting
python
tensorflow__tensorflow
tensorflow/python/keras/losses.py
{ "start": 16871, "end": 19016 }
class ____(LossFunctionWrapper): """Computes the mean squared logarithmic error between `y_true` and `y_pred`. `loss = square(log(y_true + 1.) - log(y_pred + 1.))` Standalone usage: >>> y_true = [[0., 1.], [0., 0.]] >>> y_pred = [[1., 1.], [1., 0.]] >>> # Using 'auto'/'sum_over_batch_size' reduction type. >>> msle = tf.keras.losses.MeanSquaredLogarithmicError() >>> msle(y_true, y_pred).numpy() 0.240 >>> # Calling with 'sample_weight'. >>> msle(y_true, y_pred, sample_weight=[0.7, 0.3]).numpy() 0.120 >>> # Using 'sum' reduction type. >>> msle = tf.keras.losses.MeanSquaredLogarithmicError( ... reduction=tf.keras.losses.Reduction.SUM) >>> msle(y_true, y_pred).numpy() 0.480 >>> # Using 'none' reduction type. >>> msle = tf.keras.losses.MeanSquaredLogarithmicError( ... reduction=tf.keras.losses.Reduction.NONE) >>> msle(y_true, y_pred).numpy() array([0.240, 0.240], dtype=float32) Usage with the `compile()` API: ```python model.compile(optimizer='sgd', loss=tf.keras.losses.MeanSquaredLogarithmicError()) ``` """ def __init__(self, reduction=losses_utils.ReductionV2.AUTO, name='mean_squared_logarithmic_error'): """Initializes `MeanSquaredLogarithmicError` instance. Args: reduction: Type of `tf.keras.losses.Reduction` to apply to loss. Default value is `AUTO`. `AUTO` indicates that the reduction option will be determined by the usage context. For almost all cases this defaults to `SUM_OVER_BATCH_SIZE`. When used with `tf.distribute.Strategy`, outside of built-in training loops such as `tf.keras` `compile` and `fit`, using `AUTO` or `SUM_OVER_BATCH_SIZE` will raise an error. Please see this custom training [tutorial]( https://www.tensorflow.org/tutorials/distribute/custom_training) for more details. name: Optional name for the instance. Defaults to 'mean_squared_logarithmic_error'. """ super().__init__( mean_squared_logarithmic_error, name=name, reduction=reduction)
MeanSquaredLogarithmicError
python
numpy__numpy
numpy/distutils/msvc9compiler.py
{ "start": 1039, "end": 2192 }
class ____(_MSVCCompiler): def __init__(self, verbose=0, dry_run=0, force=0): _MSVCCompiler.__init__(self, verbose, dry_run, force) def initialize(self, plat_name=None): # The 'lib' and 'include' variables may be overwritten # by MSVCCompiler.initialize, so save them for later merge. environ_lib = os.getenv('lib') environ_include = os.getenv('include') _MSVCCompiler.initialize(self, plat_name) # Merge current and previous values of 'lib' and 'include' os.environ['lib'] = _merge(environ_lib, os.environ['lib']) os.environ['include'] = _merge(environ_include, os.environ['include']) # msvc9 building for 32 bits requires SSE2 to work around a # compiler bug. if platform_bits == 32: self.compile_options += ['/arch:SSE2'] self.compile_options_debug += ['/arch:SSE2'] def manifest_setup_ldargs(self, output_filename, build_temp, ld_args): ld_args.append('/MANIFEST') _MSVCCompiler.manifest_setup_ldargs(self, output_filename, build_temp, ld_args)
MSVCCompiler
python
walkccc__LeetCode
solutions/1751. Maximum Number of Events That Can Be Attended II/1751.py
{ "start": 0, "end": 632 }
class ____: def maxValue(self, events: list[list[int]], k: int) -> int: events.sort() @functools.lru_cache(None) def dp(i: int, k: int) -> int: """ Returns the maximum sum of values that you can receive by attending events[i..n), where k is the maximum number of attendance. """ if k == 0 or i == len(events): return 0 # Binary search `events` to find the first index j # s.t. events[j][0] > events[i][1]. j = bisect.bisect(events, [events[i][1], math.inf, math.inf], i + 1) return max(events[i][2] + dp(j, k - 1), dp(i + 1, k)) return dp(0, k)
Solution
python
tensorflow__tensorflow
tensorflow/python/training/basic_session_run_hooks.py
{ "start": 34173, "end": 35929 }
class ____(session_run_hook.SessionRunHook): """Delays execution until global step reaches `wait_until_step`. This hook delays execution until global step reaches to `wait_until_step`. It is used to gradually start workers in distributed settings. One example usage would be setting `wait_until_step=int(K*log(task_id+1))` assuming that task_id=0 is the chief. """ def __init__(self, wait_until_step): """Initializes a `GlobalStepWaiterHook`. Args: wait_until_step: an `int` shows until which global step should we wait. """ self._wait_until_step = wait_until_step def begin(self): self._worker_is_started = False self._global_step_tensor = training_util._get_or_create_global_step_read() # pylint: disable=protected-access if self._global_step_tensor is None: raise RuntimeError( "Global step should be created to use _GlobalStepWaiterHook.") def before_run(self, run_context): if self._worker_is_started: return None if self._wait_until_step <= 0: self._worker_is_started = True return None logging.info("Waiting for global step %d before starting training.", self._wait_until_step) last_logged_step = 0 while True: current_step = run_context.session.run(self._global_step_tensor) if current_step >= self._wait_until_step: self._worker_is_started = True return None if current_step - last_logged_step > 1000: logging.info( "Waiting for global step %d before starting training. " "Current step is %d.", self._wait_until_step, current_step) last_logged_step = current_step time.sleep(0.5) @tf_export(v1=["train.FinalOpsHook"])
GlobalStepWaiterHook
python
davidhalter__jedi
test/completion/arrays.py
{ "start": 2349, "end": 3496 }
class ____: setitem_x = [1,2] setitem_x[0] = 3 #? ['setitem_x'] F().setitem_x #? list() F().setitem_x # ----------------- # dicts # ----------------- dic2 = {'asdf': 3, 'b': 'str'} #? int() dic2['asdf'] #? None int() str() dic2.get('asdf') # string literal #? int() dic2[r'asdf'] #? int() dic2[r'asdf'] #? int() dic2[r'as' 'd' u'f'] #? int() str() dic2['just_something'] # unpacking a, b = dic2 #? str() a a, b = {1: 'x', 2.0: 1j} #? int() float() a #? int() float() b def f(): """ github #83 """ r = {} r['status'] = (200, 'ok') return r #? dict() f() # completion within dicts #? 9 ['str'] {str: str} # iteration problem (detected with sith) d = dict({'a':''}) def y(a): return a #? y(**d) #? str() d['a'] # problem with more complicated casts dic = {str(key): ''} #? str() dic[''] for x in {1: 3.0, '': 1j}: #? int() str() x #? ['__iter__'] dict().values().__iter__ d = dict(a=3, b='') x, = d.values() #? int() str() x #? int() d['a'] #? int() str() None d.get('a') some_dct = dict({'a': 1, 'b': ''}, a=1.0) #? float() some_dct['a'] #? str() some_dct['b'] #? int() float() str() some_dct['c']
F
python
great-expectations__great_expectations
great_expectations/render/renderer/site_builder.py
{ "start": 41063, "end": 41186 }
class ____: def __init__(self, title, link) -> None: self.title = title self.link = link
CallToActionButton
python
catalyst-team__catalyst
catalyst/contrib/datasets/imagenette.py
{ "start": 473, "end": 942 }
class ____(ImageClassificationDataset): """ `Imagenette <https://github.com/fastai/imagenette#imagenette-1>`_ Dataset with images resized so that the shortest size is 160 px. .. note:: catalyst[cv] required for this dataset. """ name = "imagenette2-160" resources = [ ( "https://s3.amazonaws.com/fast-ai-imageclas/imagenette2-160.tgz", "e793b78cc4c9e9a4ccc0c1155377a412", ) ]
Imagenette160
python
joke2k__faker
tests/providers/test_ssn.py
{ "start": 41214, "end": 41799 }
class ____(unittest.TestCase): def setUp(self): self.fake = Faker("en_IN") Faker.seed(0) test_samples = 10 self.aadhaar_ids = [self.fake.aadhaar_id() for _ in range(test_samples)] def test_length(self): for aadhaar_id in self.aadhaar_ids: assert len(aadhaar_id) == 12 def test_first_digit_non_zero(self): for aadhar_id in self.aadhaar_ids: assert aadhar_id[0] != "0" def test_valid_luhn(self): for aadhaar_id in self.aadhaar_ids: assert luhn_checksum(aadhaar_id) == 0
TestEnIn
python
keon__algorithms
algorithms/map/separate_chaining_hashtable.py
{ "start": 18, "end": 172 }
class ____(object): def __init__(self, key=None, value=None, next=None): self.key = key self.value = value self.next = next
Node
python
google__python-fire
fire/trace.py
{ "start": 8251, "end": 10314 }
class ____: """A FireTraceElement represents a single step taken by a Fire execution. Examples of a FireTraceElement are the instantiation of a class or the accessing of an object member. """ def __init__(self, component=None, action=None, target=None, args=None, filename=None, lineno=None, error=None, capacity=None): """Instantiates a FireTraceElement. Args: component: The result of this element of the trace. action: The type of action (e.g. instantiating a class) taking place. target: (string) The name of the component being acted upon. args: The args consumed by the represented action. filename: The file in which the action is defined, or None if N/A. lineno: The line number on which the action is defined, or None if N/A. error: The error represented by the action, or None if N/A. capacity: (bool) Whether the action could have accepted additional args. """ self.component = component self._action = action self._target = target self.args = args self._filename = filename self._lineno = lineno self._error = error self._separator = False self._capacity = capacity def HasError(self): return self._error is not None def HasCapacity(self): return self._capacity def HasSeparator(self): return self._separator def AddSeparator(self): self._separator = True def ErrorAsStr(self): return ' '.join(str(arg) for arg in self._error.args) def __str__(self): if self.HasError(): return self.ErrorAsStr() else: # Format is: {action} "{target}" ({filename}:{lineno}) string = self._action if self._target is not None: string += f' "{self._target}"' if self._filename is not None: path = self._filename if self._lineno is not None: path += f':{self._lineno}' string += f' ({path})' return string
FireTraceElement
python
great-expectations__great_expectations
docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/multicolumn_map_expectation_template.py
{ "start": 2858, "end": 5782 }
class ____(MulticolumnMapExpectation): # </snippet> # <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/multicolumn_map_expectation_template.py docstring"> """TODO: Add a docstring here""" # </snippet> # These examples will be shown in the public gallery. # They will also be executed as unit tests for your Expectation. examples = [] # This is the id string of the Metric used by this Expectation. # For most Expectations, it will be the same as the `condition_metric_name` defined in your Metric class above. # <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/multicolumn_map_expectation_template.py map_metric"> map_metric = "METRIC NAME GOES HERE" # </snippet> # This is a list of parameter names that can affect whether the Expectation evaluates to True or False success_keys = ( "column_list", "mostly", ) def validate_configuration( self, configuration: Optional[ExpectationConfiguration] = None ) -> None: """ Validates that a configuration has been set, and sets a configuration if it has yet to be set. Ensures that necessary configuration arguments have been provided for the validation of the expectation. Args: configuration (OPTIONAL[ExpectationConfiguration]): \ An optional Expectation Configuration entry that will be used to configure the expectation Returns: None. Raises InvalidExpectationConfigurationError if the config is not validated successfully """ super().validate_configuration(configuration) configuration = configuration or self.configuration # # Check other things in configuration.kwargs and raise Exceptions if needed # try: # assert ( # ... # ), "message" # assert ( # ... # ), "message" # except AssertionError as e: # raise InvalidExpectationConfigurationError(str(e)) # This object contains metadata for display in the public Gallery # <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/multicolumn_map_expectation_template.py library_metadata"> library_metadata = { "tags": [], # Tags for this Expectation in the Gallery "contributors": [ # Github handles for all contributors to this Expectation. "@your_name_here", # Don't forget to add your github handle here! ], } # </snippet> if __name__ == "__main__": # <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/multicolumn_map_expectation_template.py diagnostics"> ExpectMulticolumnValuesToMatchSomeCriteria().print_diagnostic_checklist() # </snippet>
ExpectMulticolumnValuesToMatchSomeCriteria
python
pytorch__pytorch
test/distributed/checkpoint/e2e/test_fine_tuning.py
{ "start": 1111, "end": 1762 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.layer1 = nn.Linear(DIM, DIM) self.layer2 = nn.Linear(DIM, DIM) self.layer3 = nn.Linear(DIM, DIM) self.sequential = nn.Sequential(nn.Linear(DIM, DIM), nn.ReLU()) self.module_list = nn.ModuleList([nn.Linear(DIM, DIM), nn.ReLU()]) self.relu = nn.ReLU() def forward(self, batch): x = self.relu(self.layer1(batch)) x = self.relu(self.layer2(x)) x = self.relu(self.layer3(x)) x = self.sequential(x) x = self.module_list[1](self.module_list[0](x)) return x
PreTrainedModel
python
pandas-dev__pandas
pandas/core/arrays/integer.py
{ "start": 5693, "end": 5882 }
class ____(IntegerDtype): type = np.int64 name: ClassVar[str] = "Int64" __doc__ = _dtype_docstring.format(dtype="int64") @register_extension_dtype @set_module("pandas")
Int64Dtype
python
scipy__scipy
benchmarks/benchmarks/interpolate.py
{ "start": 1809, "end": 2459 }
class ____(Benchmark): param_names = ['n_grids', 'method'] params = [ [10j, 100j, 1000j], ['nearest', 'linear', 'cubic'] ] def setup(self, n_grids, method): self.func = lambda x, y: x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2 self.grid_x, self.grid_y = np.mgrid[0:1:n_grids, 0:1:n_grids] self.points = np.random.rand(1000, 2) self.values = self.func(self.points[:, 0], self.points[:, 1]) def time_evaluation(self, n_grids, method): interpolate.griddata(self.points, self.values, (self.grid_x, self.grid_y), method=method)
GridData
python
gevent__gevent
src/gevent/testing/util.py
{ "start": 6751, "end": 12408 }
class ____(object): """ The results of running an external command. If the command was successful, this has a boolean value of True; otherwise, a boolean value of false. The integer value of this object is the command's exit code. """ def __init__(self, command, run_kwargs, code, output=None, # type: str error=None, # type: str name=None, run_count=0, skipped_count=0, run_duration=0, # type: float ): self.command = command self.run_kwargs = run_kwargs self.code = code self.output = output self.error = error self.name = name self.run_count = run_count self.skipped_count = skipped_count self.run_duration = run_duration @property def output_lines(self): return self.output.splitlines() def __bool__(self): return not bool(self.code) __nonzero__ = __bool__ def __int__(self): return self.code def __repr__(self): return ( "RunResult of: %r\n" "Code: %s\n" "kwargs: %r\n" "Output:\n" "----\n" "%s" "----\n" "Error:\n" "----\n" "%s" "----\n" ) % ( self.command, self.code, self.run_kwargs, self.output, self.error ) def _should_show_warning_output(out): if 'Warning' in out: # Strip out some patterns we specifically do not # care about. # from test.support for monkey-patched tests out = out.replace('Warning -- reap_children', 'NADA') out = out.replace("Warning -- threading_cleanup", 'NADA') # The below *could* be done with sophisticated enough warning # filters passed to the children # collections.abc is the new home; setuptools uses the old one, # as does dnspython out = out.replace("DeprecationWarning: Using or importing the ABCs", 'NADA') # libuv poor timer resolution out = out.replace('UserWarning: libuv only supports', 'NADA') # Packages on Python 2 out = out.replace('ImportWarning: Not importing directory', 'NADA') # Testing that U mode does the same thing out = out.replace("DeprecationWarning: 'U' mode is deprecated", 'NADA') out = out.replace("DeprecationWarning: dns.hash module", 'NADA') return 'Warning' in out output_lock = threading.Lock() def _find_test_status(took, out): status = '[took %.1fs%s]' skipped = '' run_count = 0 skipped_count = 0 if out: m = re.search(r"Ran (\d+) tests in", out) if m: result = out[m.start():m.end()] status = status.replace('took', result) run_count = int(out[m.start(1):m.end(1)]) m = re.search(r' \(skipped=(\d+)\)$', out) if m: skipped = _colorize('skipped', out[m.start():m.end()]) skipped_count = int(out[m.start(1):m.end(1)]) status = status % (took, skipped) # pylint:disable=consider-using-augmented-assign if took > 10: status = _colorize('slow-test', status) return status, run_count, skipped_count def run(command, **kwargs): # pylint:disable=too-many-locals """ Execute *command*, returning a `RunResult`. This blocks until *command* finishes or until it times out. """ buffer_output = kwargs.pop('buffer_output', BUFFER_OUTPUT) quiet = kwargs.pop('quiet', QUIET) verbose = not quiet nested = kwargs.pop('nested', False) allowed_return_codes = kwargs.pop('allowed_return_codes', ()) if buffer_output: assert 'stdout' not in kwargs and 'stderr' not in kwargs, kwargs kwargs['stderr'] = subprocess.STDOUT kwargs['stdout'] = subprocess.PIPE popen = start(command, quiet=quiet, **kwargs) name = popen.name try: time_start = perf_counter() out, err = popen.communicate() duration = perf_counter() - time_start if popen.was_killed or popen.poll() is None: result = 'TIMEOUT' else: result = popen.poll() finally: kill(popen) assert popen.timer is None # We don't want to treat return codes that are allowed as failures, # but we do want to log those specially. That's why we retain the distinction # between ``failed`` and ``result`` (failed takes the allowed codes into account). failed = bool(result) and result not in allowed_return_codes if out: out = out.strip() out = out if isinstance(out, str) else out.decode('utf-8', 'ignore') if out and (failed or verbose or _should_show_warning_output(out)): out = ' ' + out.replace('\n', '\n ') out = out.rstrip() out += '\n' log('| %s\n%s', name, out) status, run_count, skipped_count = _find_test_status(duration, out) if result: log('! %s [code %s] %s', name, result, status, color='error' if failed else 'suboptimal-behaviour') elif not nested: log('- %s %s', name, status) # For everything outside this function, we need to pretend that # allowed codes are actually successes. return RunResult( command, kwargs, 0 if result in allowed_return_codes else result, output=out, error=err, name=name, run_count=run_count, skipped_count=skipped_count, run_duration=duration, )
RunResult
python
google__pytype
pytype/typegraph/typegraph_serializer.py
{ "start": 1656, "end": 1884 }
class ____: id: int solver_idx: int start_node: CFGNodeId end_node: CFGNodeId initial_binding_count: int shortcircuited: bool from_cache: bool steps: list[SerializedQueryStep] @dataclasses.dataclass
SerializedQuery
python
Textualize__textual
src/textual/_path.py
{ "start": 301, "end": 2062 }
class ____(Exception): """Raised when supplied CSS path(s) are invalid.""" def _css_path_type_as_list(css_path: CSSPathType) -> list[PurePath]: """Normalize the supplied CSSPathType into a list of paths. Args: css_path: Value to be normalized. Raises: CSSPathError: If the argument has the wrong format. Returns: A list of paths. """ paths: list[PurePath] = [] if isinstance(css_path, str): paths = [Path(css_path)] elif isinstance(css_path, PurePath): paths = [css_path] elif isinstance(css_path, list): paths = [Path(path) for path in css_path] else: raise CSSPathError("Expected a str, Path or list[str | Path] for the CSS_PATH.") return paths def _make_path_object_relative(path: str | PurePath, obj: object) -> Path: """Convert the supplied path to a Path object that is relative to a given Python object. If the supplied path is absolute, it will simply be converted to a Path object. Used, for example, to return the path of a CSS file relative to a Textual App instance. Args: path: A path. obj: A Python object to resolve the path relative to. Returns: A resolved Path object, relative to obj """ path = Path(path) # If the path supplied by the user is absolute, we can use it directly if path.is_absolute(): return path # Otherwise (relative path), resolve it relative to obj... base_path = getattr(obj, "_BASE_PATH", None) if base_path is not None: subclass_path = Path(base_path) else: subclass_path = Path(inspect.getfile(obj.__class__)) resolved_path = (subclass_path.parent / path).resolve() return resolved_path
CSSPathError
python
doocs__leetcode
solution/2200-2299/2256.Minimum Average Difference/Solution.py
{ "start": 0, "end": 434 }
class ____: def minimumAverageDifference(self, nums: List[int]) -> int: pre, suf = 0, sum(nums) n = len(nums) ans, mi = 0, inf for i, x in enumerate(nums): pre += x suf -= x a = pre // (i + 1) b = 0 if n - i - 1 == 0 else suf // (n - i - 1) if (t := abs(a - b)) < mi: ans = i mi = t return ans
Solution
python
getsentry__sentry
src/sentry/issues/endpoints/project_event_details.py
{ "start": 3044, "end": 5396 }
class ____(ProjectEndpoint): owner = ApiOwner.ISSUES publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, } rate_limits = RateLimitConfig( limit_overrides={ "GET": { RateLimitCategory.IP: RateLimit(limit=5, window=1), RateLimitCategory.USER: RateLimit(limit=5, window=1), RateLimitCategory.ORGANIZATION: RateLimit(limit=5, window=1), }, } ) def get(self, request: Request, project: Project, event_id: str) -> Response: """ Retrieve an Event for a Project ``````````````````````````````` Return details on an individual event. :pparam string organization_id_or_slug: the id or slug of the organization the event belongs to. :pparam string project_id_or_slug: the id or slug of the project the event belongs to. :pparam string event_id: the id of the event to retrieve. It is the hexadecimal id as reported by the raven client) :auth: required """ try: start, end = get_date_range_from_params(request.GET, optional=True) except InvalidParams: raise ParseError(detail="Invalid date range") group_id_s = request.GET.get("group_id") group_id = int(group_id_s) if group_id_s else None event = eventstore.backend.get_event_by_id(project.id, event_id, group_id=group_id) if event is None: return Response({"detail": "Event not found"}, status=404) environments = set(request.GET.getlist("environment")) # TODO: Remove `for_group` check once performance issues are moved to the issue platform if hasattr(event, "for_group") and event.group: event = event.for_group(event.group) data = wrap_event_response( request_user=request.user, event=event, environments=list(environments), include_full_release_data=True, start=start, end=end, ) return Response(data) from rest_framework.request import Request from rest_framework.response import Response @region_silo_endpoint
ProjectEventDetailsEndpoint
python
cython__cython
Cython/Compiler/PyrexTypes.py
{ "start": 98931, "end": 101291 }
class ____(CType): # common base type for pointer/array types # # base_type CType Reference type # is_string bool Pointer is a char* or similar C string. # is_pyunicode_ptr bool Pointer is a Py_UNICODE*. subtypes = ['base_type'] def __init__(self, base_type): self.base_type = base_type if base_type.is_cv_qualified: base_type = base_type.cv_base_type for char_type in (c_char_type, c_uchar_type, c_schar_type): if base_type.same_as(char_type): self.is_string = 1 break else: if base_type.same_as(c_py_unicode_type): self.is_pyunicode_ptr = 1 if self.is_string and not base_type.is_error: if base_type.signed == 2: self.to_py_function = "__Pyx_PyObject_FromCString" if self.is_ptr: self.from_py_function = "__Pyx_PyObject_As%sSString" elif base_type.signed: self.to_py_function = "__Pyx_PyObject_FromString" if self.is_ptr: self.from_py_function = "__Pyx_PyObject_As%sString" else: self.to_py_function = "__Pyx_PyObject_FromCString" if self.is_ptr: self.from_py_function = "__Pyx_PyObject_As%sUString" if self.is_ptr: self.from_py_function %= '' if self.base_type.is_const else 'Writable' self.exception_value = "NULL" elif self.is_pyunicode_ptr and not base_type.is_error: self.to_py_function = "__Pyx_PyUnicode_FromUnicode" self.to_py_utility_code = UtilityCode.load_cached( "pyunicode_from_unicode", "StringTools.c") if self.is_ptr: self.from_py_function = "__Pyx_PyUnicode_AsUnicode" self.exception_value = "NULL" def py_type_name(self): if self.is_string: return "bytes" elif self.is_pyunicode_ptr: return "unicode" else: return super().py_type_name() def literal_code(self, value): if self.is_string: assert isinstance(value, str) return '"%s"' % StringEncoding.escape_byte_string(value) return str(value)
CPointerBaseType
python
django__django
django/forms/widgets.py
{ "start": 33535, "end": 34449 }
class ____(MultiWidget): """ A widget that splits datetime input into two <input type="text"> boxes. """ supports_microseconds = False template_name = "django/forms/widgets/splitdatetime.html" def __init__( self, attrs=None, date_format=None, time_format=None, date_attrs=None, time_attrs=None, ): widgets = ( DateInput( attrs=attrs if date_attrs is None else date_attrs, format=date_format, ), TimeInput( attrs=attrs if time_attrs is None else time_attrs, format=time_format, ), ) super().__init__(widgets) def decompress(self, value): if value: value = to_current_timezone(value) return [value.date(), value.time()] return [None, None]
SplitDateTimeWidget
python
coleifer__peewee
peewee.py
{ "start": 98452, "end": 111716 }
class ____(_callable_context_manager): context_class = Context field_types = {} operations = {} param = '?' quote = '""' server_version = None # Feature toggles. compound_select_parentheses = CSQ_PARENTHESES_NEVER for_update = False index_schema_prefix = False index_using_precedes_table = False limit_max = None nulls_ordering = False returning_clause = False safe_create_index = True safe_drop_index = True sequences = False truncate_table = True def __init__(self, database, thread_safe=True, autorollback=False, field_types=None, operations=None, autocommit=None, autoconnect=True, **kwargs): self._field_types = merge_dict(FIELD, self.field_types) self._operations = merge_dict(OP, self.operations) if field_types: self._field_types.update(field_types) if operations: self._operations.update(operations) self.autoconnect = autoconnect self.thread_safe = thread_safe if thread_safe: self._state = _ConnectionLocal() self._lock = threading.Lock() else: self._state = _ConnectionState() self._lock = _NoopLock() if autorollback: __deprecated__('Peewee no longer uses the "autorollback" option, ' 'as we always run in autocommit-mode now. This ' 'changes psycopg2\'s semantics so that the conn ' 'is not left in a transaction-aborted state.') if autocommit is not None: __deprecated__('Peewee no longer uses the "autocommit" option, as ' 'the semantics now require it to always be True. ' 'Because some database-drivers also use the ' '"autocommit" parameter, you are receiving a ' 'warning so you may update your code and remove ' 'the parameter, as in the future, specifying ' 'autocommit could impact the behavior of the ' 'database driver you are using.') self.connect_params = {} self.init(database, **kwargs) def init(self, database, **kwargs): if not self.is_closed(): self.close() self.database = database self.connect_params.update(kwargs) self.deferred = not bool(database) def __enter__(self): if self.is_closed(): self.connect() ctx = self.atomic() self._state.ctx.append(ctx) ctx.__enter__() return self def __exit__(self, exc_type, exc_val, exc_tb): ctx = self._state.ctx.pop() try: ctx.__exit__(exc_type, exc_val, exc_tb) finally: if not self._state.ctx: self.close() def connection_context(self): return ConnectionContext(self) def _connect(self): raise NotImplementedError def connect(self, reuse_if_open=False): with self._lock: if self.deferred: raise InterfaceError('Error, database must be initialized ' 'before opening a connection.') if not self._state.closed: if reuse_if_open: return False raise OperationalError('Connection already opened.') self._state.reset() with __exception_wrapper__: self._state.set_connection(self._connect()) if self.server_version is None: self._set_server_version(self._state.conn) self._initialize_connection(self._state.conn) return True def _initialize_connection(self, conn): pass def _set_server_version(self, conn): self.server_version = 0 def close(self): with self._lock: if self.deferred: raise InterfaceError('Error, database must be initialized ' 'before opening a connection.') if self.in_transaction(): raise OperationalError('Attempting to close database while ' 'transaction is open.') is_open = not self._state.closed try: if is_open: with __exception_wrapper__: self._close(self._state.conn) finally: self._state.reset() return is_open def _close(self, conn): conn.close() def is_closed(self): return self._state.closed def is_connection_usable(self): return not self._state.closed def connection(self): if self.is_closed(): self.connect() return self._state.conn def cursor(self, commit=None, named_cursor=None): if commit is not None: __deprecated__('"commit" has been deprecated and is a no-op.') if self.is_closed(): if self.autoconnect: self.connect() else: raise InterfaceError('Error, database connection not opened.') return self._state.conn.cursor() def execute_sql(self, sql, params=None, commit=None): if commit is not None: __deprecated__('"commit" has been deprecated and is a no-op.') logger.debug((sql, params)) with __exception_wrapper__: cursor = self.cursor() cursor.execute(sql, params or ()) return cursor def execute(self, query, commit=None, **context_options): if commit is not None: __deprecated__('"commit" has been deprecated and is a no-op.') ctx = self.get_sql_context(**context_options) sql, params = ctx.sql(query).query() return self.execute_sql(sql, params) def get_context_options(self): return { 'field_types': self._field_types, 'operations': self._operations, 'param': self.param, 'quote': self.quote, 'compound_select_parentheses': self.compound_select_parentheses, 'conflict_statement': self.conflict_statement, 'conflict_update': self.conflict_update, 'for_update': self.for_update, 'index_schema_prefix': self.index_schema_prefix, 'index_using_precedes_table': self.index_using_precedes_table, 'limit_max': self.limit_max, 'nulls_ordering': self.nulls_ordering, } def get_sql_context(self, **context_options): context = self.get_context_options() if context_options: context.update(context_options) return self.context_class(**context) def conflict_statement(self, on_conflict, query): raise NotImplementedError def conflict_update(self, on_conflict, query): raise NotImplementedError def _build_on_conflict_update(self, on_conflict, query): if on_conflict._conflict_target: stmt = SQL('ON CONFLICT') target = EnclosedNodeList([ Entity(col) if isinstance(col, basestring) else col for col in on_conflict._conflict_target]) if on_conflict._conflict_where is not None: target = NodeList([target, SQL('WHERE'), on_conflict._conflict_where]) else: stmt = SQL('ON CONFLICT ON CONSTRAINT') target = on_conflict._conflict_constraint if isinstance(target, basestring): target = Entity(target) updates = [] if on_conflict._preserve: for column in on_conflict._preserve: excluded = NodeList((SQL('EXCLUDED'), ensure_entity(column)), glue='.') expression = NodeList((ensure_entity(column), SQL('='), excluded)) updates.append(expression) if on_conflict._update: for k, v in on_conflict._update.items(): if not isinstance(v, Node): # Attempt to resolve string field-names to their respective # field object, to apply data-type conversions. if isinstance(k, basestring): k = getattr(query.table, k) if isinstance(k, Field): v = k.to_value(v) else: v = Value(v, unpack=False) else: v = QualifiedNames(v) updates.append(NodeList((ensure_entity(k), SQL('='), v))) parts = [stmt, target, SQL('DO UPDATE SET'), CommaNodeList(updates)] if on_conflict._where: parts.extend((SQL('WHERE'), QualifiedNames(on_conflict._where))) return NodeList(parts) def last_insert_id(self, cursor, query_type=None): return cursor.lastrowid def rows_affected(self, cursor): return cursor.rowcount def default_values_insert(self, ctx): return ctx.literal('DEFAULT VALUES') def session_start(self): return self.transaction().__enter__() def session_commit(self): try: txn = self.pop_transaction() except IndexError: return False txn.commit(begin=self.in_transaction()) return True def session_rollback(self): try: txn = self.pop_transaction() except IndexError: return False txn.rollback(begin=self.in_transaction()) return True def in_transaction(self): return bool(self._state.transactions) def push_transaction(self, transaction): self._state.transactions.append(transaction) def pop_transaction(self): return self._state.transactions.pop() def transaction_depth(self): return len(self._state.transactions) def top_transaction(self): if self._state.transactions: return self._state.transactions[-1] def atomic(self, *args, **kwargs): return _atomic(self, *args, **kwargs) def manual_commit(self): return _manual(self) def transaction(self, *args, **kwargs): return _transaction(self, *args, **kwargs) def savepoint(self): return _savepoint(self) def begin(self): if self.is_closed(): self.connect() with __exception_wrapper__: self.cursor().execute('BEGIN') def rollback(self): with __exception_wrapper__: self.cursor().execute('ROLLBACK') def commit(self): with __exception_wrapper__: self.cursor().execute('COMMIT') def batch_commit(self, it, n): for group in chunked(it, n): with self.atomic(): for obj in group: yield obj def table_exists(self, table_name, schema=None): if is_model(table_name): model = table_name table_name = model._meta.table_name schema = model._meta.schema return table_name in self.get_tables(schema=schema) def get_tables(self, schema=None): raise NotImplementedError def get_indexes(self, table, schema=None): raise NotImplementedError def get_columns(self, table, schema=None): raise NotImplementedError def get_primary_keys(self, table, schema=None): raise NotImplementedError def get_foreign_keys(self, table, schema=None): raise NotImplementedError def sequence_exists(self, seq): raise NotImplementedError def create_tables(self, models, **options): for model in sort_models(models): model.create_table(**options) def drop_tables(self, models, **kwargs): for model in reversed(sort_models(models)): model.drop_table(**kwargs) def extract_date(self, date_part, date_field): raise NotImplementedError def truncate_date(self, date_part, date_field): raise NotImplementedError def to_timestamp(self, date_field): raise NotImplementedError def from_timestamp(self, date_field): raise NotImplementedError def random(self): return fn.random() def bind(self, models, bind_refs=True, bind_backrefs=True): for model in models: model.bind(self, bind_refs=bind_refs, bind_backrefs=bind_backrefs) def bind_ctx(self, models, bind_refs=True, bind_backrefs=True): return _BoundModelsContext(models, self, bind_refs, bind_backrefs) def get_noop_select(self, ctx): return ctx.sql(Select().columns(SQL('0')).where(SQL('0'))) @property def Model(self): if not hasattr(self, '_Model'): class Meta: database = self self._Model = type('BaseModel', (Model,), {'Meta': Meta}) return self._Model def __pragma__(name): def __get__(self): return self.pragma(name) def __set__(self, value): return self.pragma(name, value) return property(__get__, __set__)
Database
python
openai__openai-python
src/openai/resources/beta/threads/runs/runs.py
{ "start": 2086, "end": 75439 }
class ____(SyncAPIResource): @cached_property def steps(self) -> Steps: return Steps(self._client) @cached_property def with_raw_response(self) -> RunsWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/openai/openai-python#accessing-raw-response-data-eg-headers """ return RunsWithRawResponse(self) @cached_property def with_streaming_response(self) -> RunsWithStreamingResponse: """ An alternative to `.with_raw_response` that doesn't eagerly read the response body. For more information, see https://www.github.com/openai/openai-python#with_streaming_response """ return RunsWithStreamingResponse(self) @overload @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def create( self, thread_id: str, *, assistant_id: str, include: List[RunStepInclude] | Omit = omit, additional_instructions: Optional[str] | Omit = omit, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | Omit = omit, instructions: Optional[str] | Omit = omit, max_completion_tokens: Optional[int] | Omit = omit, max_prompt_tokens: Optional[int] | Omit = omit, metadata: Optional[Metadata] | Omit = omit, model: Union[str, ChatModel, None] | Omit = omit, parallel_tool_calls: bool | Omit = omit, reasoning_effort: Optional[ReasoningEffort] | Omit = omit, response_format: Optional[AssistantResponseFormatOptionParam] | Omit = omit, stream: Optional[Literal[False]] | Omit = omit, temperature: Optional[float] | Omit = omit, tool_choice: Optional[AssistantToolChoiceOptionParam] | Omit = omit, tools: Optional[Iterable[AssistantToolParam]] | Omit = omit, top_p: Optional[float] | Omit = omit, truncation_strategy: Optional[run_create_params.TruncationStrategy] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> Run: """ Create a run. Args: assistant_id: The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. include: A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content. See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. additional_instructions: Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. additional_messages: Adds additional messages to the thread before creating the run. instructions: Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. parallel_tool_calls: Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. reasoning_effort: Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently supported values are `none`, `minimal`, `low`, `medium`, and `high`. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - `gpt-5.1` defaults to `none`, which does not perform reasoning. The supported reasoning values for `gpt-5.1` are `none`, `low`, `medium`, and `high`. Tool calls are supported for all reasoning values in gpt-5.1. - All models before `gpt-5.1` default to `medium` reasoning effort, and do not support `none`. - The `gpt-5-pro` model defaults to (and only supports) `high` reasoning effort. response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. stream: If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to control the initial context window of the run. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ ... @overload @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def create( self, thread_id: str, *, assistant_id: str, stream: Literal[True], include: List[RunStepInclude] | Omit = omit, additional_instructions: Optional[str] | Omit = omit, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | Omit = omit, instructions: Optional[str] | Omit = omit, max_completion_tokens: Optional[int] | Omit = omit, max_prompt_tokens: Optional[int] | Omit = omit, metadata: Optional[Metadata] | Omit = omit, model: Union[str, ChatModel, None] | Omit = omit, parallel_tool_calls: bool | Omit = omit, reasoning_effort: Optional[ReasoningEffort] | Omit = omit, response_format: Optional[AssistantResponseFormatOptionParam] | Omit = omit, temperature: Optional[float] | Omit = omit, tool_choice: Optional[AssistantToolChoiceOptionParam] | Omit = omit, tools: Optional[Iterable[AssistantToolParam]] | Omit = omit, top_p: Optional[float] | Omit = omit, truncation_strategy: Optional[run_create_params.TruncationStrategy] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> Stream[AssistantStreamEvent]: """ Create a run. Args: assistant_id: The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. stream: If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. include: A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content. See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. additional_instructions: Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. additional_messages: Adds additional messages to the thread before creating the run. instructions: Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. parallel_tool_calls: Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. reasoning_effort: Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently supported values are `none`, `minimal`, `low`, `medium`, and `high`. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - `gpt-5.1` defaults to `none`, which does not perform reasoning. The supported reasoning values for `gpt-5.1` are `none`, `low`, `medium`, and `high`. Tool calls are supported for all reasoning values in gpt-5.1. - All models before `gpt-5.1` default to `medium` reasoning effort, and do not support `none`. - The `gpt-5-pro` model defaults to (and only supports) `high` reasoning effort. response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to control the initial context window of the run. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ ... @overload @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def create( self, thread_id: str, *, assistant_id: str, stream: bool, include: List[RunStepInclude] | Omit = omit, additional_instructions: Optional[str] | Omit = omit, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | Omit = omit, instructions: Optional[str] | Omit = omit, max_completion_tokens: Optional[int] | Omit = omit, max_prompt_tokens: Optional[int] | Omit = omit, metadata: Optional[Metadata] | Omit = omit, model: Union[str, ChatModel, None] | Omit = omit, parallel_tool_calls: bool | Omit = omit, reasoning_effort: Optional[ReasoningEffort] | Omit = omit, response_format: Optional[AssistantResponseFormatOptionParam] | Omit = omit, temperature: Optional[float] | Omit = omit, tool_choice: Optional[AssistantToolChoiceOptionParam] | Omit = omit, tools: Optional[Iterable[AssistantToolParam]] | Omit = omit, top_p: Optional[float] | Omit = omit, truncation_strategy: Optional[run_create_params.TruncationStrategy] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> Run | Stream[AssistantStreamEvent]: """ Create a run. Args: assistant_id: The ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) to use to execute this run. stream: If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. include: A list of additional fields to include in the response. Currently the only supported value is `step_details.tool_calls[*].file_search.results[*].content` to fetch the file search result content. See the [file search tool documentation](https://platform.openai.com/docs/assistants/tools/file-search#customizing-file-search-settings) for more information. additional_instructions: Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions. additional_messages: Adds additional messages to the thread before creating the run. instructions: Overrides the [instructions](https://platform.openai.com/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis. max_completion_tokens: The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. max_prompt_tokens: The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info. metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. model: The ID of the [Model](https://platform.openai.com/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used. parallel_tool_calls: Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use. reasoning_effort: Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently supported values are `none`, `minimal`, `low`, `medium`, and `high`. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. - `gpt-5.1` defaults to `none`, which does not perform reasoning. The supported reasoning values for `gpt-5.1` are `none`, `low`, `medium`, and `high`. Tool calls are supported for all reasoning values in gpt-5.1. - All models before `gpt-5.1` default to `medium` reasoning effort, and do not support `none`. - The `gpt-5-pro` model defaults to (and only supports) `high` reasoning effort. response_format: Specifies the format that the model must output. Compatible with [GPT-4o](https://platform.openai.com/docs/models#gpt-4o), [GPT-4 Turbo](https://platform.openai.com/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`. Setting to `{ "type": "json_schema", "json_schema": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). Setting to `{ "type": "json_object" }` enables JSON mode, which ensures the message the model generates is valid JSON. **Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request. Also note that the message content may be partially cut off if `finish_reason="length"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length. temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. tool_choice: Controls which (if any) tool is called by the model. `none` means the model will not call any tools and instead generates a message. `auto` is the default value and means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user. Specifying a particular tool like `{"type": "file_search"}` or `{"type": "function", "function": {"name": "my_function"}}` forces the model to call that tool. tools: Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis. top_p: An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both. truncation_strategy: Controls for how a thread will be truncated prior to the run. Use this to control the initial context window of the run. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ ... @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") @required_args(["assistant_id"], ["assistant_id", "stream"]) def create( self, thread_id: str, *, assistant_id: str, include: List[RunStepInclude] | Omit = omit, additional_instructions: Optional[str] | Omit = omit, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | Omit = omit, instructions: Optional[str] | Omit = omit, max_completion_tokens: Optional[int] | Omit = omit, max_prompt_tokens: Optional[int] | Omit = omit, metadata: Optional[Metadata] | Omit = omit, model: Union[str, ChatModel, None] | Omit = omit, parallel_tool_calls: bool | Omit = omit, reasoning_effort: Optional[ReasoningEffort] | Omit = omit, response_format: Optional[AssistantResponseFormatOptionParam] | Omit = omit, stream: Optional[Literal[False]] | Literal[True] | Omit = omit, temperature: Optional[float] | Omit = omit, tool_choice: Optional[AssistantToolChoiceOptionParam] | Omit = omit, tools: Optional[Iterable[AssistantToolParam]] | Omit = omit, top_p: Optional[float] | Omit = omit, truncation_strategy: Optional[run_create_params.TruncationStrategy] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> Run | Stream[AssistantStreamEvent]: if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/runs", body=maybe_transform( { "assistant_id": assistant_id, "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, "max_completion_tokens": max_completion_tokens, "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, "parallel_tool_calls": parallel_tool_calls, "reasoning_effort": reasoning_effort, "response_format": response_format, "stream": stream, "temperature": temperature, "tool_choice": tool_choice, "tools": tools, "top_p": top_p, "truncation_strategy": truncation_strategy, }, run_create_params.RunCreateParamsStreaming if stream else run_create_params.RunCreateParamsNonStreaming, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, query=maybe_transform({"include": include}, run_create_params.RunCreateParams), ), cast_to=Run, stream=stream or False, stream_cls=Stream[AssistantStreamEvent], ) @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def retrieve( self, run_id: str, *, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> Run: """ Retrieves a run. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get( f"/threads/{thread_id}/runs/{run_id}", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=Run, ) @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def update( self, run_id: str, *, thread_id: str, metadata: Optional[Metadata] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> Run: """ Modifies a run. Args: metadata: Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/runs/{run_id}", body=maybe_transform({"metadata": metadata}, run_update_params.RunUpdateParams), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=Run, ) @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def list( self, thread_id: str, *, after: str | Omit = omit, before: str | Omit = omit, limit: int | Omit = omit, order: Literal["asc", "desc"] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> SyncCursorPage[Run]: """ Returns a list of runs belonging to a thread. Args: after: A cursor for use in pagination. `after` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, ending with obj_foo, your subsequent call can include after=obj_foo in order to fetch the next page of the list. before: A cursor for use in pagination. `before` is an object ID that defines your place in the list. For instance, if you make a list request and receive 100 objects, starting with obj_foo, your subsequent call can include before=obj_foo in order to fetch the previous page of the list. limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. order: Sort order by the `created_at` timestamp of the objects. `asc` for ascending order and `desc` for descending order. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._get_api_list( f"/threads/{thread_id}/runs", page=SyncCursorPage[Run], options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, query=maybe_transform( { "after": after, "before": before, "limit": limit, "order": order, }, run_list_params.RunListParams, ), ), model=Run, ) @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def cancel( self, run_id: str, *, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> Run: """ Cancels a run that is `in_progress`. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/runs/{run_id}/cancel", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=Run, ) @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def create_and_poll( self, *, assistant_id: str, include: List[RunStepInclude] | Omit = omit, additional_instructions: Optional[str] | Omit = omit, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | Omit = omit, instructions: Optional[str] | Omit = omit, max_completion_tokens: Optional[int] | Omit = omit, max_prompt_tokens: Optional[int] | Omit = omit, metadata: Optional[Metadata] | Omit = omit, model: Union[str, ChatModel, None] | Omit = omit, parallel_tool_calls: bool | Omit = omit, reasoning_effort: Optional[ReasoningEffort] | Omit = omit, response_format: Optional[AssistantResponseFormatOptionParam] | Omit = omit, temperature: Optional[float] | Omit = omit, tool_choice: Optional[AssistantToolChoiceOptionParam] | Omit = omit, tools: Optional[Iterable[AssistantToolParam]] | Omit = omit, top_p: Optional[float] | Omit = omit, truncation_strategy: Optional[run_create_params.TruncationStrategy] | Omit = omit, poll_interval_ms: int | Omit = omit, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ A helper to create a run an poll for a terminal state. More information on Run lifecycles can be found here: https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps """ run = self.create( # pyright: ignore[reportDeprecated] thread_id=thread_id, assistant_id=assistant_id, include=include, additional_instructions=additional_instructions, additional_messages=additional_messages, instructions=instructions, max_completion_tokens=max_completion_tokens, max_prompt_tokens=max_prompt_tokens, metadata=metadata, model=model, response_format=response_format, temperature=temperature, tool_choice=tool_choice, parallel_tool_calls=parallel_tool_calls, reasoning_effort=reasoning_effort, # We assume we are not streaming when polling stream=False, tools=tools, truncation_strategy=truncation_strategy, top_p=top_p, extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, ) return self.poll( # pyright: ignore[reportDeprecated] run.id, thread_id=thread_id, extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, poll_interval_ms=poll_interval_ms, timeout=timeout, ) @overload @typing_extensions.deprecated("use `stream` instead") def create_and_stream( self, *, assistant_id: str, additional_instructions: Optional[str] | Omit = omit, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | Omit = omit, instructions: Optional[str] | Omit = omit, max_completion_tokens: Optional[int] | Omit = omit, max_prompt_tokens: Optional[int] | Omit = omit, metadata: Optional[Metadata] | Omit = omit, model: Union[str, ChatModel, None] | Omit = omit, parallel_tool_calls: bool | Omit = omit, reasoning_effort: Optional[ReasoningEffort] | Omit = omit, response_format: Optional[AssistantResponseFormatOptionParam] | Omit = omit, temperature: Optional[float] | Omit = omit, tool_choice: Optional[AssistantToolChoiceOptionParam] | Omit = omit, tools: Optional[Iterable[AssistantToolParam]] | Omit = omit, top_p: Optional[float] | Omit = omit, truncation_strategy: Optional[run_create_params.TruncationStrategy] | Omit = omit, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AssistantStreamManager[AssistantEventHandler]: """Create a Run stream""" ... @overload @typing_extensions.deprecated("use `stream` instead") def create_and_stream( self, *, assistant_id: str, additional_instructions: Optional[str] | Omit = omit, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | Omit = omit, instructions: Optional[str] | Omit = omit, max_completion_tokens: Optional[int] | Omit = omit, max_prompt_tokens: Optional[int] | Omit = omit, metadata: Optional[Metadata] | Omit = omit, model: Union[str, ChatModel, None] | Omit = omit, parallel_tool_calls: bool | Omit = omit, reasoning_effort: Optional[ReasoningEffort] | Omit = omit, response_format: Optional[AssistantResponseFormatOptionParam] | Omit = omit, temperature: Optional[float] | Omit = omit, tool_choice: Optional[AssistantToolChoiceOptionParam] | Omit = omit, tools: Optional[Iterable[AssistantToolParam]] | Omit = omit, top_p: Optional[float] | Omit = omit, truncation_strategy: Optional[run_create_params.TruncationStrategy] | Omit = omit, thread_id: str, event_handler: AssistantEventHandlerT, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AssistantStreamManager[AssistantEventHandlerT]: """Create a Run stream""" ... @typing_extensions.deprecated("use `stream` instead") def create_and_stream( self, *, assistant_id: str, additional_instructions: Optional[str] | Omit = omit, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | Omit = omit, instructions: Optional[str] | Omit = omit, max_completion_tokens: Optional[int] | Omit = omit, max_prompt_tokens: Optional[int] | Omit = omit, metadata: Optional[Metadata] | Omit = omit, model: Union[str, ChatModel, None] | Omit = omit, parallel_tool_calls: bool | Omit = omit, reasoning_effort: Optional[ReasoningEffort] | Omit = omit, response_format: Optional[AssistantResponseFormatOptionParam] | Omit = omit, temperature: Optional[float] | Omit = omit, tool_choice: Optional[AssistantToolChoiceOptionParam] | Omit = omit, tools: Optional[Iterable[AssistantToolParam]] | Omit = omit, top_p: Optional[float] | Omit = omit, truncation_strategy: Optional[run_create_params.TruncationStrategy] | Omit = omit, thread_id: str, event_handler: AssistantEventHandlerT | None = None, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT]: """Create a Run stream""" if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = { "OpenAI-Beta": "assistants=v2", "X-Stainless-Stream-Helper": "threads.runs.create_and_stream", "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", **(extra_headers or {}), } make_request = partial( self._post, f"/threads/{thread_id}/runs", body=maybe_transform( { "assistant_id": assistant_id, "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, "max_completion_tokens": max_completion_tokens, "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, "response_format": response_format, "temperature": temperature, "tool_choice": tool_choice, "stream": True, "tools": tools, "truncation_strategy": truncation_strategy, "parallel_tool_calls": parallel_tool_calls, "reasoning_effort": reasoning_effort, "top_p": top_p, }, run_create_params.RunCreateParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=Run, stream=True, stream_cls=Stream[AssistantStreamEvent], ) return AssistantStreamManager(make_request, event_handler=event_handler or AssistantEventHandler()) @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def poll( self, run_id: str, thread_id: str, extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, poll_interval_ms: int | Omit = omit, ) -> Run: """ A helper to poll a run status until it reaches a terminal state. More information on Run lifecycles can be found here: https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps """ extra_headers = {"X-Stainless-Poll-Helper": "true", **(extra_headers or {})} if is_given(poll_interval_ms): extra_headers["X-Stainless-Custom-Poll-Interval"] = str(poll_interval_ms) terminal_states = {"requires_action", "cancelled", "completed", "failed", "expired", "incomplete"} while True: response = self.with_raw_response.retrieve( # pyright: ignore[reportDeprecated] thread_id=thread_id, run_id=run_id, extra_headers=extra_headers, extra_body=extra_body, extra_query=extra_query, timeout=timeout, ) run = response.parse() # Return if we reached a terminal state if run.status in terminal_states: return run if not is_given(poll_interval_ms): from_header = response.headers.get("openai-poll-after-ms") if from_header is not None: poll_interval_ms = int(from_header) else: poll_interval_ms = 1000 self._sleep(poll_interval_ms / 1000) @overload @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def stream( self, *, assistant_id: str, include: List[RunStepInclude] | Omit = omit, additional_instructions: Optional[str] | Omit = omit, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | Omit = omit, instructions: Optional[str] | Omit = omit, max_completion_tokens: Optional[int] | Omit = omit, max_prompt_tokens: Optional[int] | Omit = omit, metadata: Optional[Metadata] | Omit = omit, model: Union[str, ChatModel, None] | Omit = omit, parallel_tool_calls: bool | Omit = omit, reasoning_effort: Optional[ReasoningEffort] | Omit = omit, response_format: Optional[AssistantResponseFormatOptionParam] | Omit = omit, temperature: Optional[float] | Omit = omit, tool_choice: Optional[AssistantToolChoiceOptionParam] | Omit = omit, tools: Optional[Iterable[AssistantToolParam]] | Omit = omit, top_p: Optional[float] | Omit = omit, truncation_strategy: Optional[run_create_params.TruncationStrategy] | Omit = omit, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AssistantStreamManager[AssistantEventHandler]: """Create a Run stream""" ... @overload @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def stream( self, *, assistant_id: str, include: List[RunStepInclude] | Omit = omit, additional_instructions: Optional[str] | Omit = omit, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | Omit = omit, instructions: Optional[str] | Omit = omit, max_completion_tokens: Optional[int] | Omit = omit, max_prompt_tokens: Optional[int] | Omit = omit, metadata: Optional[Metadata] | Omit = omit, model: Union[str, ChatModel, None] | Omit = omit, parallel_tool_calls: bool | Omit = omit, reasoning_effort: Optional[ReasoningEffort] | Omit = omit, response_format: Optional[AssistantResponseFormatOptionParam] | Omit = omit, temperature: Optional[float] | Omit = omit, tool_choice: Optional[AssistantToolChoiceOptionParam] | Omit = omit, tools: Optional[Iterable[AssistantToolParam]] | Omit = omit, top_p: Optional[float] | Omit = omit, truncation_strategy: Optional[run_create_params.TruncationStrategy] | Omit = omit, thread_id: str, event_handler: AssistantEventHandlerT, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AssistantStreamManager[AssistantEventHandlerT]: """Create a Run stream""" ... @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def stream( self, *, assistant_id: str, include: List[RunStepInclude] | Omit = omit, additional_instructions: Optional[str] | Omit = omit, additional_messages: Optional[Iterable[run_create_params.AdditionalMessage]] | Omit = omit, instructions: Optional[str] | Omit = omit, max_completion_tokens: Optional[int] | Omit = omit, max_prompt_tokens: Optional[int] | Omit = omit, metadata: Optional[Metadata] | Omit = omit, model: Union[str, ChatModel, None] | Omit = omit, parallel_tool_calls: bool | Omit = omit, reasoning_effort: Optional[ReasoningEffort] | Omit = omit, response_format: Optional[AssistantResponseFormatOptionParam] | Omit = omit, temperature: Optional[float] | Omit = omit, tool_choice: Optional[AssistantToolChoiceOptionParam] | Omit = omit, tools: Optional[Iterable[AssistantToolParam]] | Omit = omit, top_p: Optional[float] | Omit = omit, truncation_strategy: Optional[run_create_params.TruncationStrategy] | Omit = omit, thread_id: str, event_handler: AssistantEventHandlerT | None = None, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT]: """Create a Run stream""" if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = { "OpenAI-Beta": "assistants=v2", "X-Stainless-Stream-Helper": "threads.runs.create_and_stream", "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", **(extra_headers or {}), } make_request = partial( self._post, f"/threads/{thread_id}/runs", body=maybe_transform( { "assistant_id": assistant_id, "additional_instructions": additional_instructions, "additional_messages": additional_messages, "instructions": instructions, "max_completion_tokens": max_completion_tokens, "max_prompt_tokens": max_prompt_tokens, "metadata": metadata, "model": model, "response_format": response_format, "temperature": temperature, "tool_choice": tool_choice, "stream": True, "tools": tools, "parallel_tool_calls": parallel_tool_calls, "reasoning_effort": reasoning_effort, "truncation_strategy": truncation_strategy, "top_p": top_p, }, run_create_params.RunCreateParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, query=maybe_transform({"include": include}, run_create_params.RunCreateParams), ), cast_to=Run, stream=True, stream_cls=Stream[AssistantStreamEvent], ) return AssistantStreamManager(make_request, event_handler=event_handler or AssistantEventHandler()) @overload @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def submit_tool_outputs( self, run_id: str, *, thread_id: str, tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], stream: Optional[Literal[False]] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> Run: """ When a run has the `status: "requires_action"` and `required_action.type` is `submit_tool_outputs`, this endpoint can be used to submit the outputs from the tool calls once they're all completed. All outputs must be submitted in a single request. Args: tool_outputs: A list of tools for which the outputs are being submitted. stream: If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ ... @overload @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def submit_tool_outputs( self, run_id: str, *, thread_id: str, stream: Literal[True], tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> Stream[AssistantStreamEvent]: """ When a run has the `status: "requires_action"` and `required_action.type` is `submit_tool_outputs`, this endpoint can be used to submit the outputs from the tool calls once they're all completed. All outputs must be submitted in a single request. Args: stream: If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. tool_outputs: A list of tools for which the outputs are being submitted. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ ... @overload @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def submit_tool_outputs( self, run_id: str, *, thread_id: str, stream: bool, tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> Run | Stream[AssistantStreamEvent]: """ When a run has the `status: "requires_action"` and `required_action.type` is `submit_tool_outputs`, this endpoint can be used to submit the outputs from the tool calls once they're all completed. All outputs must be submitted in a single request. Args: stream: If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. tool_outputs: A list of tools for which the outputs are being submitted. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ ... @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") @required_args(["thread_id", "tool_outputs"], ["thread_id", "stream", "tool_outputs"]) @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def submit_tool_outputs( self, run_id: str, *, thread_id: str, tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], stream: Optional[Literal[False]] | Literal[True] | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> Run | Stream[AssistantStreamEvent]: if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") extra_headers = {"OpenAI-Beta": "assistants=v2", **(extra_headers or {})} return self._post( f"/threads/{thread_id}/runs/{run_id}/submit_tool_outputs", body=maybe_transform( { "tool_outputs": tool_outputs, "stream": stream, }, run_submit_tool_outputs_params.RunSubmitToolOutputsParamsStreaming if stream else run_submit_tool_outputs_params.RunSubmitToolOutputsParamsNonStreaming, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=Run, stream=stream or False, stream_cls=Stream[AssistantStreamEvent], ) @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def submit_tool_outputs_and_poll( self, *, tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], run_id: str, thread_id: str, poll_interval_ms: int | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> Run: """ A helper to submit a tool output to a run and poll for a terminal run state. More information on Run lifecycles can be found here: https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps """ run = self.submit_tool_outputs( # pyright: ignore[reportDeprecated] run_id=run_id, thread_id=thread_id, tool_outputs=tool_outputs, stream=False, extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, ) return self.poll( # pyright: ignore[reportDeprecated] run_id=run.id, thread_id=thread_id, extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, poll_interval_ms=poll_interval_ms, ) @overload @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def submit_tool_outputs_stream( self, *, tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], run_id: str, thread_id: str, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AssistantStreamManager[AssistantEventHandler]: """ Submit the tool outputs from a previous run and stream the run to a terminal state. More information on Run lifecycles can be found here: https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps """ ... @overload @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def submit_tool_outputs_stream( self, *, tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], run_id: str, thread_id: str, event_handler: AssistantEventHandlerT, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AssistantStreamManager[AssistantEventHandlerT]: """ Submit the tool outputs from a previous run and stream the run to a terminal state. More information on Run lifecycles can be found here: https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps """ ... @typing_extensions.deprecated("The Assistants API is deprecated in favor of the Responses API") def submit_tool_outputs_stream( self, *, tool_outputs: Iterable[run_submit_tool_outputs_params.ToolOutput], run_id: str, thread_id: str, event_handler: AssistantEventHandlerT | None = None, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN, ) -> AssistantStreamManager[AssistantEventHandler] | AssistantStreamManager[AssistantEventHandlerT]: """ Submit the tool outputs from a previous run and stream the run to a terminal state. More information on Run lifecycles can be found here: https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps """ if not run_id: raise ValueError(f"Expected a non-empty value for `run_id` but received {run_id!r}") if not thread_id: raise ValueError(f"Expected a non-empty value for `thread_id` but received {thread_id!r}") extra_headers = { "OpenAI-Beta": "assistants=v2", "X-Stainless-Stream-Helper": "threads.runs.submit_tool_outputs_stream", "X-Stainless-Custom-Event-Handler": "true" if event_handler else "false", **(extra_headers or {}), } request = partial( self._post, f"/threads/{thread_id}/runs/{run_id}/submit_tool_outputs", body=maybe_transform( { "tool_outputs": tool_outputs, "stream": True, }, run_submit_tool_outputs_params.RunSubmitToolOutputsParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=Run, stream=True, stream_cls=Stream[AssistantStreamEvent], ) return AssistantStreamManager(request, event_handler=event_handler or AssistantEventHandler())
Runs
python
allegroai__clearml
clearml/backend_api/session/client/client.py
{ "start": 2934, "end": 4286 }
class ____(Session): """ Session that raises exceptions on errors, and be configured with explicit ``config_file`` path. """ def __init__( self, config_file: Union[Path, Text] = None, initialize_logging: bool = False, *args: Any, **kwargs: Any, ) -> None: """ :param config_file: configuration file to use, else use the default :type config_file: Path | Text """ def init() -> None: super(StrictSession, self).__init__(initialize_logging=initialize_logging, *args, **kwargs) if not config_file: init() return original = LOCAL_CONFIG_FILE_OVERRIDE_VAR.get() or None try: LOCAL_CONFIG_FILE_OVERRIDE_VAR.set(str(config_file)) init() finally: if original is None: LOCAL_CONFIG_FILE_OVERRIDE_VAR.pop() else: LOCAL_CONFIG_FILE_OVERRIDE_VAR.set(original) def send(self, request: APIRequest, *args: Any, **kwargs: Any) -> CallResult: result = super(StrictSession, self).send(request, *args, **kwargs) if not result.ok(): raise APIError(result) if not result.response: raise APIError(result, extra_info="Invalid response") return result
StrictSession
python
joke2k__faker
faker/providers/currency/es_AR/__init__.py
{ "start": 48, "end": 281 }
class ____(CurrencyProvider): price_formats = ["%##", "%.###", "%#.##0", "%##.##0", "%##.##0", "%.###.##0", "%#,##"] def pricetag(self) -> str: return "$" + self.numerify(self.random_element(self.price_formats))
Provider
python
fastapi__sqlmodel
docs_src/tutorial/many_to_many/tutorial003.py
{ "start": 753, "end": 3834 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_links: List[HeroTeamLink] = Relationship(back_populates="hero") sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def create_heroes(): with Session(engine) as session: team_preventers = Team(name="Preventers", headquarters="Sharp Tower") team_z_force = Team(name="Z-Force", headquarters="Sister Margaret's Bar") hero_deadpond = Hero( name="Deadpond", secret_name="Dive Wilson", ) hero_rusty_man = Hero( name="Rusty-Man", secret_name="Tommy Sharp", age=48, ) hero_spider_boy = Hero( name="Spider-Boy", secret_name="Pedro Parqueador", ) deadpond_team_z_link = HeroTeamLink(team=team_z_force, hero=hero_deadpond) deadpond_preventers_link = HeroTeamLink( team=team_preventers, hero=hero_deadpond, is_training=True ) spider_boy_preventers_link = HeroTeamLink( team=team_preventers, hero=hero_spider_boy, is_training=True ) rusty_man_preventers_link = HeroTeamLink( team=team_preventers, hero=hero_rusty_man ) session.add(deadpond_team_z_link) session.add(deadpond_preventers_link) session.add(spider_boy_preventers_link) session.add(rusty_man_preventers_link) session.commit() for link in team_z_force.hero_links: print("Z-Force hero:", link.hero, "is training:", link.is_training) for link in team_preventers.hero_links: print("Preventers hero:", link.hero, "is training:", link.is_training) def update_heroes(): with Session(engine) as session: hero_spider_boy = session.exec( select(Hero).where(Hero.name == "Spider-Boy") ).one() team_z_force = session.exec(select(Team).where(Team.name == "Z-Force")).one() spider_boy_z_force_link = HeroTeamLink( team=team_z_force, hero=hero_spider_boy, is_training=True ) team_z_force.hero_links.append(spider_boy_z_force_link) session.add(team_z_force) session.commit() print("Updated Spider-Boy's Teams:", hero_spider_boy.team_links) print("Z-Force heroes:", team_z_force.hero_links) for link in hero_spider_boy.team_links: if link.team.name == "Preventers": link.is_training = False session.add(hero_spider_boy) session.commit() for link in hero_spider_boy.team_links: print("Spider-Boy team:", link.team, "is training:", link.is_training) def main(): create_db_and_tables() create_heroes() update_heroes() if __name__ == "__main__": main()
Hero
python
pytorch__pytorch
torch/nn/modules/rnn.py
{ "start": 48956, "end": 60810 }
class ____(RNNBase): r"""__init__(input_size,hidden_size,num_layers=1,bias=True,batch_first=False,dropout=0.0,bidirectional=False,device=None,dtype=None) Apply a multi-layer gated recurrent unit (GRU) RNN to an input sequence. For each element in the input sequence, each layer computes the following function: .. math:: \begin{array}{ll} r_t = \sigma(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\ z_t = \sigma(W_{iz} x_t + b_{iz} + W_{hz} h_{(t-1)} + b_{hz}) \\ n_t = \tanh(W_{in} x_t + b_{in} + r_t \odot (W_{hn} h_{(t-1)}+ b_{hn})) \\ h_t = (1 - z_t) \odot n_t + z_t \odot h_{(t-1)} \end{array} where :math:`h_t` is the hidden state at time `t`, :math:`x_t` is the input at time `t`, :math:`h_{(t-1)}` is the hidden state of the layer at time `t-1` or the initial hidden state at time `0`, and :math:`r_t`, :math:`z_t`, :math:`n_t` are the reset, update, and new gates, respectively. :math:`\sigma` is the sigmoid function, and :math:`\odot` is the Hadamard product. In a multilayer GRU, the input :math:`x^{(l)}_t` of the :math:`l` -th layer (:math:`l \ge 2`) is the hidden state :math:`h^{(l-1)}_t` of the previous layer multiplied by dropout :math:`\delta^{(l-1)}_t` where each :math:`\delta^{(l-1)}_t` is a Bernoulli random variable which is :math:`0` with probability :attr:`dropout`. Args: input_size: The number of expected features in the input `x` hidden_size: The number of features in the hidden state `h` num_layers: Number of recurrent layers. E.g., setting ``num_layers=2`` would mean stacking two GRUs together to form a `stacked GRU`, with the second GRU taking in outputs of the first GRU and computing the final results. Default: 1 bias: If ``False``, then the layer does not use bias weights `b_ih` and `b_hh`. Default: ``True`` batch_first: If ``True``, then the input and output tensors are provided as `(batch, seq, feature)` instead of `(seq, batch, feature)`. Note that this does not apply to hidden or cell states. See the Inputs/Outputs sections below for details. Default: ``False`` dropout: If non-zero, introduces a `Dropout` layer on the outputs of each GRU layer except the last layer, with dropout probability equal to :attr:`dropout`. Default: 0 bidirectional: If ``True``, becomes a bidirectional GRU. Default: ``False`` Inputs: input, h_0 * **input**: tensor of shape :math:`(L, H_{in})` for unbatched input, :math:`(L, N, H_{in})` when ``batch_first=False`` or :math:`(N, L, H_{in})` when ``batch_first=True`` containing the features of the input sequence. The input can also be a packed variable length sequence. See :func:`torch.nn.utils.rnn.pack_padded_sequence` or :func:`torch.nn.utils.rnn.pack_sequence` for details. * **h_0**: tensor of shape :math:`(D * \text{num\_layers}, H_{out})` or :math:`(D * \text{num\_layers}, N, H_{out})` containing the initial hidden state for the input sequence. Defaults to zeros if not provided. where: .. math:: \begin{aligned} N ={} & \text{batch size} \\ L ={} & \text{sequence length} \\ D ={} & 2 \text{ if bidirectional=True otherwise } 1 \\ H_{in} ={} & \text{input\_size} \\ H_{out} ={} & \text{hidden\_size} \end{aligned} Outputs: output, h_n * **output**: tensor of shape :math:`(L, D * H_{out})` for unbatched input, :math:`(L, N, D * H_{out})` when ``batch_first=False`` or :math:`(N, L, D * H_{out})` when ``batch_first=True`` containing the output features `(h_t)` from the last layer of the GRU, for each `t`. If a :class:`torch.nn.utils.rnn.PackedSequence` has been given as the input, the output will also be a packed sequence. * **h_n**: tensor of shape :math:`(D * \text{num\_layers}, H_{out})` or :math:`(D * \text{num\_layers}, N, H_{out})` containing the final hidden state for the input sequence. Attributes: weight_ih_l[k] : the learnable input-hidden weights of the :math:`\text{k}^{th}` layer (W_ir|W_iz|W_in), of shape `(3*hidden_size, input_size)` for `k = 0`. Otherwise, the shape is `(3*hidden_size, num_directions * hidden_size)` weight_hh_l[k] : the learnable hidden-hidden weights of the :math:`\text{k}^{th}` layer (W_hr|W_hz|W_hn), of shape `(3*hidden_size, hidden_size)` bias_ih_l[k] : the learnable input-hidden bias of the :math:`\text{k}^{th}` layer (b_ir|b_iz|b_in), of shape `(3*hidden_size)` bias_hh_l[k] : the learnable hidden-hidden bias of the :math:`\text{k}^{th}` layer (b_hr|b_hz|b_hn), of shape `(3*hidden_size)` .. note:: All the weights and biases are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where :math:`k = \frac{1}{\text{hidden\_size}}` .. note:: For bidirectional GRUs, forward and backward are directions 0 and 1 respectively. Example of splitting the output layers when ``batch_first=False``: ``output.view(seq_len, batch, num_directions, hidden_size)``. .. note:: ``batch_first`` argument is ignored for unbatched inputs. .. note:: The calculation of new gate :math:`n_t` subtly differs from the original paper and other frameworks. In the original implementation, the Hadamard product :math:`(\odot)` between :math:`r_t` and the previous hidden state :math:`h_{(t-1)}` is done before the multiplication with the weight matrix `W` and addition of bias: .. math:: \begin{aligned} n_t = \tanh(W_{in} x_t + b_{in} + W_{hn} ( r_t \odot h_{(t-1)} ) + b_{hn}) \end{aligned} This is in contrast to PyTorch implementation, which is done after :math:`W_{hn} h_{(t-1)}` .. math:: \begin{aligned} n_t = \tanh(W_{in} x_t + b_{in} + r_t \odot (W_{hn} h_{(t-1)}+ b_{hn})) \end{aligned} This implementation differs on purpose for efficiency. .. include:: ../cudnn_persistent_rnn.rst Examples:: >>> rnn = nn.GRU(10, 20, 2) >>> input = torch.randn(5, 3, 10) >>> h0 = torch.randn(2, 3, 20) >>> output, hn = rnn(input, h0) """ @overload def __init__( self, input_size: int, hidden_size: int, num_layers: int = 1, bias: bool = True, batch_first: bool = False, dropout: float = 0.0, bidirectional: bool = False, device=None, dtype=None, ) -> None: ... @overload def __init__(self, *args, **kwargs) -> None: ... def __init__(self, *args, **kwargs): if "proj_size" in kwargs: raise ValueError( "proj_size argument is only supported for LSTM, not RNN or GRU" ) super().__init__("GRU", *args, **kwargs) @overload # type: ignore[override] @torch._jit_internal._overload_method # noqa: F811 def forward( self, input: Tensor, hx: Optional[Tensor] = None, ) -> tuple[Tensor, Tensor]: # noqa: F811 pass @overload @torch._jit_internal._overload_method # noqa: F811 def forward( self, input: PackedSequence, hx: Optional[Tensor] = None, ) -> tuple[PackedSequence, Tensor]: # noqa: F811 pass def forward(self, input, hx=None): # noqa: F811 self._update_flat_weights() orig_input = input # xxx: isinstance check needs to be in conditional for TorchScript to compile if isinstance(orig_input, PackedSequence): input, batch_sizes, sorted_indices, unsorted_indices = input max_batch_size = batch_sizes[0] if hx is None: num_directions = 2 if self.bidirectional else 1 hx = torch.zeros( self.num_layers * num_directions, max_batch_size, self.hidden_size, dtype=input.dtype, device=input.device, ) else: # Each batch of the hidden state should match the input sequence that # the user believes he/she is passing in. hx = self.permute_hidden(hx, sorted_indices) else: batch_sizes = None if input.dim() not in (2, 3): raise ValueError( f"GRU: Expected input to be 2D or 3D, got {input.dim()}D instead" ) is_batched = input.dim() == 3 batch_dim = 0 if self.batch_first else 1 if not is_batched: input = input.unsqueeze(batch_dim) if hx is not None: if hx.dim() != 2: raise RuntimeError( f"For unbatched 2-D input, hx should also be 2-D but got {hx.dim()}-D tensor" ) hx = hx.unsqueeze(1) else: if hx is not None and hx.dim() != 3: raise RuntimeError( f"For batched 3-D input, hx should also be 3-D but got {hx.dim()}-D tensor" ) max_batch_size = input.size(0) if self.batch_first else input.size(1) sorted_indices = None unsorted_indices = None if hx is None: num_directions = 2 if self.bidirectional else 1 hx = torch.zeros( self.num_layers * num_directions, max_batch_size, self.hidden_size, dtype=input.dtype, device=input.device, ) else: # Each batch of the hidden state should match the input sequence that # the user believes he/she is passing in. hx = self.permute_hidden(hx, sorted_indices) self.check_forward_args(input, hx, batch_sizes) if batch_sizes is None: result = _VF.gru( input, hx, self._flat_weights, # type: ignore[arg-type] self.bias, self.num_layers, self.dropout, self.training, self.bidirectional, self.batch_first, ) else: result = _VF.gru( input, batch_sizes, hx, self._flat_weights, # type: ignore[arg-type] self.bias, self.num_layers, self.dropout, self.training, self.bidirectional, ) output = result[0] hidden = result[1] # xxx: isinstance check needs to be in conditional for TorchScript to compile if isinstance(orig_input, PackedSequence): output_packed = PackedSequence( output, batch_sizes, sorted_indices, unsorted_indices, ) return output_packed, self.permute_hidden(hidden, unsorted_indices) else: if not is_batched: # type: ignore[possibly-undefined] output = output.squeeze(batch_dim) # type: ignore[possibly-undefined] hidden = hidden.squeeze(1) return output, self.permute_hidden(hidden, unsorted_indices)
GRU
python
plotly__plotly.py
plotly/graph_objs/indicator/number/_font.py
{ "start": 233, "end": 9890 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "indicator.number" _path_str = "indicator.number.font" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weight", } @property def color(self): """ The 'color' 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 Returns ------- str """ return self["color"] @color.setter def color(self, val): self["color"] = val @property def family(self): """ HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. The 'family' property is a string and must be specified as: - A non-empty string Returns ------- str """ return self["family"] @family.setter def family(self, val): self["family"] = val @property def lineposition(self): """ Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. The 'lineposition' property is a flaglist and may be specified as a string containing: - Any combination of ['under', 'over', 'through'] joined with '+' characters (e.g. 'under+over') OR exactly one of ['none'] (e.g. 'none') Returns ------- Any """ return self["lineposition"] @lineposition.setter def lineposition(self, val): self["lineposition"] = val @property def shadow(self): """ Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow for additional options. The 'shadow' property is a string and must be specified as: - A string - A number that will be converted to a string Returns ------- str """ return self["shadow"] @shadow.setter def shadow(self, val): self["shadow"] = val @property def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] Returns ------- int|float """ return self["size"] @size.setter def size(self, val): self["size"] = val @property def style(self): """ Sets whether a font should be styled with a normal or italic face from its family. The 'style' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'italic'] Returns ------- Any """ return self["style"] @style.setter def style(self, val): self["style"] = val @property def textcase(self): """ Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. The 'textcase' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'word caps', 'upper', 'lower'] Returns ------- Any """ return self["textcase"] @textcase.setter def textcase(self, val): self["textcase"] = val @property def variant(self): """ Sets the variant of the font. The 'variant' property is an enumeration that may be specified as: - One of the following enumeration values: ['normal', 'small-caps', 'all-small-caps', 'all-petite-caps', 'petite-caps', 'unicase'] Returns ------- Any """ return self["variant"] @variant.setter def variant(self, val): self["variant"] = val @property def weight(self): """ Sets the weight (or boldness) of the font. The 'weight' property is a integer and may be specified as: - An int (or float that will be cast to an int) in the interval [1, 1000] OR exactly one of ['normal', 'bold'] (e.g. 'bold') Returns ------- int """ return self["weight"] @weight.setter def weight(self, val): self["weight"] = val @property def _prop_descriptions(self): return """\ color family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. size style Sets whether a font should be styled with a normal or italic face from its family. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. variant Sets the variant of the font. weight Sets the weight (or boldness) of the font. """ def __init__( self, arg=None, color=None, family=None, lineposition=None, shadow=None, size=None, style=None, textcase=None, variant=None, weight=None, **kwargs, ): """ Construct a new Font object Set the font used to display main number Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.indicator.number.Font` color family HTML font family - the typeface that will be applied by the web browser. The web browser can only apply a font if it is available on the system where it runs. Provide multiple font families, separated by commas, to indicate the order in which to apply fonts if they aren't available. lineposition Sets the kind of decoration line(s) with text, such as an "under", "over" or "through" as well as combinations e.g. "under+over", etc. shadow Sets the shape and color of the shadow behind text. "auto" places minimal shadow and applies contrast text font color. See https://developer.mozilla.org/en- US/docs/Web/CSS/text-shadow for additional options. size style Sets whether a font should be styled with a normal or italic face from its family. textcase Sets capitalization of text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. variant Sets the variant of the font. weight Sets the weight (or boldness) of the font. Returns ------- Font """ super().__init__("font") 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.indicator.number.Font constructor must be a dict or an instance of :class:`plotly.graph_objs.indicator.number.Font`""") self._skip_invalid = kwargs.pop("skip_invalid", False) self._validate = kwargs.pop("_validate", True) self._set_property("color", arg, color) self._set_property("family", arg, family) self._set_property("lineposition", arg, lineposition) self._set_property("shadow", arg, shadow) self._set_property("size", arg, size) self._set_property("style", arg, style) self._set_property("textcase", arg, textcase) self._set_property("variant", arg, variant) self._set_property("weight", arg, weight) self._process_kwargs(**dict(arg, **kwargs)) self._skip_invalid = False
Font
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/orm/strategy_options.py
{ "start": 45935, "end": 52005 }
class ____(_AbstractLoad): """represent a standalone '*' load operation""" __slots__ = ("strategy", "path", "local_opts") _traverse_internals = [ ("strategy", visitors.ExtendedInternalTraversal.dp_plain_obj), ("path", visitors.ExtendedInternalTraversal.dp_plain_obj), ( "local_opts", visitors.ExtendedInternalTraversal.dp_string_multi_dict, ), ] cache_key_traversal: _CacheKeyTraversalType = None strategy: Optional[Tuple[Any, ...]] local_opts: _OptsType path: Union[Tuple[()], Tuple[str]] propagate_to_loaders = False def __init__(self) -> None: self.path = () self.strategy = None self.local_opts = util.EMPTY_DICT def _clone_for_bind_strategy( self, attrs, strategy, wildcard_key, opts=None, attr_group=None, propagate_to_loaders=True, reconcile_to_other=None, extra_criteria=None, ): assert attrs is not None attr = attrs[0] assert ( wildcard_key and isinstance(attr, str) and attr in (_WILDCARD_TOKEN, _DEFAULT_TOKEN) ) attr = f"{wildcard_key}:{attr}" self.strategy = strategy self.path = (attr,) if opts: self.local_opts = util.immutabledict(opts) assert extra_criteria is None def options(self, *opts: _AbstractLoad) -> Self: raise NotImplementedError("Star option does not support sub-options") def _apply_to_parent(self, parent: Load) -> None: """apply this :class:`_orm._WildcardLoad` object as a sub-option of a :class:`_orm.Load` object. This method is used by the :meth:`_orm.Load.options` method. Note that :class:`_orm.WildcardLoad` itself can't have sub-options, but it may be used as the sub-option of a :class:`_orm.Load` object. """ assert self.path attr = self.path[0] if attr.endswith(_DEFAULT_TOKEN): attr = f"{attr.split(':')[0]}:{_WILDCARD_TOKEN}" effective_path = cast(_AbstractEntityRegistry, parent.path).token(attr) assert effective_path.is_token loader = _TokenStrategyLoad.create( effective_path, None, self.strategy, None, self.local_opts, self.propagate_to_loaders, ) parent.context += (loader,) def _process(self, compile_state, mapper_entities, raiseerr): is_refresh = compile_state.compile_options._for_refresh_state if is_refresh and not self.propagate_to_loaders: return entities = [ent.entity_zero for ent in mapper_entities] current_path = compile_state.current_path start_path: _PathRepresentation = self.path if current_path: # TODO: no cases in test suite where we actually get # None back here new_path = self._chop_path(start_path, current_path) if new_path is None: return # chop_path does not actually "chop" a wildcard token path, # just returns it assert new_path == start_path # start_path is a single-token tuple assert start_path and len(start_path) == 1 token = start_path[0] assert isinstance(token, str) entity = self._find_entity_basestring(entities, token, raiseerr) if not entity: return path_element = entity # transfer our entity-less state into a Load() object # with a real entity path. Start with the lead entity # we just located, then go through the rest of our path # tokens and populate into the Load(). assert isinstance(token, str) loader = _TokenStrategyLoad.create( path_element._path_registry, token, self.strategy, None, self.local_opts, self.propagate_to_loaders, raiseerr=raiseerr, ) if not loader: return assert loader.path.is_token # don't pass a reconciled lead entity here loader.process_compile_state( self, compile_state, mapper_entities, None, raiseerr ) return loader def _find_entity_basestring( self, entities: Iterable[_InternalEntityType[Any]], token: str, raiseerr: bool, ) -> Optional[_InternalEntityType[Any]]: if token.endswith(f":{_WILDCARD_TOKEN}"): if len(list(entities)) != 1: if raiseerr: raise sa_exc.ArgumentError( "Can't apply wildcard ('*') or load_only() " f"loader option to multiple entities " f"{', '.join(str(ent) for ent in entities)}. Specify " "loader options for each entity individually, such as " f"""{ ", ".join( f"Load({ent}).some_option('*')" for ent in entities ) }.""" ) elif token.endswith(_DEFAULT_TOKEN): raiseerr = False for ent in entities: # return only the first _MapperEntity when searching # based on string prop name. Ideally object # attributes are used to specify more exactly. return ent else: if raiseerr: raise sa_exc.ArgumentError( "Query has only expression-based entities - " f'can\'t find property named "{token}".' ) else: return None def __getstate__(self) -> Dict[str, Any]: d = self._shallow_to_dict() return d def __setstate__(self, state: Dict[str, Any]) -> None: self._shallow_from_dict(state)
_WildcardLoad
python
openai__openai-python
src/openai/types/beta/threads/message_delta.py
{ "start": 279, "end": 570 }
class ____(BaseModel): content: Optional[List[MessageContentDelta]] = None """The content of the message in array of text and/or images.""" role: Optional[Literal["user", "assistant"]] = None """The entity that produced the message. One of `user` or `assistant`."""
MessageDelta
python
facebook__pyre-check
tools/generate_taint_models/model.py
{ "start": 12229, "end": 12771 }
class ____(Model): class_name: str annotation: str def __init__(self, class_name: str, annotation: str) -> None: self.class_name = class_name self.annotation = annotation def __str__(self) -> str: return f"class {self.class_name}({self.annotation}): ..." def __eq__(self, other: object) -> bool: if not isinstance(other, ClassModel): return False return self.class_name == other.class_name def __hash__(self) -> int: return hash(self.class_name)
ClassModel
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-pathway/llama_index/readers/pathway/base.py
{ "start": 3476, "end": 4951 }
class ____(BaseReader): """ Pathway reader. Retrieve documents from Pathway data indexing pipeline. Args: host (str): The URI where Pathway is currently hosted. port (str | int): The port number on which Pathway is listening. See Also: llamaindex.retriever.pathway.PathwayRetriever and, llamaindex.retriever.pathway.PathwayVectorServer """ def __init__( self, host: Optional[str] = None, port: Optional[int] = None, url: Optional[str] = None, ): """Initializing the Pathway reader client.""" self.client = _VectorStoreClient(host, port, url) def load_data( self, query_text: str, k: Optional[int] = 4, metadata_filter: Optional[str] = None, ) -> List[Document]: """ Load data from Pathway. Args: query_text (str): The text to get the closest neighbors of. k (int): Number of results to return. metadata_filter (str): Filter to be applied. Returns: List[Document]: A list of documents. """ results = self.client(query_text, k, metadata_filter) documents = [] for return_elem in results: document = Document( text=return_elem["text"], extra_info=return_elem["metadata"], ) documents.append(document) return documents
PathwayReader
python
realpython__materials
python-enum/semaphore.py
{ "start": 24, "end": 665 }
class ____(Enum): RED = 1 YELLOW = 2 GREEN = 3 # def handle_semaphore(light): # if light is Semaphore.RED: # print("You must stop!") # elif light is Semaphore.YELLOW: # print("Light will change to red, be careful!") # elif light is Semaphore.GREEN: # print("You can continue!") def handle_semaphore(light): match light: case Semaphore.RED: print("You must stop!") case Semaphore.YELLOW: print("Light will change to red, be careful!") case Semaphore.GREEN: print("You can continue!") handle_semaphore(Semaphore.YELLOW)
Semaphore
python
tornadoweb__tornado
tornado/test/util_test.py
{ "start": 9001, "end": 9670 }
class ____(unittest.TestCase): def test_import_member(self): self.assertIs(import_object("tornado.escape.utf8"), utf8) def test_import_member_unicode(self): self.assertIs(import_object("tornado.escape.utf8"), utf8) def test_import_module(self): self.assertIs(import_object("tornado.escape"), tornado.escape) def test_import_module_unicode(self): # The internal implementation of __import__ differs depending on # whether the thing being imported is a module or not. # This variant requires a byte string in python 2. self.assertIs(import_object("tornado.escape"), tornado.escape)
ImportObjectTest
python
h5py__h5py
h5py/tests/test_file.py
{ "start": 24369, "end": 25059 }
class ____(TestCase): """ Feature: Files can be closed """ def test_close(self): """ Close file via .close method """ fid = File(self.mktemp(), 'w') self.assertTrue(fid) fid.close() self.assertFalse(fid) def test_closed_file(self): """ Trying to modify closed file raises ValueError """ fid = File(self.mktemp(), 'w') fid.close() with self.assertRaises(ValueError): fid.create_group('foo') def test_close_multiple_default_driver(self): fname = self.mktemp() f = h5py.File(fname, 'w') f.create_group("test") f.close() f.close()
TestClose
python
apache__airflow
task-sdk/tests/task_sdk/definitions/test_callback.py
{ "start": 6717, "end": 8030 }
class ____: @pytest.mark.parametrize( ("callback_callable", "kwargs", "expected_path"), [ pytest.param( empty_async_callback_for_deadline_tests, TEST_CALLBACK_KWARGS, TEST_CALLBACK_PATH, id="callable", ), pytest.param(TEST_CALLBACK_PATH, TEST_CALLBACK_KWARGS, TEST_CALLBACK_PATH, id="string_path"), pytest.param( UNIMPORTABLE_DOT_PATH, TEST_CALLBACK_KWARGS, UNIMPORTABLE_DOT_PATH, id="unimportable_path" ), ], ) def test_init(self, callback_callable, kwargs, expected_path): callback = AsyncCallback(callback_callable, kwargs=kwargs) assert callback.path == expected_path assert callback.kwargs == kwargs assert isinstance(callback, Callback) def test_init_error(self): with pytest.raises(AttributeError, match="is not awaitable."): AsyncCallback(empty_sync_callback_for_deadline_tests) def test_serialize_deserialize(self): callback = AsyncCallback(TEST_CALLBACK_PATH, kwargs=TEST_CALLBACK_KWARGS) serialized = serialize(callback) deserialized = cast("Callback", deserialize(serialized.copy())) assert callback == deserialized
TestAsyncCallback
python
airbytehq__airbyte
airbyte-integrations/connectors/source-microsoft-onedrive/source_microsoft_onedrive/source.py
{ "start": 571, "end": 3152 }
class ____(FileBasedSource): def __init__(self, catalog: Optional[ConfiguredAirbyteCatalog], config: Optional[Mapping[str, Any]], state: Optional[TState]): super().__init__( stream_reader=SourceMicrosoftOneDriveStreamReader(), spec_class=SourceMicrosoftOneDriveSpec, catalog=catalog, config=config, state=state, cursor_cls=DefaultFileBasedCursor, ) def spec(self, *args: Any, **kwargs: Any) -> ConnectorSpecification: """ Returns the specification describing what fields can be configured by a user when setting up a file-based source. """ return ConnectorSpecification( documentationUrl=self.spec_class.documentation_url(), connectionSpecification=self.spec_class.schema(), advanced_auth=AdvancedAuth( auth_flow_type="oauth2.0", predicate_key=["credentials", "auth_type"], predicate_value="Client", oauth_config_specification=OAuthConfigSpecification( complete_oauth_output_specification={ "type": "object", "additionalProperties": False, "properties": {"refresh_token": {"type": "string", "path_in_connector_config": ["credentials", "refresh_token"]}}, }, complete_oauth_server_input_specification={ "type": "object", "additionalProperties": False, "properties": {"client_id": {"type": "string"}, "client_secret": {"type": "string"}}, }, complete_oauth_server_output_specification={ "type": "object", "additionalProperties": False, "properties": { "client_id": {"type": "string", "path_in_connector_config": ["credentials", "client_id"]}, "client_secret": {"type": "string", "path_in_connector_config": ["credentials", "client_secret"]}, }, }, oauth_user_input_from_connector_config_specification={ "type": "object", "additionalProperties": False, "properties": {"tenant_id": {"type": "string", "path_in_connector_config": ["credentials", "tenant_id"]}}, }, ), ), )
SourceMicrosoftOneDrive
python
apache__airflow
airflow-core/tests/unit/models/test_dag.py
{ "start": 113688, "end": 139405 }
class ____: """ Task clearing behavior is mainly controlled by dag.partial_subset. Here we verify, primarily with regard to setups and teardowns, the behavior of dag.partial_subset but also the supporting methods defined on AbstractOperator. """ @staticmethod def make_tasks(dag, input_str): """ Helper for building setup and teardown tasks for testing. Given an input such as 's1, w1, t1, tf1', returns setup task "s1", normal task "w1" (the w means *work*), teardown task "t1", and teardown task "tf1" where the f means on_failure_fail_dagrun has been set to true. """ def teardown_task(task_id): return BaseOperator(task_id=task_id).as_teardown() def teardown_task_f(task_id): return BaseOperator(task_id=task_id).as_teardown(on_failure_fail_dagrun=True) def work_task(task_id): return BaseOperator(task_id=task_id) def setup_task(task_id): return BaseOperator(task_id=task_id).as_setup() def make_task(task_id): """ Task factory helper. Will give a setup, teardown, work, or teardown-with-dagrun-failure task depending on input. """ if task_id.startswith("s"): factory = setup_task elif task_id.startswith("w"): factory = work_task elif task_id.startswith("tf"): factory = teardown_task_f elif task_id.startswith("t"): factory = teardown_task else: raise ValueError("unexpected") return dag.task_dict.get(task_id) or factory(task_id=task_id) return (make_task(x) for x in input_str.split(", ")) @staticmethod def cleared_downstream(task): """Helper to return tasks that would be cleared if **downstream** selected.""" upstream = False return set( task.dag.partial_subset( task_ids=[task.task_id], include_downstream=not upstream, include_upstream=upstream, ).tasks ) @staticmethod def cleared_upstream(task): """Helper to return tasks that would be cleared if **upstream** selected.""" upstream = True return set( task.dag.partial_subset( task_ids=task.task_id, include_downstream=not upstream, include_upstream=upstream, ).tasks ) @staticmethod def cleared_neither(task): """Helper to return tasks that would be cleared if **upstream** selected.""" return set( task.dag.partial_subset( task_ids=[task.task_id], include_downstream=False, include_upstream=False, ).tasks ) def test_get_flat_relative_ids_with_setup(self): with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1, w1, w2, w3, w4, t1 = self.make_tasks(dag, "s1, w1, w2, w3, w4, t1") s1 >> w1 >> w2 >> w3 # w1 is downstream of s1, and s1 has no teardown, so clearing w1 clears s1 assert set(w1.get_upstreams_only_setups_and_teardowns()) == {s1} # same with w2 and w3 assert set(w2.get_upstreams_only_setups_and_teardowns()) == {s1} assert set(w3.get_upstreams_only_setups_and_teardowns()) == {s1} # so if we clear w2, we should also get s1, and w3, but not w1 assert self.cleared_downstream(w2) == {s1, w2, w3} w3 >> t1 # now, w2 has a downstream teardown, but it's not connected directly to s1 assert set(w2.get_upstreams_only_setups_and_teardowns()) == {s1} # so if we clear downstream then s1 will be cleared, and t1 will be cleared but only by virtue of # being downstream of w2 -- not as a result of being the teardown for s1, which it ain't assert self.cleared_downstream(w2) == {s1, w2, w3, t1} # and, another consequence of not linking s1 and t1 is that when we clear upstream, note that # t1 doesn't get cleared -- cus it's not upstream and it's not linked to s1 assert self.cleared_upstream(w2) == {s1, w1, w2} # note also that if we add a 4th work task after t1, it will still be "in scope" for s1 t1 >> w4 assert self.cleared_downstream(w4) == {s1, w4} s1 >> t1 # now, we know that t1 is the teardown for s1, so now we know that s1 will be "torn down" # by the time w4 runs, so we now know that w4 no longer requires s1, so when we clear w4, # s1 will not also be cleared self.cleared_downstream(w4) == {w4} assert set(w1.get_upstreams_only_setups_and_teardowns()) == {s1, t1} assert self.cleared_downstream(w1) == {s1, w1, w2, w3, t1, w4} assert self.cleared_upstream(w1) == {s1, w1, t1} assert set(w2.get_upstreams_only_setups_and_teardowns()) == {s1, t1} assert set(w2.get_upstreams_follow_setups()) == {s1, w1, t1} assert self.cleared_downstream(w2) == {s1, w2, w3, t1, w4} assert self.cleared_upstream(w2) == {s1, w1, w2, t1} assert self.cleared_downstream(w3) == {s1, w3, t1, w4} assert self.cleared_upstream(w3) == {s1, w1, w2, w3, t1} def test_get_flat_relative_ids_with_setup_nested_ctx_mgr(self): """Let's test some gnarlier cases here""" with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1, t1, s2, t2 = self.make_tasks(dag, "s1, t1, s2, t2") with s1 >> t1: BaseOperator(task_id="w1") with s2 >> t2: BaseOperator(task_id="w2") BaseOperator(task_id="w3") # to_do: implement tests def test_get_flat_relative_ids_with_setup_nested_no_ctx_mgr(self): """Let's test some gnarlier cases here""" with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1, t1, s2, t2, w1, w2, w3 = self.make_tasks(dag, "s1, t1, s2, t2, w1, w2, w3") s1 >> t1 s1 >> w1 >> t1 s1 >> s2 s2 >> t2 s2 >> w2 >> w3 >> t2 assert w1.get_flat_relative_ids(upstream=True) == {"s1"} assert w1.get_flat_relative_ids(upstream=False) == {"t1"} assert self.cleared_downstream(w1) == {s1, w1, t1} assert self.cleared_upstream(w1) == {s1, w1, t1} assert w3.get_flat_relative_ids(upstream=True) == {"s1", "s2", "w2"} assert w3.get_flat_relative_ids(upstream=False) == {"t2"} assert t1 not in w2.get_flat_relatives(upstream=False) # t1 not required by w2 # t1 only included because s1 is upstream assert self.cleared_upstream(w2) == {s1, t1, s2, w2, t2} # t1 not included because t1 is not downstream assert self.cleared_downstream(w2) == {s2, w2, w3, t2} # t1 only included because s1 is upstream assert self.cleared_upstream(w3) == {s1, t1, s2, w2, w3, t2} # t1 not included because t1 is not downstream assert self.cleared_downstream(w3) == {s2, w3, t2} def test_get_flat_relative_ids_follows_teardowns(self): with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1, w1, w2, t1 = self.make_tasks(dag, "s1, w1, w2, t1") s1 >> w1 >> [w2, t1] s1 >> t1 # w2, we infer, does not require s1, since t1 does not come after it assert set(w2.get_upstreams_only_setups_and_teardowns()) == set() # w1, however, *does* require s1, since t1 is downstream of it assert set(w1.get_upstreams_only_setups_and_teardowns()) == {s1, t1} # downstream is just downstream and includes teardowns assert self.cleared_downstream(w1) == {s1, w1, w2, t1} assert self.cleared_downstream(w2) == {w2} # and if there's a downstream setup, it will be included as well s2 = BaseOperator(task_id="s2", dag=dag).as_setup() t1 >> s2 assert w1.get_flat_relative_ids(upstream=False) == {"t1", "w2", "s2"} assert self.cleared_downstream(w1) == {s1, w1, w2, t1, s2} def test_get_flat_relative_ids_two_tasks_diff_setup_teardowns(self): with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1, t1, s2, t2, w1, w2 = self.make_tasks(dag, "s1, t1, s2, t2, w1, w2") s1 >> w1 >> [w2, t1] s1 >> t1 s2 >> t2 s2 >> w2 >> t2 assert set(w1.get_upstreams_only_setups_and_teardowns()) == {s1, t1} # s2 is included because w2 is included assert self.cleared_downstream(w1) == {s1, w1, t1, s2, w2, t2} assert self.cleared_neither(w1) == {s1, w1, t1} assert set(w2.get_upstreams_only_setups_and_teardowns()) == {s2, t2} assert self.cleared_downstream(w2) == {s2, w2, t2} def test_get_flat_relative_ids_one_task_multiple_setup_teardowns(self): with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1a, s1b, t1, s2, t2, s3, t3a, t3b, w1, w2 = self.make_tasks( dag, "s1a, s1b, t1, s2, t2, s3, t3a, t3b, w1, w2" ) # teardown t1 has two setups, s1a and s1b [s1a, s1b] >> t1 # work 1 requires s1a and s1b, both of which are torn down by t1 [s1a, s1b] >> w1 >> [w2, t1] # work 2 requires s2, and s3. s2 is torn down by t2. s3 is torn down by two teardowns, t3a and t3b. s2 >> t2 s2 >> w2 >> t2 s3 >> w2 >> [t3a, t3b] s3 >> [t3a, t3b] assert set(w1.get_upstreams_only_setups_and_teardowns()) == {s1a, s1b, t1} # since w2 is downstream of w1, w2 gets cleared. # and since w2 gets cleared, we should also see s2 and s3 in here assert self.cleared_downstream(w1) == {s1a, s1b, w1, t1, s3, t3a, t3b, w2, s2, t2} assert set(w2.get_upstreams_only_setups_and_teardowns()) == {s2, t2, s3, t3a, t3b} assert self.cleared_downstream(w2) == {s2, s3, w2, t2, t3a, t3b} def test_get_flat_relative_ids_with_setup_and_groups(self): """ This is a dag with a setup / teardown at dag level and two task groups that have their own setups / teardowns. When we do tg >> dag_teardown, teardowns should be excluded from tg leaves. """ dag = DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) with dag: dag_setup = BaseOperator(task_id="dag_setup").as_setup() dag_teardown = BaseOperator(task_id="dag_teardown").as_teardown() dag_setup >> dag_teardown for group_name in ("g1", "g2"): with TaskGroup(group_name) as tg: group_setup = BaseOperator(task_id="group_setup").as_setup() w1 = BaseOperator(task_id="w1") w2 = BaseOperator(task_id="w2") w3 = BaseOperator(task_id="w3") group_teardown = BaseOperator(task_id="group_teardown").as_teardown() group_setup >> w1 >> w2 >> w3 >> group_teardown group_setup >> group_teardown dag_setup >> tg >> dag_teardown g2_w2 = dag.task_dict["g2.w2"] g2_w3 = dag.task_dict["g2.w3"] g2_group_teardown = dag.task_dict["g2.group_teardown"] # the line `dag_setup >> tg >> dag_teardown` should be equivalent to # dag_setup >> group_setup; w3 >> dag_teardown # i.e. not group_teardown >> dag_teardown # this way the two teardowns can run in parallel # so first, check that dag_teardown not downstream of group 2 teardown # this means they can run in parallel assert "dag_teardown" not in g2_group_teardown.downstream_task_ids # and just document that g2 teardown is in effect a dag leaf assert g2_group_teardown.downstream_task_ids == set() # group 2 task w3 is in the scope of 2 teardowns -- the dag teardown and the group teardown # it is arrowed to both of them assert g2_w3.downstream_task_ids == {"g2.group_teardown", "dag_teardown"} # dag teardown should have 3 upstreams: the last work task in groups 1 and 2, and its setup assert dag_teardown.upstream_task_ids == {"g1.w3", "g2.w3", "dag_setup"} assert {x.task_id for x in g2_w2.get_upstreams_only_setups_and_teardowns()} == { "dag_setup", "dag_teardown", "g2.group_setup", "g2.group_teardown", } # clearing g2.w2 clears all setups and teardowns and g2.w2 and g2.w2 # but not anything from g1 assert {x.task_id for x in self.cleared_downstream(g2_w2)} == { "dag_setup", "dag_teardown", "g2.group_setup", "g2.group_teardown", "g2.w3", "g2.w2", } assert {x.task_id for x in self.cleared_upstream(g2_w2)} == { "dag_setup", "dag_teardown", "g2.group_setup", "g2.group_teardown", "g2.w1", "g2.w2", } def test_clear_upstream_not_your_setup(self): """ When you have a work task that comes after a setup, then if you clear upstream the setup (and its teardown) will be cleared even though strictly speaking you don't "require" it since, depending on speed of execution, it might be torn down by t1 before / while w2 runs. It just gets cleared by virtue of it being upstream, and that's what you requested. And its teardown gets cleared too. But w1 doesn't. """ with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1, w1, w2, t1 = self.make_tasks(dag, "s1, w1, w2, t1") s1 >> w1 >> t1.as_teardown(setups=s1) s1 >> w2 # w2 is downstream of s1, so when clearing upstream, it should clear s1 (since it # is upstream of w2) and t1 since it's the teardown for s1 even though not downstream of w1 assert self.cleared_upstream(w2) == {s1, w2, t1} def test_clearing_teardown_no_clear_setup(self): with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1, w1, t1 = self.make_tasks(dag, "s1, w1, t1") s1 >> t1 # clearing t1 does not clear s1 assert self.cleared_downstream(t1) == {t1} s1 >> w1 >> t1 # that isn't changed with the introduction of w1 assert self.cleared_downstream(t1) == {t1} # though, of course, clearing w1 clears them all assert self.cleared_downstream(w1) == {s1, w1, t1} def test_clearing_setup_clears_teardown(self): with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1, w1, t1 = self.make_tasks(dag, "s1, w1, t1") s1 >> t1 s1 >> w1 >> t1 # clearing w1 clears all always assert self.cleared_upstream(w1) == {s1, w1, t1} assert self.cleared_downstream(w1) == {s1, w1, t1} assert self.cleared_neither(w1) == {s1, w1, t1} # clearing s1 clears t1 always assert self.cleared_upstream(s1) == {s1, t1} assert self.cleared_downstream(s1) == {s1, w1, t1} assert self.cleared_neither(s1) == {s1, t1} @pytest.mark.parametrize( ("upstream", "downstream", "expected"), [ (False, False, {"my_teardown", "my_setup"}), (False, True, {"my_setup", "my_work", "my_teardown"}), (True, False, {"my_teardown", "my_setup"}), (True, True, {"my_setup", "my_work", "my_teardown"}), ], ) def test_clearing_setup_clears_teardown_taskflow(self, upstream, downstream, expected): with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: @setup def my_setup(): ... @task_decorator def my_work(): ... @teardown def my_teardown(): ... s1 = my_setup() w1 = my_work() t1 = my_teardown() s1 >> w1 >> t1 s1 >> t1 assert { x.task_id for x in dag.partial_subset( "my_setup", include_upstream=upstream, include_downstream=downstream ).tasks } == expected def test_get_flat_relative_ids_two_tasks_diff_setup_teardowns_deeper(self): with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1, t1, s2, t2, w1, w2, s3, w3, t3 = self.make_tasks(dag, "s1, t1, s2, t2, w1, w2, s3, w3, t3") s1 >> w1 >> t1 s1 >> t1 w1 >> w2 # with the below, s2 is not downstream of w1, but it's the setup for w2 # so it should be cleared when w1 is cleared s2 >> w2 >> t2 s2 >> t2 assert set(w1.get_upstreams_only_setups_and_teardowns()) == {s1, t1} assert set(w2.get_upstreams_only_setups_and_teardowns()) == {s2, t2} assert self.cleared_downstream(w1) == {s1, w1, t1, s2, w2, t2} assert self.cleared_downstream(w2) == {s2, w2, t2} # now, what if s2 itself has a setup and teardown? s3 >> s2 >> t3 s3 >> t3 # note that s3 is excluded because it's assumed that a setup won't have a setup # so, we don't continue to recurse for setups after reaching the setups for # the downstream work tasks # but, t3 is included since it's a teardown for s2 assert self.cleared_downstream(w1) == {s1, w1, t1, s2, w2, t2, t3} def test_clearing_behavior_multiple_setups_for_work_task(self): with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1, t1, s2, t2, w1, w2, s3, w3, t3 = self.make_tasks(dag, "s1, t1, s2, t2, w1, w2, s3, w3, t3") s1 >> t1 s2 >> t2 s3 >> t3 s1 >> s2 >> s3 >> w1 >> w2 >> [t1, t2, t3] assert self.cleared_downstream(w1) == {s1, s2, s3, w1, w2, t1, t2, t3} assert self.cleared_downstream(w2) == {s1, s2, s3, w2, t1, t2, t3} assert self.cleared_downstream(s3) == {s1, s2, s3, w1, w2, t1, t2, t3} # even if we don't include upstream / downstream, setups and teardowns are cleared assert self.cleared_neither(w2) == {s3, t3, s2, t2, s1, t1, w2} assert self.cleared_neither(w1) == {s3, t3, s2, t2, s1, t1, w1} # but, a setup doesn't formally have a setup, so if we only clear s3, say then its upstream setups # are not also cleared assert self.cleared_neither(s3) == {s3, t3} assert self.cleared_neither(s2) == {s2, t2} def test_clearing_behavior_multiple_setups_for_work_task2(self): with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1, t1, s2, t2, w1, w2, s3, w3, t3 = self.make_tasks(dag, "s1, t1, s2, t2, w1, w2, s3, w3, t3") s1 >> t1 s2 >> t2 s3 >> t3 [s1, s2, s3] >> w1 >> w2 >> [t1, t2, t3] assert self.cleared_downstream(w1) == {s1, s2, s3, w1, w2, t1, t2, t3} assert self.cleared_downstream(w2) == {s1, s2, s3, w2, t1, t2, t3} def test_clearing_behavior_more_tertiary_weirdness(self): with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1, t1, s2, t2, w1, w2, s3, t3 = self.make_tasks(dag, "s1, t1, s2, t2, w1, w2, s3, t3") s1 >> t1 s2 >> t2 s1 >> w1 >> s2 >> w2 >> [t1, t2] s2 >> w2 >> t2 s3 >> s2 >> t3 s3 >> t3 def sort(task_list): return sorted(x.task_id for x in task_list) assert set(w1.get_upstreams_only_setups_and_teardowns()) == {s1, t1} # s2 is included because w2 is included assert self.cleared_downstream(w1) == {s1, w1, t1, s2, w2, t2, t3} assert self.cleared_downstream(w2) == {s1, t1, s2, w2, t2, t3} # t3 is included since s2 is included and s2 >> t3 # but s3 not included because it's assumed that a setup doesn't have a setup assert self.cleared_neither(w2) == {s1, w2, t1, s2, t2, t3} # since we're clearing upstream, s3 is upstream of w2, so s3 and t3 are included # even though w2 doesn't require them # s2 and t2 are included for obvious reasons, namely that w2 requires s2 # and s1 and t1 are included for the same reason # w1 included since it is upstream of w2 assert sort(self.cleared_upstream(w2)) == sort({s1, t1, s2, t2, s3, t3, w1, w2}) # t3 is included here since it's a teardown for s2 assert set(w2.get_upstreams_only_setups_and_teardowns()) == {s2, t2, s1, t1, t3} def test_clearing_behavior_more_tertiary_weirdness2(self): with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1, t1, s2, t2, w1, w2, s3, t3 = self.make_tasks(dag, "s1, t1, s2, t2, w1, w2, s3, t3") s1 >> t1 s2 >> t2 s1 >> w1 >> t1 s2 >> t1 >> t2 def sort(task_list): return sorted(x.task_id for x in task_list) # t2 included since downstream, but s2 not included since it's not required by t2 # and clearing teardown does not clear the setup assert self.cleared_downstream(w1) == {s1, w1, t1, t2} # even though t1 is cleared here, s2 and t2 are not "setup and teardown" for t1 # so they are not included assert self.cleared_neither(w1) == {s1, w1, t1} assert self.cleared_upstream(w1) == {s1, w1, t1} # t1 does not have a setup or teardown # but t2 is downstream so it's included # and s2 is not included since clearing teardown does not clear the setup assert self.cleared_downstream(t1) == {t1, t2} # t1 does not have a setup or teardown assert self.cleared_neither(t1) == {t1} # s2 included since upstream, and t2 included since s2 included assert self.cleared_upstream(t1) == {s1, t1, s2, t2, w1} def test_clearing_behavior_just_teardown(self): with DAG(dag_id="test_dag", schedule=None, start_date=pendulum.now()) as dag: s1, t1 = self.make_tasks(dag, "s1, t1") s1 >> t1 assert set(t1.get_upstreams_only_setups_and_teardowns()) == set() assert self.cleared_upstream(t1) == {s1, t1} assert self.cleared_downstream(t1) == {t1} assert self.cleared_neither(t1) == {t1} assert set(s1.get_upstreams_only_setups_and_teardowns()) == set() assert self.cleared_upstream(s1) == {s1, t1} assert self.cleared_downstream(s1) == {s1, t1} assert self.cleared_neither(s1) == {s1, t1} def test_validate_setup_teardown_trigger_rule(self): with DAG( dag_id="direct_setup_trigger_rule", start_date=pendulum.now(), schedule=None, catchup=False ) as dag: s1, w1 = self.make_tasks(dag, "s1, w1") s1 >> w1 dag.validate_setup_teardown() w1.trigger_rule = TriggerRule.ONE_FAILED with pytest.raises( Exception, match="Setup tasks must be followed with trigger rule ALL_SUCCESS." ): dag.validate_setup_teardown() @pytest.mark.parametrize( ("disable", "bundle_version", "expected"), [ (True, "some-version", None), (False, "some-version", "some-version"), ], ) def test_disable_bundle_versioning(disable, bundle_version, expected, dag_maker, session, clear_dags): """When bundle versioning is disabled for a dag, the dag run should not have a bundle version.""" def hello(): print("hello") with dag_maker(disable_bundle_versioning=disable, session=session, serialized=True) as dag: PythonOperator(task_id="hi", python_callable=hello) assert dag.disable_bundle_versioning is disable # the dag *always* has bundle version dag_model = session.scalar(select(DagModel).where(DagModel.dag_id == dag.dag_id)) dag_model.bundle_version = bundle_version session.commit() dr = dag.create_dagrun( run_id="abcoercuhcrh", run_after=pendulum.now(), run_type="manual", triggered_by=DagRunTriggeredByType.TEST, state=None, ) # but it only gets stamped on the dag run when bundle versioning not disabled assert dr.bundle_version == expected def test_get_run_data_interval(): with DAG("dag", schedule=None, start_date=DEFAULT_DATE) as dag: EmptyOperator(task_id="empty_task") dr = _create_dagrun( dag, logical_date=timezone.utcnow(), data_interval=(DEFAULT_DATE, DEFAULT_DATE), run_type=DagRunType.MANUAL, ) assert get_run_data_interval(dag.timetable, dr) == DataInterval(start=DEFAULT_DATE, end=DEFAULT_DATE) def test_get_run_data_interval_pre_aip_39(): with DAG( "dag", schedule="0 0 * * *", start_date=DEFAULT_DATE, ) as dag: EmptyOperator(task_id="empty_task") current_ts = timezone.utcnow() dr = _create_dagrun( dag, logical_date=current_ts, data_interval=(None, None), run_type=DagRunType.MANUAL, ) ds_start = current_ts.replace(hour=0, minute=0, second=0, microsecond=0) - timedelta(days=1) ds_end = current_ts.replace(hour=0, minute=0, second=0, microsecond=0) assert get_run_data_interval(dag.timetable, dr) == DataInterval(start=ds_start, end=ds_end)
TestTaskClearingSetupTeardownBehavior
python
getsentry__sentry
src/sentry/incidents/endpoints/organization_incident_details.py
{ "start": 775, "end": 1301 }
class ____(serializers.Serializer): status = serializers.IntegerField() comment = serializers.CharField(required=False, allow_null=True) def validate_status(self, value): try: value = IncidentStatus(value) except Exception: raise serializers.ValidationError( "Invalid value for status. Valid values: {}".format( [e.value for e in IncidentStatus] ) ) return value @region_silo_endpoint
IncidentSerializer
python
huggingface__transformers
src/transformers/models/mistral3/modeling_mistral3.py
{ "start": 1779, "end": 2508 }
class ____(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ Mistral3RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype) def extra_repr(self): return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
Mistral3RMSNorm
python
bokeh__bokeh
tests/unit/bokeh/core/property/test_constraints.py
{ "start": 1247, "end": 1285 }
class ____(Child0, Local): pass
Child1
python
huggingface__transformers
setup.py
{ "start": 7844, "end": 16390 }
class ____(Command): """ A custom distutils command that updates the dependency table. usage: python setup.py deps_table_update """ description = "build runtime dependency table" user_options = [ # format: (long option, short option, description). ("dep-table-update", None, "updates src/transformers/dependency_versions_table.py"), ] def initialize_options(self): pass def finalize_options(self): pass def run(self): entries = "\n".join([f' "{k}": "{v}",' for k, v in deps.items()]) content = [ "# THIS FILE HAS BEEN AUTOGENERATED. To update:", "# 1. modify the `_deps` dict in setup.py", "# 2. run `make deps_table_update``", "deps = {", entries, "}", "", ] target = "src/transformers/dependency_versions_table.py" print(f"updating {target}") with open(target, "w", encoding="utf-8", newline="\n") as f: f.write("\n".join(content)) extras = {} extras["ja"] = deps_list("fugashi", "ipadic", "unidic_lite", "unidic", "sudachipy", "sudachidict_core", "rhoknp") extras["sklearn"] = deps_list("scikit-learn") extras["torch"] = deps_list("torch", "accelerate") extras["accelerate"] = deps_list("accelerate") extras["hf_xet"] = deps_list("hf_xet") extras["retrieval"] = deps_list("faiss-cpu", "datasets") extras["tokenizers"] = deps_list("tokenizers") extras["ftfy"] = deps_list("ftfy") extras["modelcreation"] = deps_list("cookiecutter") extras["sagemaker"] = deps_list("sagemaker") extras["deepspeed"] = deps_list("deepspeed") + extras["accelerate"] extras["optuna"] = deps_list("optuna") extras["ray"] = deps_list("ray[tune]") extras["hub-kernels"] = deps_list("kernels") extras["integrations"] = extras["hub-kernels"] + extras["optuna"] + extras["ray"] extras["serving"] = deps_list("openai", "pydantic", "uvicorn", "fastapi", "starlette", "rich") + extras["torch"] extras["audio"] = deps_list( "librosa", "pyctcdecode", "phonemizer", "kenlm", ) # `pip install ".[speech]"` is deprecated and `pip install ".[torch-speech]"` should be used instead extras["speech"] = deps_list("torchaudio") + extras["audio"] extras["torch-speech"] = deps_list("torchaudio") + extras["audio"] extras["vision"] = deps_list("Pillow") extras["timm"] = deps_list("timm") extras["torch-vision"] = deps_list("torchvision") + extras["vision"] extras["natten"] = deps_list("natten") extras["codecarbon"] = deps_list("codecarbon") extras["video"] = deps_list("av") extras["num2words"] = deps_list("num2words") extras["sentencepiece"] = deps_list("sentencepiece", "protobuf") extras["tiktoken"] = deps_list("tiktoken", "blobfile") extras["mistral-common"] = deps_list("mistral-common[opencv]") extras["chat_template"] = deps_list("jinja2", "jmespath") extras["testing"] = ( deps_list( "pytest", "pytest-asyncio", "pytest-rich", "pytest-xdist", "pytest-order", "pytest-rerunfailures", "timeout-decorator", "parameterized", "psutil", "datasets", "dill", "evaluate", "pytest-timeout", "ruff", "rouge-score", "nltk", "GitPython", "sacremoses", "rjieba", "beautifulsoup4", "tensorboard", "pydantic", "sentencepiece", "sacrebleu", # needed in trainer tests, see references to `run_translation.py` "libcst", ) + extras["retrieval"] + extras["modelcreation"] + extras["mistral-common"] + extras["serving"] ) extras["deepspeed-testing"] = extras["deepspeed"] + extras["testing"] + extras["optuna"] + extras["sentencepiece"] extras["ruff"] = deps_list("ruff") extras["quality"] = deps_list("datasets", "ruff", "GitPython", "urllib3", "libcst", "rich", "pandas") extras["all"] = ( extras["torch"] + extras["sentencepiece"] + extras["tokenizers"] + extras["torch-speech"] + extras["vision"] + extras["integrations"] + extras["timm"] + extras["torch-vision"] + extras["codecarbon"] + extras["accelerate"] + extras["video"] + extras["num2words"] + extras["mistral-common"] + extras["chat_template"] ) extras["dev-torch"] = ( extras["testing"] + extras["torch"] + extras["sentencepiece"] + extras["tokenizers"] + extras["torch-speech"] + extras["vision"] + extras["integrations"] + extras["timm"] + extras["torch-vision"] + extras["codecarbon"] + extras["quality"] + extras["ja"] + extras["sklearn"] + extras["modelcreation"] + extras["num2words"] ) extras["dev"] = ( extras["all"] + extras["testing"] + extras["quality"] + extras["ja"] + extras["sklearn"] + extras["modelcreation"] ) extras["torchhub"] = deps_list( "filelock", "huggingface-hub", "importlib_metadata", "numpy", "packaging", "protobuf", "regex", "requests", "sentencepiece", "torch", "tokenizers", "tqdm", ) extras["benchmark"] = deps_list("optimum-benchmark") # OpenTelemetry dependencies for metrics collection in continuous batching # TODO: refactor this to split API and SDK; SDK and exporter should only be needed to run code that collects metrics whereas API is what people will need to instrument their code and handle exporter themselves extras["open-telemetry"] = deps_list("opentelemetry-api") + ["opentelemetry-exporter-otlp", "opentelemetry-sdk"] # when modifying the following list, make sure to update src/transformers/dependency_versions_check.py install_requires = [ deps["filelock"], # filesystem locks, e.g., to prevent parallel downloads deps["huggingface-hub"], deps["numpy"], deps["packaging"], # utilities from PyPA to e.g., compare versions deps["pyyaml"], # used for the model cards metadata deps["regex"], # for OpenAI GPT deps["requests"], # for downloading models over HTTPS deps["tokenizers"], deps["typer-slim"], # CLI utilities. In practice, already a dependency of huggingface_hub deps["safetensors"], deps["tqdm"], # progress bars in model download and training scripts ] setup( name="transformers", version="5.0.0.dev0", # expected format is one of x.y.z.dev0, or x.y.z.rc1 or x.y.z (no to dashes, yes to dots) author="The Hugging Face team (past and future) with the help of all our contributors (https://github.com/huggingface/transformers/graphs/contributors)", author_email="transformers@huggingface.co", description="Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.", long_description=open("README.md", "r", encoding="utf-8").read(), long_description_content_type="text/markdown", keywords="machine-learning nlp python pytorch transformer llm vlm deep-learning inference training model-hub pretrained-models llama gemma qwen", license="Apache 2.0 License", url="https://github.com/huggingface/transformers", package_dir={"": "src"}, packages=find_packages("src"), include_package_data=True, package_data={"": ["**/*.cu", "**/*.cpp", "**/*.cuh", "**/*.h", "**/*.pyx", "py.typed"]}, zip_safe=False, extras_require=extras, entry_points={"console_scripts": ["transformers=transformers.cli.transformers:main"]}, python_requires=">=3.10.0", install_requires=list(install_requires), classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Intended Audience :: Education", "Intended Audience :: Science/Research", "License :: OSI Approved :: Apache Software License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Topic :: Scientific/Engineering :: Artificial Intelligence", ], cmdclass={"deps_table_update": DepsTableUpdateCommand}, ) extras["tests_torch"] = deps_list() extras["tests_hub"] = deps_list() extras["tests_pipelines_torch"] = deps_list() extras["tests_examples_torch"] = deps_list() extras["tests_custom_tokenizers"] = deps_list() extras["tests_exotic_models"] = deps_list() extras["consistency"] = deps_list()
DepsTableUpdateCommand
python
scrapy__scrapy
scrapy/core/downloader/handlers/http11.py
{ "start": 4581, "end": 9752 }
class ____(TCP4ClientEndpoint): """An endpoint that tunnels through proxies to allow HTTPS downloads. To accomplish that, this endpoint sends an HTTP CONNECT to the proxy. The HTTP CONNECT is always sent when using this endpoint, I think this could be improved as the CONNECT will be redundant if the connection associated with this endpoint comes from the pool and a CONNECT has already been issued for it. """ _truncatedLength = 1000 _responseAnswer = ( r"HTTP/1\.. (?P<status>\d{3})(?P<reason>.{," + str(_truncatedLength) + r"})" ) _responseMatcher = re.compile(_responseAnswer.encode()) def __init__( self, reactor: ReactorBase, host: str, port: int, proxyConf: tuple[str, int, bytes | None], contextFactory: IPolicyForHTTPS, timeout: float = 30, bindAddress: tuple[str, int] | None = None, ): proxyHost, proxyPort, self._proxyAuthHeader = proxyConf super().__init__(reactor, proxyHost, proxyPort, timeout, bindAddress) self._tunnelReadyDeferred: Deferred[Protocol] = Deferred() self._tunneledHost: str = host self._tunneledPort: int = port self._contextFactory: IPolicyForHTTPS = contextFactory self._connectBuffer: bytearray = bytearray() def requestTunnel(self, protocol: Protocol) -> Protocol: """Asks the proxy to open a tunnel.""" assert protocol.transport tunnelReq = tunnel_request_data( self._tunneledHost, self._tunneledPort, self._proxyAuthHeader ) protocol.transport.write(tunnelReq) self._protocolDataReceived = protocol.dataReceived protocol.dataReceived = self.processProxyResponse # type: ignore[method-assign] self._protocol = protocol return protocol def processProxyResponse(self, data: bytes) -> None: """Processes the response from the proxy. If the tunnel is successfully created, notifies the client that we are ready to send requests. If not raises a TunnelError. """ assert self._protocol.transport self._connectBuffer += data # make sure that enough (all) bytes are consumed # and that we've got all HTTP headers (ending with a blank line) # from the proxy so that we don't send those bytes to the TLS layer # # see https://github.com/scrapy/scrapy/issues/2491 if b"\r\n\r\n" not in self._connectBuffer: return self._protocol.dataReceived = self._protocolDataReceived # type: ignore[method-assign] respm = TunnelingTCP4ClientEndpoint._responseMatcher.match(self._connectBuffer) if respm and int(respm.group("status")) == 200: # set proper Server Name Indication extension sslOptions = self._contextFactory.creatorForNetloc( # type: ignore[call-arg,misc] self._tunneledHost, self._tunneledPort ) self._protocol.transport.startTLS(sslOptions, self._protocolFactory) self._tunnelReadyDeferred.callback(self._protocol) else: extra: Any if respm: extra = { "status": int(respm.group("status")), "reason": respm.group("reason").strip(), } else: extra = data[: self._truncatedLength] self._tunnelReadyDeferred.errback( TunnelError( "Could not open CONNECT tunnel with proxy " f"{self._host}:{self._port} [{extra!r}]" ) ) def connectFailed(self, reason: Failure) -> None: """Propagates the errback to the appropriate deferred.""" self._tunnelReadyDeferred.errback(reason) def connect(self, protocolFactory: Factory) -> Deferred[Protocol]: self._protocolFactory = protocolFactory connectDeferred = super().connect(protocolFactory) connectDeferred.addCallback(self.requestTunnel) connectDeferred.addErrback(self.connectFailed) return self._tunnelReadyDeferred def tunnel_request_data( host: str, port: int, proxy_auth_header: bytes | None = None ) -> bytes: r""" Return binary content of a CONNECT request. >>> from scrapy.utils.python import to_unicode as s >>> s(tunnel_request_data("example.com", 8080)) 'CONNECT example.com:8080 HTTP/1.1\r\nHost: example.com:8080\r\n\r\n' >>> s(tunnel_request_data("example.com", 8080, b"123")) 'CONNECT example.com:8080 HTTP/1.1\r\nHost: example.com:8080\r\nProxy-Authorization: 123\r\n\r\n' >>> s(tunnel_request_data(b"example.com", "8090")) 'CONNECT example.com:8090 HTTP/1.1\r\nHost: example.com:8090\r\n\r\n' """ host_value = to_bytes(host, encoding="ascii") + b":" + to_bytes(str(port)) tunnel_req = b"CONNECT " + host_value + b" HTTP/1.1\r\n" tunnel_req += b"Host: " + host_value + b"\r\n" if proxy_auth_header: tunnel_req += b"Proxy-Authorization: " + proxy_auth_header + b"\r\n" tunnel_req += b"\r\n" return tunnel_req
TunnelingTCP4ClientEndpoint
python
scipy__scipy
scipy/special/tests/test_spherical_bessel.py
{ "start": 11042, "end": 15195 }
class ____: # These are tests from the TestSpherical class of test_basic.py, # rewritten to use spherical_* instead of sph_* but otherwise unchanged. def test_sph_in(self): # This test reproduces test_basic.TestSpherical.test_sph_in. i1n = np.empty((2,2)) x = 0.2 i1n[0][0] = spherical_in(0, x) i1n[0][1] = spherical_in(1, x) i1n[1][0] = spherical_in(0, x, derivative=True) i1n[1][1] = spherical_in(1, x, derivative=True) inp0 = (i1n[0][1]) inp1 = (i1n[0][0] - 2.0/0.2 * i1n[0][1]) assert_allclose(i1n[0], np.array([1.0066800127054699381, 0.066933714568029540839]), atol=1.5e-12, rtol=0.0) assert_allclose(i1n[1], [inp0, inp1], atol=1.5e-12, rtol=0) def test_sph_in_kn_order0(self): x = 1. sph_i0 = np.empty((2,)) sph_i0[0] = spherical_in(0, x) sph_i0[1] = spherical_in(0, x, derivative=True) sph_i0_expected = np.array([np.sinh(x)/x, np.cosh(x)/x-np.sinh(x)/x**2]) assert_allclose(r_[sph_i0], sph_i0_expected, atol=1.5e-7, rtol=0) sph_k0 = np.empty((2,)) sph_k0[0] = spherical_kn(0, x) sph_k0[1] = spherical_kn(0, x, derivative=True) sph_k0_expected = np.array([0.5*pi*exp(-x)/x, -0.5*pi*exp(-x)*(1/x+1/x**2)]) assert_allclose(r_[sph_k0], sph_k0_expected, atol=1.5e-7, rtol=0) def test_sph_jn(self): s1 = np.empty((2,3)) x = 0.2 s1[0][0] = spherical_jn(0, x) s1[0][1] = spherical_jn(1, x) s1[0][2] = spherical_jn(2, x) s1[1][0] = spherical_jn(0, x, derivative=True) s1[1][1] = spherical_jn(1, x, derivative=True) s1[1][2] = spherical_jn(2, x, derivative=True) s10 = -s1[0][1] s11 = s1[0][0]-2.0/0.2*s1[0][1] s12 = s1[0][1]-3.0/0.2*s1[0][2] assert_allclose(s1[0], [0.99334665397530607731, 0.066400380670322230863, 0.0026590560795273856680], atol=1.5e-12, rtol=0) assert_allclose(s1[1], [s10, s11, s12], atol=1.5e-12, rtol=0) def test_sph_kn(self): kn = np.empty((2,3)) x = 0.2 kn[0][0] = spherical_kn(0, x) kn[0][1] = spherical_kn(1, x) kn[0][2] = spherical_kn(2, x) kn[1][0] = spherical_kn(0, x, derivative=True) kn[1][1] = spherical_kn(1, x, derivative=True) kn[1][2] = spherical_kn(2, x, derivative=True) kn0 = -kn[0][1] kn1 = -kn[0][0]-2.0/0.2*kn[0][1] kn2 = -kn[0][1]-3.0/0.2*kn[0][2] assert_allclose(kn[0], [6.4302962978445670140, 38.581777787067402086, 585.15696310385559829], atol=1.5e-12, rtol=0) assert_allclose(kn[1], [kn0, kn1, kn2], atol=1.5e-9, rtol=0) def test_sph_yn(self): sy1 = spherical_yn(2, 0.2) sy2 = spherical_yn(0, 0.2) # previous values in the system assert_allclose(sy1, -377.52483, atol=1.5e-5, rtol=0) assert_allclose(sy2, -4.9003329, atol=1.5e-5, rtol=0) sphpy = (spherical_yn(0, 0.2) - 2*spherical_yn(2, 0.2))/3 sy3 = spherical_yn(1, 0.2, derivative=True) # compare correct derivative val. (correct =-system val). assert_allclose(sy3, sphpy, atol=1.5e-4, rtol=0) @pytest.mark.parametrize('derivative', [False, True]) @pytest.mark.parametrize('fun', [spherical_jn, spherical_in, spherical_yn, spherical_kn]) def test_negative_real_gh14582(derivative, fun): # gh-14582 reported that the spherical Bessel functions did not work # with negative real argument `z`. Check that this is resolved. rng = np.random.default_rng(3598435982345987234) size = 25 n = rng.integers(0, 10, size=size) z = rng.standard_normal(size=size) res = fun(n, z, derivative=derivative) ref = fun(n, z+0j, derivative=derivative) assert_allclose(res, ref.real)
TestSphericalOld
python
huggingface__transformers
src/transformers/models/siglip2/modeling_siglip2.py
{ "start": 23587, "end": 25884 }
class ____(nn.Module): def __init__(self, config: Siglip2TextConfig): super().__init__() self.config = config embed_dim = config.hidden_size self.embeddings = Siglip2TextEmbeddings(config) self.encoder = Siglip2Encoder(config) self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps) self.head = nn.Linear(embed_dim, config.projection_size) @can_return_tuple @auto_docstring def forward( self, input_ids: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.Tensor] = None, **kwargs: Unpack[TransformersKwargs], ) -> BaseModelOutputWithPooling: if input_ids is None: raise ValueError("You have to specify input_ids") input_shape = input_ids.size() input_ids = input_ids.view(-1, input_shape[-1]) hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids) # note: Siglip2's text model does not use a causal mask, unlike the original CLIP model. # expand attention_mask uses_flash_attention = "flash" in self.config._attn_implementation if uses_flash_attention: attention_mask = None elif attention_mask is not None and not uses_flash_attention: # [batch_size, seq_len] -> [batch_size, 1, tgt_seq_len, src_seq_len] attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype) encoder_outputs: BaseModelOutput = self.encoder( inputs_embeds=hidden_states, attention_mask=attention_mask, **kwargs, ) last_hidden_state = encoder_outputs.last_hidden_state last_hidden_state = self.final_layer_norm(last_hidden_state) # The model uses the last token's hidden state, which may be padding. pooled_output = last_hidden_state[:, -1, :] pooled_output = self.head(pooled_output) return BaseModelOutputWithPooling( last_hidden_state=last_hidden_state, pooler_output=pooled_output, ) @auto_docstring( custom_intro=""" The text model from Siglip2 without any head or projection on top. """ )
Siglip2TextTransformer
python
huggingface__transformers
src/transformers/models/aimv2/configuration_aimv2.py
{ "start": 1315, "end": 5906 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`Aimv2VisionModel`]. It is used to instantiate a AIMv2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the vision encoder of the AIMv2 [apple/aimv2-large-patch14-224](https://huggingface.co/apple/aimv2-large-patch14-224) architecture. Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PreTrainedConfig`] for more information. Args: hidden_size (`int`, *optional*, defaults to 1024): Dimensionality of the encoder layers and the pooler layer. intermediate_size (`int`, *optional*, defaults to 2816): Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. num_hidden_layers (`int`, *optional*, defaults to 24): Number of hidden layers in the Transformer encoder. num_attention_heads (`int`, *optional*, defaults to 8): Number of attention heads for each attention layer in the Transformer encoder. num_channels (`int`, *optional*, defaults to 3): Number of channels in the input images. image_size (`int`, *optional*, defaults to 224): The size (resolution) of each image. patch_size (`int`, *optional*, defaults to 14): The size (resolution) of each patch. rms_norm_eps (`float`, *optional*, defaults to 1e-05): The epsilon used by the rms normalization layers. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. qkv_bias (`bool`, *optional*, defaults to `False`): Whether to add a bias to the queries, keys and values. mlp_bias (`bool`, *optional*, defaults to `False`): Whether to add a bias to the Linear layers or Not. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the for initializing all weight matrices. use_head (`str`, *optional*, defaults to `True`): Whether to use Attention Pooling Head or Not. is_native (`str`, *optional*, defaults to `False`): Whether to use ckpt trained for image native resolution or not. Example: ```python >>> from transformers import SiglipVisionConfig, SiglipVisionModel >>> # Initializing a Aimv2VisionConfig with apple/aimv2-large-patch14-224 style configuration >>> configuration = Aimv2VisionConfig() >>> # Initializing a Aimv2VisionModel (with random weights) from the apple/aimv2-large-patch14-224 style configuration >>> model = Aimv2VisionModel(configuration) >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "aimv2_vision_model" base_config_key = "vision_config" def __init__( self, hidden_size: int = 1024, intermediate_size: int = 2816, num_hidden_layers: int = 24, num_attention_heads: int = 8, num_channels: int = 3, image_size: int = 224, patch_size: int = 14, rms_norm_eps: float = 1e-5, attention_dropout: float = 0.0, qkv_bias: bool = False, mlp_bias: bool = False, hidden_act: str = "silu", initializer_range: float = 0.02, use_head: bool = True, is_native: bool = False, **kwargs, ): super().__init__(**kwargs) self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_channels = num_channels self.patch_size = patch_size self.image_size = image_size self.attention_dropout = attention_dropout self.hidden_act = hidden_act self.use_head = use_head self.initializer_range = initializer_range self.mlp_bias = mlp_bias self.qkv_bias = qkv_bias self.rms_norm_eps = rms_norm_eps self.is_native = is_native
Aimv2VisionConfig
python
ray-project__ray
python/ray/_private/worker.py
{ "start": 12224, "end": 45210 }
class ____: """A class used to define the control flow of a worker process. Note: The methods in this class are considered unexposed to the user. The functions outside of this class are considered exposed. Attributes: node (ray._private.node.Node): The node this worker is attached to. mode: The mode of the worker. One of SCRIPT_MODE, LOCAL_MODE, and WORKER_MODE. """ def __init__(self): """Initialize a Worker object.""" self.node = None self.mode = None self.actors = {} # GPU object manager to manage GPU object lifecycles, including coordinating out-of-band # tensor transfers between actors, storing and retrieving GPU objects, and garbage collection. # We create the GPU object manager lazily, if a user specifies a # non-default tensor_transport, to avoid circular import and because it # imports third-party dependencies like PyTorch. self._gpu_object_manager = None # When the worker is constructed. Record the original value of the # (CUDA_VISIBLE_DEVICES, ONEAPI_DEVICE_SELECTOR, HIP_VISIBLE_DEVICES, # NEURON_RT_VISIBLE_CORES, TPU_VISIBLE_CHIPS, ..) environment variables. self.original_visible_accelerator_ids = ( ray._private.utils.get_visible_accelerator_ids() ) # A dictionary that maps from driver id to SerializationContext # TODO: clean up the SerializationContext once the job finished. self.serialization_context_map = {} self.function_actor_manager = FunctionActorManager(self) # This event is checked regularly by all of the threads so that they # know when to exit. self.threads_stopped = threading.Event() # If this is set, the next .remote call should drop into the # debugger, at the specified breakpoint ID. self.debugger_breakpoint = b"" # If this is set, ray.get calls invoked on the object ID returned # by the worker should drop into the debugger at the specified # breakpoint ID. self.debugger_get_breakpoint = b"" # If True, make the debugger external to the node this worker is # running on. self.ray_debugger_external = False self._load_code_from_local = False # Opened file descriptor to stdout/stderr for this python worker. self._enable_record_actor_task_log = ( ray_constants.RAY_ENABLE_RECORD_ACTOR_TASK_LOGGING ) # Whether rotation is enabled for out file and err file, task log position report will be skipped if rotation enabled, since the position cannot be accurate. self._file_rotation_enabled = False self._out_filepath = None self._err_filepath = None # Create the lock here because the serializer will use it before # initializing Ray. self.lock = threading.RLock() # By default, don't show logs from other drivers. This is set to true by Serve # in order to stream logs from the controller and replica actors across # different drivers that connect to the same Serve instance. # See https://github.com/ray-project/ray/pull/35070. self._filter_logs_by_job = True # the debugger port for this worker self._debugger_port = None # Cache the job id from initialize_job_config() to optimize lookups. # This is on the critical path of ray.get()/put() calls. self._cached_job_id = None # Indicates whether the worker is connected to the Ray cluster. # It should be set to True in `connect` and False in `disconnect`. self._is_connected: bool = False @property def gpu_object_manager(self) -> "ray.experimental.GPUObjectManager": if self._gpu_object_manager is None: # We create the GPU object manager lazily, if a user specifies a # non-default tensor_transport, to avoid circular import and because it # imports third-party dependencies like PyTorch. from ray.experimental import GPUObjectManager self._gpu_object_manager = GPUObjectManager() return self._gpu_object_manager @property def connected(self): """bool: True if Ray has been started and False otherwise.""" return self._is_connected def set_is_connected(self, is_connected: bool): self._is_connected = is_connected @property def node_ip_address(self): self.check_connected() return self.node.node_ip_address @property def load_code_from_local(self): self.check_connected() return self._load_code_from_local @property def current_job_id(self): if self._cached_job_id is not None: return self._cached_job_id elif hasattr(self, "core_worker"): return self.core_worker.get_current_job_id() return JobID.nil() @property def actor_id(self): if hasattr(self, "core_worker"): return self.core_worker.get_actor_id() return ActorID.nil() @property def actor_name(self): if hasattr(self, "core_worker"): return self.core_worker.get_actor_name().decode("utf-8") return None @property def current_task_id(self): return self.core_worker.get_current_task_id() @property def current_task_name(self): return self.core_worker.get_current_task_name() @property def current_task_function_name(self): return self.core_worker.get_current_task_function_name() @property def current_node_id(self): return self.core_worker.get_current_node_id() @property def task_depth(self): return self.core_worker.get_task_depth() @property def namespace(self): return self.core_worker.get_job_config().ray_namespace @property def placement_group_id(self): return self.core_worker.get_placement_group_id() @property def worker_id(self): return self.core_worker.get_worker_id().binary() @property def should_capture_child_tasks_in_placement_group(self): return self.core_worker.should_capture_child_tasks_in_placement_group() @property def current_cluster_and_job(self): """Get the current session index and job id as pair.""" assert isinstance(self.node.cluster_id, ray.ClusterID) assert isinstance(self.current_job_id, ray.JobID) return self.node.cluster_id, self.current_job_id @property def runtime_env(self): """Get the runtime env in json format""" return self.core_worker.get_current_runtime_env() @property def debugger_port(self): """Get the debugger port for this worker""" worker_id = self.core_worker.get_worker_id() return ray._private.state.get_worker_debugger_port(worker_id) @property def job_logging_config(self): """Get the job's logging config for this worker""" if not hasattr(self, "core_worker"): return None job_config = self.core_worker.get_job_config() if not job_config.serialized_py_logging_config: return None logging_config = pickle.loads(job_config.serialized_py_logging_config) return logging_config @property def current_node_labels(self): # Return the node labels of this worker's current node. return self.node.node_labels def set_debugger_port(self, port): worker_id = self.core_worker.get_worker_id() ray._private.state.update_worker_debugger_port(worker_id, port) def set_cached_job_id(self, job_id): """Set the cached job id to speed `current_job_id()`.""" self._cached_job_id = job_id @contextmanager def task_paused_by_debugger(self): """Use while the task is paused by debugger""" try: self.core_worker.update_task_is_debugger_paused( ray.get_runtime_context()._get_current_task_id(), True ) yield finally: self.core_worker.update_task_is_debugger_paused( ray.get_runtime_context()._get_current_task_id(), False ) @contextmanager def worker_paused_by_debugger(self): """ Updates the worker num paused threads when the worker is paused by debugger """ try: worker_id = self.core_worker.get_worker_id() ray._private.state.update_worker_num_paused_threads(worker_id, 1) yield finally: ray._private.state.update_worker_num_paused_threads(worker_id, -1) def set_file_rotation_enabled(self, rotation_enabled: bool) -> None: """Set whether rotation is enabled for outfile and errfile.""" self._file_rotation_enabled = rotation_enabled def set_err_file(self, err_filepath=Optional[AnyStr]) -> None: """Set the worker's err file where stderr is redirected to""" self._err_filepath = err_filepath def set_out_file(self, out_filepath=Optional[AnyStr]) -> None: """Set the worker's out file where stdout is redirected to""" self._out_filepath = out_filepath def record_task_log_start(self, task_id: TaskID, attempt_number: int): """Record the task log info when task starts executing for non concurrent actor tasks.""" if not self._enable_record_actor_task_log and not self.actor_id.is_nil(): # We are not recording actor task log if not enabled explicitly. # Recording actor task log is expensive and should be enabled only # when needed. # https://github.com/ray-project/ray/issues/35598 return if not hasattr(self, "core_worker"): return if self._file_rotation_enabled: return self.core_worker.record_task_log_start( task_id, attempt_number, self.get_out_file_path(), self.get_err_file_path(), self.get_current_out_offset(), self.get_current_err_offset(), ) def record_task_log_end(self, task_id: TaskID, attempt_number: int): """Record the task log info when task finishes executing for non concurrent actor tasks.""" if not self._enable_record_actor_task_log and not self.actor_id.is_nil(): # We are not recording actor task log if not enabled explicitly. # Recording actor task log is expensive and should be enabled only # when needed. # https://github.com/ray-project/ray/issues/35598 return if not hasattr(self, "core_worker"): return # Disable file offset fetch if rotation enabled (since file offset doesn't make sense for rotated files). if self._file_rotation_enabled: return self.core_worker.record_task_log_end( task_id, attempt_number, self.get_current_out_offset(), self.get_current_err_offset(), ) def get_out_file_path(self) -> str: """Get the out log file path""" return self._out_filepath if self._out_filepath is not None else "" def get_err_file_path(self) -> str: """Get the err log file path""" return self._err_filepath if self._err_filepath is not None else "" def get_current_out_offset(self) -> int: """Get the current offset of the out file if seekable, else 0""" if self._out_filepath is not None: return os.path.getsize(self._out_filepath) return 0 def get_current_err_offset(self) -> int: """Get the current offset of the err file if seekable, else 0""" if self._err_filepath is not None: return os.path.getsize(self._err_filepath) return 0 def get_serialization_context(self): """Get the SerializationContext of the job that this worker is processing. Returns: The serialization context of the given job. """ # This function needs to be protected by a lock, because it will be # called by`register_class_for_serialization`, as well as the import # thread, from different threads. Also, this function will recursively # call itself, so we use RLock here. job_id = self.current_job_id context_map = self.serialization_context_map with self.lock: if job_id not in context_map: # The job ID is nil before initializing Ray. if JobID.nil() in context_map: # Transfer the serializer context used before initializing Ray. context_map[job_id] = context_map.pop(JobID.nil()) else: context_map[job_id] = serialization.SerializationContext(self) return context_map[job_id] def check_connected(self): """Check if the worker is connected. Raises: Exception: An exception is raised if the worker is not connected. """ if not self.connected: raise RaySystemError( "Ray has not been started yet. You can start Ray with 'ray.init()'." ) def set_mode(self, mode): """Set the mode of the worker. The mode SCRIPT_MODE should be used if this Worker is a driver that is being run as a Python script or interactively in a shell. It will print information about task failures. The mode WORKER_MODE should be used if this Worker is not a driver. It will not print information about tasks. The mode LOCAL_MODE should be used if this Worker is a driver and if you want to run the driver in a manner equivalent to serial Python for debugging purposes. It will not send remote function calls to the scheduler and will instead execute them in a blocking fashion. Args: mode: One of SCRIPT_MODE, WORKER_MODE, and LOCAL_MODE. """ self.mode = mode def set_load_code_from_local(self, load_code_from_local): self._load_code_from_local = load_code_from_local def put_object( self, value: Any, owner_address: Optional[str] = None, _is_experimental_channel: bool = False, _tensor_transport: str = "object_store", ): """Put value in the local object store. If the plasma store is full, the worker will automatically retry up to DEFAULT_PUT_OBJECT_RETRIES times. Each retry will delay for an exponentially doubling amount of time, starting with DEFAULT_PUT_OBJECT_DELAY. After this, exception will be raised. Args: value: The value to put in the object store. owner_address: The serialized address of object's owner. _is_experimental_channel: An experimental flag for mutable objects. If True, then the returned object will not have a valid value. The object must be written to using the ray.experimental.channel API before readers can read. _tensor_transport: [Alpha] The tensor transport backend to use. Currently, this supports "object_store" and "nixl". Returns: ObjectRef: The object ref the object was put under. Raises: ray.exceptions.ObjectStoreFullError: This is raised if the attempt to store the object fails because the object store is full even after multiple retries. """ # Make sure that the value is not an object ref. if isinstance(value, ObjectRef): raise TypeError( "Calling 'put' on an ray.ObjectRef is not allowed. " "If you really want to do this, you can wrap the " "ray.ObjectRef in a list and call 'put' on it." ) tensors = None tensor_transport: TensorTransportEnum = TensorTransportEnum.from_str( _tensor_transport ) if tensor_transport not in [ TensorTransportEnum.OBJECT_STORE, TensorTransportEnum.NIXL, ]: raise ValueError( "Currently, Ray Direct Transport only supports 'object_store' and 'nixl' for tensor transport in ray.put()." ) try: if tensor_transport != TensorTransportEnum.OBJECT_STORE: ( serialized_value, tensors, ) = self.get_serialization_context().serialize_gpu_objects(value) else: serialized_value = self.get_serialization_context().serialize(value) except TypeError as e: sio = io.StringIO() ray.util.inspect_serializability(value, print_file=sio) msg = ( "Could not serialize the put value " f"{repr(value)}:\n" f"{sio.getvalue()}" ) raise TypeError(msg) from e # If the object is mutable, then the raylet should never read the # object. Instead, clients will keep the object pinned. pin_object = not _is_experimental_channel # This *must* be the first place that we construct this python # ObjectRef because an entry with 0 local references is created when # the object is Put() in the core worker, expecting that this python # reference will be created. If another reference is created and # removed before this one, it will corrupt the state in the # reference counter. ret = self.core_worker.put_object( serialized_value, pin_object=pin_object, owner_address=owner_address, inline_small_object=True, _is_experimental_channel=_is_experimental_channel, tensor_transport_val=tensor_transport.value, ) if tensors: self.gpu_object_manager.put_object(ret, tensor_transport, tensors) return ret def raise_errors(self, serialized_objects, object_refs): out = self.deserialize_objects(serialized_objects, object_refs) if "RAY_IGNORE_UNHANDLED_ERRORS" in os.environ: return for e in out: _unhandled_error_handler(e) def deserialize_objects( self, serialized_objects, object_refs, tensor_transport_hint: Optional[TensorTransportEnum] = None, ): gpu_objects: Dict[str, List["torch.Tensor"]] = {} for obj_ref, (_, _, tensor_transport) in zip(object_refs, serialized_objects): # TODO: Here tensor_transport_hint is set by the user in ray.get(), tensor_transport is set # in serialize_objects by ray.method(tensor_transport="xxx"), and obj_ref.tensor_transport() # is set by ray.put(). We may clean up this logic in the future. if ( tensor_transport is None or tensor_transport == TensorTransportEnum.OBJECT_STORE ) and ( obj_ref is None or obj_ref.tensor_transport() == TensorTransportEnum.OBJECT_STORE.value ): # The object is not a gpu object, so we cannot use other external transport to # fetch it. continue # If the object is a gpu object, we can choose to use the object store or other external # transport to fetch it. The `tensor_transport_hint` has the highest priority, then the # tensor_transport in obj_ref.tensor_transport(), then the tensor_transport in serialize_objects, # then the default value `OBJECT_STORE`. chosen_tensor_transport = ( tensor_transport_hint or ( TensorTransportEnum(obj_ref.tensor_transport()) if obj_ref else None ) or tensor_transport or TensorTransportEnum.OBJECT_STORE ) object_id = obj_ref.hex() if object_id not in gpu_objects: # If using a non-object store transport, then tensors will be sent # out-of-band. Get them before deserializing the object store data. gpu_objects[object_id] = self.gpu_object_manager.get_gpu_object( object_id, tensor_transport=chosen_tensor_transport ) # Function actor manager or the import thread may call pickle.loads # at the same time which can lead to failed imports # TODO: We may be better off locking on all imports or injecting a lock # into pickle.loads (https://github.com/ray-project/ray/issues/16304) with self.function_actor_manager.lock: context = self.get_serialization_context() return context.deserialize_objects( serialized_objects, object_refs, gpu_objects ) def get_objects( self, object_refs: list, timeout: Optional[float] = None, return_exceptions: bool = False, skip_deserialization: bool = False, _tensor_transport: Optional[str] = None, ) -> Tuple[List[serialization.SerializedRayObject], bytes]: """Get the values in the object store associated with the IDs. Return the values from the local object store for object_refs. This will block until all the values for object_refs have been written to the local object store. Args: object_refs: A list of the object refs whose values should be retrieved. timeout: The maximum amount of time in seconds to wait before returning. return_exceptions: If any of the objects deserialize to an Exception object, whether to return them as values in the returned list. If False, then the first found exception will be raised. skip_deserialization: If true, only the buffer will be released and the object associated with the buffer will not be deserialized. _tensor_transport: [Alpha] The tensor transport to use to fetch `torch.Tensors` found in the Ray Direct Transport object. Currently, this supports "object_store" and "nixl". Returns: list: List of deserialized objects or None if skip_deserialization is True. bytes: UUID of the debugger breakpoint we should drop into or b"" if there is no breakpoint. """ # Make sure that the values are object refs. for object_ref in object_refs: if not isinstance(object_ref, ObjectRef): raise TypeError( f"Attempting to call `get` on the value {object_ref}, " "which is not an ray.ObjectRef." ) tensor_transport: TensorTransportEnum = ( TensorTransportEnum.from_str(_tensor_transport) if _tensor_transport is not None else None ) assert tensor_transport in [ TensorTransportEnum.OBJECT_STORE, TensorTransportEnum.NIXL, None, ], "Currently, RDT only supports 'object_store' and 'nixl' for tensor transport in ray.get()." timeout_ms = ( int(timeout * 1000) if timeout is not None and timeout != -1 else -1 ) serialized_objects: List[ serialization.SerializedRayObject ] = self.core_worker.get_objects( object_refs, timeout_ms, ) debugger_breakpoint = b"" for data, metadata, _ in serialized_objects: if metadata: metadata_fields = metadata.split(b",") if len(metadata_fields) >= 2 and metadata_fields[1].startswith( ray_constants.OBJECT_METADATA_DEBUG_PREFIX ): debugger_breakpoint = metadata_fields[1][ len(ray_constants.OBJECT_METADATA_DEBUG_PREFIX) : ] if skip_deserialization: return None, debugger_breakpoint values = self.deserialize_objects( serialized_objects, object_refs, tensor_transport_hint=tensor_transport ) if not return_exceptions: # Raise exceptions instead of returning them to the user. for i, value in enumerate(values): if isinstance(value, RayError): if isinstance( value, ray.exceptions.ObjectLostError ) and not isinstance(value, ray.exceptions.OwnerDiedError): global_worker.core_worker.log_plasma_usage() if isinstance(value, RayTaskError): raise value.as_instanceof_cause() else: raise value return values, debugger_breakpoint def main_loop(self): """The main loop a worker runs to receive and execute tasks.""" def sigterm_handler(signum, frame): raise_sys_exit_with_custom_error_message( "The process receives a SIGTERM.", exit_code=1 ) # Note: shutdown() function is called from atexit handler. ray._private.utils.set_sigterm_handler(sigterm_handler) self.core_worker.run_task_loop() sys.exit(0) def print_logs(self): """Prints log messages from workers on all nodes in the same job.""" subscriber = self.gcs_log_subscriber subscriber.subscribe() exception_type = ray.exceptions.RpcError localhost = services.get_node_ip_address() try: # Number of messages received from the last polling. When the batch # size exceeds 100 and keeps increasing, the worker and the user # probably will not be able to consume the log messages as rapidly # as they are coming in. # This is meaningful only for GCS subscriber. last_polling_batch_size = 0 job_id_hex = self.current_job_id.hex() while True: # Exit if we received a signal that we should stop. if self.threads_stopped.is_set(): return data = subscriber.poll() # GCS subscriber only returns None on unavailability. if data is None: last_polling_batch_size = 0 continue if ( self._filter_logs_by_job and data["job"] and data["job"] != job_id_hex ): last_polling_batch_size = 0 continue data["localhost"] = localhost global_worker_stdstream_dispatcher.emit(data) lagging = 100 <= last_polling_batch_size < subscriber.last_batch_size if lagging: logger.warning( "The driver may not be able to keep up with the " "stdout/stderr of the workers. To avoid forwarding " "logs to the driver, use " "'ray.init(log_to_driver=False)'." ) last_polling_batch_size = subscriber.last_batch_size except (OSError, exception_type) as e: logger.error(f"print_logs: {e}") finally: # Close the pubsub client to avoid leaking file descriptors. subscriber.close() def get_accelerator_ids_for_accelerator_resource( self, resource_name: str, resource_regex: str ) -> Union[List[str], List[int]]: """Get the accelerator IDs that are assigned to the given accelerator resource. Args: resource_name: The name of the resource. resource_regex: The regex of the resource. Returns: (List[str]) The IDs that are assigned to the given resource pre-configured. (List[int]) The IDs that are assigned to the given resource. """ resource_ids = self.core_worker.resource_ids() assigned_ids = set() # Handle both normal and placement group accelerator resources. # Note: We should only get the accelerator ids from the placement # group resource that does not contain the bundle index! import re for resource, assignment in resource_ids.items(): if resource == resource_name or re.match(resource_regex, resource): for resource_id, _ in assignment: assigned_ids.add(resource_id) # If the user had already set the environment variables # (CUDA_VISIBLE_DEVICES, ONEAPI_DEVICE_SELECTOR, NEURON_RT_VISIBLE_CORES, # TPU_VISIBLE_CHIPS, ..) then respect that in the sense that only IDs # that appear in (CUDA_VISIBLE_DEVICES, ONEAPI_DEVICE_SELECTOR, # HIP_VISIBLE_DEVICES, NEURON_RT_VISIBLE_CORES, TPU_VISIBLE_CHIPS, ..) # should be returned. if self.original_visible_accelerator_ids.get(resource_name, None) is not None: original_ids = self.original_visible_accelerator_ids[resource_name] assigned_ids = {str(original_ids[i]) for i in assigned_ids} # Give all accelerator ids in local_mode. if self.mode == LOCAL_MODE: if resource_name == ray_constants.GPU: max_accelerators = self.node.get_resource_and_label_spec().num_gpus else: max_accelerators = ( self.node.get_resource_and_label_spec().resources.get( resource_name, None ) ) if max_accelerators: assigned_ids = original_ids[:max_accelerators] return list(assigned_ids) def shutdown_gpu_object_manager(self): if self._gpu_object_manager: self._gpu_object_manager.shutdown() _connect_or_shutdown_lock = threading.RLock() def with_connect_or_shutdown_lock(func: Callable) -> Callable: @wraps(func) def wrapper(*args, **kwargs): with _connect_or_shutdown_lock: return func(*args, **kwargs) return wrapper @PublicAPI @client_mode_hook def get_gpu_ids() -> Union[List[int], List[str]]: """Get the IDs of the GPUs that are available to the worker. This method should only be called inside of a task or actor, and not a driver. If the CUDA_VISIBLE_DEVICES environment variable was set when the worker started up, then the IDs returned by this method will be a subset of the IDs in CUDA_VISIBLE_DEVICES. If not, the IDs will fall in the range [0, NUM_GPUS - 1], where NUM_GPUS is the number of GPUs that the node has. Returns: A list of GPU IDs. """ worker = global_worker worker.check_connected() return worker.get_accelerator_ids_for_accelerator_resource( ray_constants.GPU, f"^{ray_constants.GPU}_group_[0-9A-Za-z]+$" ) @Deprecated( message="Use ray.get_runtime_context().get_assigned_resources() instead.", warning=True, ) def get_resource_ids(): """Get the IDs of the resources that are available to the worker. Returns: A dictionary mapping the name of a resource to a list of pairs, where each pair consists of the ID of a resource and the fraction of that resource reserved for this worker. """ worker = global_worker worker.check_connected() if _mode() == LOCAL_MODE: raise RuntimeError( "ray._private.worker.get_resource_ids() does not work in local_mode." ) return global_worker.core_worker.resource_ids() @Deprecated(message="Use ray.init().address_info['webui_url'] instead.") def get_dashboard_url(): """Get the URL to access the Ray dashboard. Note that the URL does not specify which node the dashboard is on. Returns: The URL of the dashboard as a string. """ if ray_constants.RAY_OVERRIDE_DASHBOARD_URL in os.environ: return _remove_protocol_from_url( os.environ.get(ray_constants.RAY_OVERRIDE_DASHBOARD_URL) ) else: worker = global_worker worker.check_connected() return _global_node.webui_url def _remove_protocol_from_url(url: Optional[str]) -> str: """ Helper function to remove protocol from URL if it exists. """ if not url: return url parsed_url = urllib.parse.urlparse(url) if parsed_url.scheme: # Construct URL without protocol scheme = f"{parsed_url.scheme}://" return parsed_url.geturl().replace(scheme, "", 1) return url
Worker
python
great-expectations__great_expectations
great_expectations/core/freshness_diagnostics.py
{ "start": 3594, "end": 4016 }
class ____(_ParentFreshnessDiagnostics): parent_error_class: ClassVar[Type[GreatExpectationsError]] = CheckpointNotAddedError children_error_classes: ClassVar[Tuple[Type[GreatExpectationsError], ...]] = ( ValidationDefinitionNotAddedError, ) raise_for_error_class: ClassVar[Type[ResourceFreshnessAggregateError]] = ( CheckpointRelatedResourcesFreshnessError )
CheckpointFreshnessDiagnostics
python
Textualize__textual
docs/examples/widgets/header_app_title.py
{ "start": 80, "end": 357 }
class ____(App): def compose(self) -> ComposeResult: yield Header() def on_mount(self) -> None: self.title = "Header Application" self.sub_title = "With title and sub-title" if __name__ == "__main__": app = HeaderApp() app.run()
HeaderApp
python
spack__spack
lib/spack/spack/variant.py
{ "start": 1343, "end": 8661 }
class ____: """Represents a variant definition, created by the ``variant()`` directive. There can be multiple definitions of the same variant, and they are given precedence by order of appearance in the package. Later definitions have higher precedence. Similarly, definitions in derived classes have higher precedence than those in their superclasses. """ name: str default: Union[bool, str] description: str values: Optional[Collection] #: if None, valid values are defined only by validators multi: bool single_value_validator: Callable group_validator: Optional[Callable] sticky: bool precedence: int def __init__( self, name: str, *, default: Union[bool, str], description: str, values: Union[Collection, Callable] = (True, False), multi: bool = False, validator: Optional[Callable] = None, sticky: bool = False, precedence: int = 0, ): """Initialize a package variant. Args: name: name of the variant default: default value for the variant, used when nothing is explicitly specified description: purpose of the variant values: sequence of allowed values or a callable accepting a single value as argument and returning True if the value is good, False otherwise multi: whether multiple values are allowed validator: optional callable that can be used to perform additional validation sticky: if true the variant is set to the default value at concretization time precedence: int indicating precedence of this variant definition in the solve (definition with highest precedence is used when multiple definitions are possible) """ self.name = name self.default = default self.description = str(description) self.values = None if values == "*": # wildcard is a special case to make it easy to say any value is ok self.single_value_validator = lambda v: True elif isinstance(values, type): # supplying a type means any value *of that type* def isa_type(v): try: values(v) return True except ValueError: return False self.single_value_validator = isa_type elif callable(values): # If 'values' is a callable, assume it is a single value # validator and reset the values to be explicit during debug self.single_value_validator = values else: # Otherwise, assume values is the set of allowed explicit values values = _flatten(values) self.values = values self.single_value_validator = lambda v: v in values self.multi = multi self.group_validator = validator self.sticky = sticky self.precedence = precedence def validate_or_raise(self, vspec: "VariantValue", pkg_name: str): """Validate a variant spec against this package variant. Raises an exception if any error is found. Args: vspec: variant spec to be validated pkg_name: the name of the package class that required this validation (for errors) Raises: InconsistentValidationError: if ``vspec.name != self.name`` MultipleValuesInExclusiveVariantError: if ``vspec`` has multiple values but ``self.multi == False`` InvalidVariantValueError: if ``vspec.value`` contains invalid values """ # Check the name of the variant if self.name != vspec.name: raise InconsistentValidationError(vspec, self) # If the value is exclusive there must be at most one value = vspec.values if not self.multi and len(value) != 1: raise MultipleValuesInExclusiveVariantError(vspec, pkg_name) # Check and record the values that are not allowed invalid_vals = ", ".join( f"'{v}'" for v in value if v != "*" and self.single_value_validator(v) is False ) if invalid_vals: raise InvalidVariantValueError( f"invalid values for variant '{self.name}' in package {pkg_name}: {invalid_vals}\n" ) # Validate the group of values if needed if self.group_validator is not None and value != ("*",): self.group_validator(pkg_name, self.name, value) @property def allowed_values(self): """Returns a string representation of the allowed values for printing purposes Returns: str: representation of the allowed values """ # Join an explicit set of allowed values if self.values is not None: v = tuple(str(x) for x in self.values) return ", ".join(v) # In case we were given a single-value validator # print the docstring docstring = inspect.getdoc(self.single_value_validator) v = docstring if docstring else "" return v def make_default(self) -> "VariantValue": """Factory that creates a variant holding the default value(s).""" variant = VariantValue.from_string_or_bool(self.name, self.default) variant.type = self.variant_type return variant def make_variant(self, *value: Union[str, bool]) -> "VariantValue": """Factory that creates a variant holding the value(s) passed.""" return VariantValue(self.variant_type, self.name, value) @property def variant_type(self) -> VariantType: """String representation of the type of this variant (single/multi/bool)""" if self.multi: return VariantType.MULTI elif self.values == (True, False): return VariantType.BOOL else: return VariantType.SINGLE def __str__(self) -> str: return ( f"Variant('{self.name}', " f"default='{self.default}', " f"description='{self.description}', " f"values={self.values}, " f"multi={self.multi}, " f"single_value_validator={self.single_value_validator}, " f"group_validator={self.group_validator}, " f"sticky={self.sticky}, " f"precedence={self.precedence})" ) def _flatten(values) -> Collection: """Flatten instances of _ConditionalVariantValues for internal representation""" if isinstance(values, DisjointSetsOfValues): return values flattened: List = [] for item in values: if isinstance(item, ConditionalVariantValues): flattened.extend(item) else: flattened.append(item) # There are parts of the variant checking mechanism that expect to find tuples # here, so it is important to convert the type once we flattened the values. return tuple(flattened) #: Type for value of a variant ValueType = Tuple[Union[bool, str], ...] #: Type of variant value when output for JSON, YAML, etc. SerializedValueType = Union[str, bool, List[Union[str, bool]]] @lang.lazy_lexicographic_ordering
Variant
python
doocs__leetcode
solution/2500-2599/2569.Handling Sum Queries After Update/Solution.py
{ "start": 1808, "end": 2263 }
class ____: def handleQuery( self, nums1: List[int], nums2: List[int], queries: List[List[int]] ) -> List[int]: tree = SegmentTree(nums1) s = sum(nums2) ans = [] for op, a, b in queries: if op == 1: tree.modify(1, a + 1, b + 1) elif op == 2: s += a * tree.query(1, 1, len(nums1)) else: ans.append(s) return ans
Solution
python
dagster-io__dagster
python_modules/libraries/dagster-postgres/dagster_postgres_tests/test_daemon_cursor_storage.py
{ "start": 264, "end": 563 }
class ____(TestDaemonCursorStorage): __test__ = True @pytest.fixture(scope="function", name="storage") def cursor_storage(self, conn_string): storage = PostgresRunStorage.create_clean_storage(conn_string) assert storage return storage
TestPostgresDaemonCursorStorage
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_tests.py
{ "start": 83084, "end": 84502 }
class ____(TestCase): def test_copy(self) -> None: class Schema(Config): foo = c.MarkdownExtensions() copy.deepcopy(Schema()) copy.deepcopy(self.get_config(IpAddressTest.Schema, {'option': '1.2.3.4:5678'})) copy.deepcopy(IpAddressTest.Schema) copy.deepcopy(IpAddressTest.Schema()) copy.deepcopy(self.get_config(EditURITest.Schema, {})) copy.deepcopy(EditURITest.Schema) copy.deepcopy(EditURITest.Schema()) def test_subclass(self) -> None: class A(Config): foo = c.Type(int) bar = c.Optional(c.Type(str)) class B(A): baz = c.ListOfItems(c.Type(str)) conf = self.get_config(B, {'foo': 1, 'baz': ['b']}) assert_type(conf.foo, int) self.assertEqual(conf.foo, 1) assert_type(conf.bar, Optional[str]) self.assertEqual(conf.bar, None) assert_type(conf.baz, List[str]) self.assertEqual(conf.baz, ['b']) with self.expect_error(baz="Required configuration not provided."): self.get_config(B, {'foo': 1}) with self.expect_error(foo="Required configuration not provided."): self.get_config(B, {'baz': ['b']}) bconf = self.get_config(A, {'foo': 2, 'bar': 'a'}) assert_type(bconf.foo, int) self.assertEqual(bconf.foo, 2) self.assertEqual(bconf.bar, 'a')
SchemaTest
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/math_ops/segment_reduction_ops_test.py
{ "start": 1458, "end": 3574 }
class ____(test.TestCase): def _input(self, input_shape, dtype=dtypes_lib.int32): num_elem = 1 for x in input_shape: num_elem *= x values = np.arange(1, num_elem + 1) np_values = values.reshape(input_shape).astype(dtype.as_numpy_dtype) if dtype == dtypes_lib.bfloat16: # Large numbers from arange lead to high absolute diff with bfloat16, so # scale down. np_values *= np.array(0.00001, dtype=dtype.as_numpy_dtype) # Add a non-zero imaginary component to complex types. if dtype.is_complex: np_values -= 1j * np_values return constant_op.constant( np_values, shape=input_shape, dtype=dtype), np_values def _segmentReduce( self, indices, x, op1, op2=None, num_segments=None, initial_value=0, empty_value=0, ): if not x.size: return np.array([]) indices = np.asarray(indices) if num_segments is None: num_segments = indices[-1] + 1 output = [None] * num_segments slice_shape = x.shape[indices.ndim:] x_flat = x.reshape((indices.size,) + slice_shape) for i, index in enumerate(indices.ravel()): if (output[index] is not None) and op1 == np.max: for j in range(0, output[index].shape[0]): output[index][j] = op1([output[index][j], x_flat[i][j]]) elif output[index] is not None: output[index] = op1(output[index], x_flat[i]) else: output[index] = x_flat[i] # zero initialize values that are still uncalculated. empty_value_slice = np.ones(slice_shape) * empty_value output = [o if o is not None else empty_value_slice for o in output] if op2 is not None: output = [op2(o) for o in output] output = [o.reshape(slice_shape) for o in output] return np.array(output) def _mean_cum_op(self, x, y): return (x[0] + y, x[1] + 1) if isinstance(x, tuple) else (x + y, 2) def _mean_reduce_op(self, x): return x[0] / x[1] if isinstance(x, tuple) else x def _sqrt_n_reduce_op(self, x): return x[0] / np.sqrt(x[1]) if isinstance(x, tuple) else x
SegmentReductionHelper
python
pandas-dev__pandas
asv_bench/benchmarks/libs.py
{ "start": 2219, "end": 2445 }
class ____: def setup(self): class Foo: @cache_readonly def prop(self): return 5 self.obj = Foo() def time_cache_readonly(self): self.obj.prop
CacheReadonly
python
zarr-developers__zarr-python
src/zarr/core/_info.py
{ "start": 411, "end": 2034 }
class ____: """ Visual summary for a Group. Note that this method and its properties is not part of Zarr's public API. """ _name: str _type: Literal["Group"] = "Group" _zarr_format: ZarrFormat _read_only: bool _store_type: str _count_members: int | None = None _count_arrays: int | None = None _count_groups: int | None = None def __repr__(self) -> str: template = textwrap.dedent("""\ Name : {_name} Type : {_type} Zarr format : {_zarr_format} Read-only : {_read_only} Store type : {_store_type}""") if self._count_members is not None: template += "\nNo. members : {_count_members}" if self._count_arrays is not None: template += "\nNo. arrays : {_count_arrays}" if self._count_groups is not None: template += "\nNo. groups : {_count_groups}" return template.format(**dataclasses.asdict(self)) def human_readable_size(size: int) -> str: if size < 2**10: return f"{size}" elif size < 2**20: return f"{size / float(2**10):.1f}K" elif size < 2**30: return f"{size / float(2**20):.1f}M" elif size < 2**40: return f"{size / float(2**30):.1f}G" elif size < 2**50: return f"{size / float(2**40):.1f}T" else: return f"{size / float(2**50):.1f}P" def byte_info(size: int) -> str: if size < 2**10: return str(size) else: return f"{size} ({human_readable_size(size)})" @dataclasses.dataclass(kw_only=True, frozen=True, slots=True)
GroupInfo
python
django__django
tests/servers/tests.py
{ "start": 1850, "end": 3767 }
class ____(LiveServerBase): server_thread_class = CloseConnectionTestLiveServerThread @classmethod def _make_connections_override(cls): conn = connections[DEFAULT_DB_ALIAS] cls.conn = conn cls.old_conn_max_age = conn.settings_dict["CONN_MAX_AGE"] # Set the connection's CONN_MAX_AGE to None to simulate the # CONN_MAX_AGE setting being set to None on the server. This prevents # Django from closing the connection and allows testing that # ThreadedWSGIServer closes connections. conn.settings_dict["CONN_MAX_AGE"] = None # Pass a database connection through to the server to check it is being # closed by ThreadedWSGIServer. return {DEFAULT_DB_ALIAS: conn} @classmethod def tearDownConnectionTest(cls): cls.conn.settings_dict["CONN_MAX_AGE"] = cls.old_conn_max_age @classmethod def tearDownClass(cls): cls.tearDownConnectionTest() super().tearDownClass() def test_closes_connections(self): # The server's request thread sets this event after closing # its database connections. closed_event = self.server_thread.httpd._connections_closed conn = self.conn # Open a connection to the database. conn.connect() self.assertIsNotNone(conn.connection) with self.urlopen("/model_view/") as f: # The server can access the database. self.assertCountEqual(f.read().splitlines(), [b"jane", b"robert"]) # Wait for the server's request thread to close the connection. # A timeout of 0.1 seconds should be more than enough. If the wait # times out, the assertion after should fail. closed_event.wait(timeout=0.1) self.assertIsNone(conn.connection) @unittest.skipUnless(connection.vendor == "sqlite", "SQLite specific test.")
LiveServerTestCloseConnectionTest
python
modin-project__modin
modin/config/envvars.py
{ "start": 26545, "end": 26892 }
class ____(EnvironmentVariable, type=int): """ How much memory (in bytes) give to an execution engine. Notes ----- * In Ray case: the amount of memory to start the Plasma object store with. * In Dask case: the amount of memory that is given to each worker depending on CPUs used. """ varname = "MODIN_MEMORY"
Memory
python
pydantic__pydantic
pydantic/types.py
{ "start": 45265, "end": 46258 }
class ____(Generic[SecretType]): def __init__(self, secret_value: SecretType) -> None: self._secret_value: SecretType = secret_value def get_secret_value(self) -> SecretType: """Get the secret value. Returns: The secret value. """ return self._secret_value def __eq__(self, other: Any) -> bool: return isinstance(other, self.__class__) and self.get_secret_value() == other.get_secret_value() def __hash__(self) -> int: return hash(self.get_secret_value()) def __str__(self) -> str: return str(self._display()) def __repr__(self) -> str: return f'{self.__class__.__name__}({self._display()!r})' def _display(self) -> str | bytes: raise NotImplementedError def _serialize_secret(value: Secret[SecretType], info: core_schema.SerializationInfo) -> str | Secret[SecretType]: if info.mode == 'json': return str(value) else: return value
_SecretBase
python
encode__django-rest-framework
tests/test_serializer_nested.py
{ "start": 8551, "end": 8670 }
class ____(models.Model): profile = models.ForeignKey(NestedWriteProfile, on_delete=models.CASCADE)
NestedWritePerson
python
getsentry__sentry
src/sentry/web/frontend/error_404.py
{ "start": 207, "end": 542 }
class ____(View): def dispatch(self, request: HttpRequest, exception=None) -> HttpResponse: # HACK: We don't have any use for exception, but in Django 2.0, # signatures for 4XX handler views were changed to include it. return render_to_response("sentry/404.html", status=404, request=request)
Error404View
python
pytorch__pytorch
torch/distributed/optim/zero_redundancy_optimizer.py
{ "start": 6706, "end": 11183 }
class ____: r""" Information needed by :class:`ZeroRedundancyOptimizer` to overlap with :class:`DistributedDataParallel`. Arguments: world_size (int): world size of the process group being used. Attributes: shard_buckets (bool): if ``True``, then the assignment of each :class:`DistributedDataParallel` bucket is partitioned across possibly multiple :class:`ZeroRedundancyOptimizer` instances (i.e. across possibly multiple ranks) to approximate uniformity following a threshold given by the total parameter size divided by the world size; if ``False``, then each bucket is wholly assigned to a single :class:`ZeroRedundancyOptimizer` instance (i.e. to a single rank); this should be set to the value passed into the hook constructor. status (_OverlapStatus): current status; see :class:`_OverlapStatus` for more information. params_per_bucket (List[List[torch.Tensor]]): ``params_per_bucket[i]`` gives the model parameters in the ``i``th bucket. params_per_rank (List[List[torch.Tensor]]): ``params_per_rank[i]`` gives the model parameters assigned to the ``i``th rank, where the parameters are grouped by increasing bucket indices. offsets (Dict[int, int]): maps from bucket index to the offset in ``self.params_per_rank[rank]`` giving the index of the first parameter in that bucket, where ``rank`` is this process's own rank; the keys of this :class:`dict` are the bucket indices assigned to this rank. num_bucket_assignments (int): total number of bucket assignments across all ranks; this is equal to the number of :class:`DistributedDataParallel` gradient buckets if ``shard_buckets=False`` and possibly greater otherwise. total_size (int, optional): total size of all buckets (i.e. sum of ``param.numel()`` for all ``param`` across all buckets) if ``shard_buckets=True``; otherwise, ``None``. broadcast_handles (List[Work]): :class:`list` of async work handles for the parameter broadcasts. bucket_index_to_future (Dict[int, torch.futures.Future]): :class:`dict` mapping bucket index to the corresponding all-reduce future. bucket_index_to_bucket (Dict[int, dist.GradBucket]): :class:`dict` mapping bucket index to the corresponding bucket. bucket_indices_seen (List[int]): :class:`list` of the bucket indices seen on this iteration. """ def __init__(self, world_size) -> None: self.status: _OverlapStatus = _OverlapStatus.UNINITIALIZED self.shard_buckets: bool = False # Modified per bucket reconstruction self.params_per_bucket: list[list[torch.Tensor]] = [] self.params_per_rank: list[list[torch.Tensor]] = [[] for _ in range(world_size)] self.offsets: dict[int, int] = {} # Group Ranks self.assigned_ranks_per_bucket: list[set[int]] = [] self.num_bucket_assignments: int = 0 self.total_size: int | None = None # Modified per iteration self.broadcast_handles: list[Any] = [] self.bucket_indices_seen: list[int] = [] # Used by `hook_with_zero_step()` self.bucket_index_to_future: dict[int, torch.futures.Future] = {} self.bucket_index_to_bucket: dict[int, dist.GradBucket] = {} def wait_for_broadcasts(self) -> None: r""" Wait for all parameter broadcasts. This function should be called once all broadcasts have been scheduled, meaning ``self.broadcast_handles`` is filled. This clears ``self.broadcast_handles`` in preparation for the next iteration. """ assert len(self.broadcast_handles) == self.num_bucket_assignments, ( f"Missing at least one broadcast handle on rank {dist.get_rank()}" ) _ = [x.wait() for x in self.broadcast_handles] self.broadcast_handles.clear() def clear_per_iter_info(self) -> None: r""" Clear the data structures that are modified per-iteration. This function should be called at the end of an iteration. """ self.bucket_indices_seen.clear() self.bucket_index_to_future.clear() self.bucket_index_to_bucket.clear()
_OverlapInfo
python
django-haystack__django-haystack
test_haystack/test_altered_internal_names.py
{ "start": 395, "end": 688 }
class ____(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(model_attr="foo", document=True) name = indexes.CharField(model_attr="author") pub_date = indexes.DateTimeField(model_attr="pub_date") def get_model(self): return MockModel
MockModelSearchIndex
python
mkdocs__mkdocs
mkdocs/tests/config/config_options_tests.py
{ "start": 39544, "end": 44913 }
class ____(TestCase): def test_theme_as_string(self) -> None: class Schema(Config): option = c.Theme() conf = self.get_config(Schema, {'option': "mkdocs"}) assert_type(conf.option, Theme) assert_type(conf.option.name, Optional[str]) self.assertEqual(conf.option.name, 'mkdocs') def test_uninstalled_theme_as_string(self) -> None: class Schema(Config): theme = c.Theme() plugins = c.Plugins(theme_key='theme') with self.expect_error( theme=re.compile( r"Unrecognised theme name: 'mkdocs2'. The available installed themes are: .+" ) ): self.get_config(Schema, {'theme': "mkdocs2", 'plugins': "search"}) def test_theme_default(self) -> None: class Schema(Config): option = c.Theme(default='mkdocs') conf = self.get_config(Schema, {'option': None}) self.assertEqual(conf.option.name, 'mkdocs') def test_theme_as_simple_config(self) -> None: config = { 'name': 'mkdocs', } class Schema(Config): option = c.Theme() conf = self.get_config(Schema, {'option': config}) self.assertEqual(conf.option.name, 'mkdocs') @tempdir() def test_theme_as_complex_config(self, custom_dir) -> None: config = { 'name': 'mkdocs', 'custom_dir': custom_dir, 'static_templates': ['sitemap.html'], 'show_sidebar': False, } class Schema(Config): option = c.Theme() conf = self.get_config(Schema, {'option': config}) self.assertEqual(conf.option.name, 'mkdocs') self.assertEqual(conf.option.custom_dir, custom_dir) self.assertIn(custom_dir, conf.option.dirs) self.assertEqual( conf.option.static_templates, {'404.html', 'sitemap.xml', 'sitemap.html'}, ) self.assertEqual(conf.option['show_sidebar'], False) def test_theme_name_is_none(self) -> None: config = { 'name': None, } class Schema(Config): option = c.Theme() with self.expect_error(option="At least one of 'name' or 'custom_dir' must be defined."): self.get_config(Schema, {'option': config}) def test_theme_config_missing_name(self) -> None: config = { 'custom_dir': 'custom', } class Schema(Config): option = c.Theme() with self.expect_error(option="No theme name set."): self.get_config(Schema, {'option': config}) def test_uninstalled_theme_as_config(self) -> None: config = { 'name': 'mkdocs2', } class Schema(Config): option = c.Theme() with self.expect_error( option=re.compile( r"Unrecognised theme name: 'mkdocs2'. The available installed themes are: .+" ) ): self.get_config(Schema, {'option': config}) def test_theme_invalid_type(self) -> None: config = ['mkdocs2'] class Schema(Config): option = c.Theme() with self.expect_error( option="Invalid type <class 'list'>. Expected a string or key/value pairs." ): self.get_config(Schema, {'option': config}) def test_post_validation_none_theme_name_and_missing_custom_dir(self) -> None: config = { 'theme': { 'name': None, }, } class Schema(Config): theme = c.Theme() with self.expect_error(theme="At least one of 'name' or 'custom_dir' must be defined."): self.get_config(Schema, config) @tempdir() def test_post_validation_inexisting_custom_dir(self, abs_base_path) -> None: path = os.path.join(abs_base_path, 'inexisting_custom_dir') config = { 'theme': { 'name': None, 'custom_dir': path, }, } class Schema(Config): theme = c.Theme() with self.expect_error(theme=f"The path set in custom_dir ('{path}') does not exist."): self.get_config(Schema, config) def test_post_validation_locale_none(self) -> None: config = { 'theme': { 'name': 'mkdocs', 'locale': None, }, } class Schema(Config): theme = c.Theme() with self.expect_error(theme="'locale' must be a string."): self.get_config(Schema, config) def test_post_validation_locale_invalid_type(self) -> None: config = { 'theme': { 'name': 'mkdocs', 'locale': 0, }, } class Schema(Config): theme = c.Theme() with self.expect_error(theme="'locale' must be a string."): self.get_config(Schema, config) def test_post_validation_locale(self) -> None: config = { 'theme': { 'name': 'mkdocs', 'locale': 'fr', }, } class Schema(Config): theme = c.Theme() conf = self.get_config(Schema, config) self.assertEqual(conf.theme.locale.language, 'fr')
ThemeTest
python
apache__airflow
providers/samba/src/airflow/providers/samba/transfers/gcs_to_samba.py
{ "start": 1337, "end": 9020 }
class ____(BaseOperator): """ Transfer files from a Google Cloud Storage bucket to SMB server. .. code-block:: python with models.DAG( "example_gcs_to_smb", start_date=datetime(2020, 6, 19), schedule=None, ) as dag: # downloads file to media/folder/subfolder/file.txt copy_file_from_gcs_to_smb = GCSToSambaOperator( task_id="file-copy-gcs-to-smb", source_bucket="test-gcs-sftp-bucket-name", source_object="folder/subfolder/file.txt", destination_path="media", ) # moves file to media/data.txt move_file_from_gcs_to_smb = GCSToSambaOperator( task_id="file-move-gcs-to-smb", source_bucket="test-gcs-sftp-bucket-name", source_object="folder/subfolder/data.txt", destination_path="media", move_object=True, keep_directory_structure=False, ) .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:GCSToSambaOperator` :param source_bucket: The source Google Cloud Storage bucket where the object is. (templated) :param source_object: The source name of the object to copy in the Google cloud storage bucket. (templated) You can use only one wildcard for objects (filenames) within your bucket. The wildcard can appear inside the object name or at the end of the object name. Appending a wildcard to the bucket name is unsupported. :param destination_path: The SMB remote path. This is the specified directory path in the SMB share name for uploading files to the SMB server. :param keep_directory_structure: (Optional) When set to False the path of the file on the bucket is recreated within path passed in destination_path. :param move_object: When move object is True, the object is moved instead of copied to the new location. This is the equivalent of a mv command as opposed to a cp command. :param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud. :param samba_conn_id: The SMB connection id. The name or identifier for establishing a connection to the SMB server. :param impersonation_chain: Optional service account to impersonate using short-term credentials, or chained list of accounts required to get the access_token of the last account in the list, which will be impersonated in the request. If set as a string, the account must grant the originating account the Service Account Token Creator IAM role. If set as a sequence, the identities from the list must grant Service Account Token Creator IAM role to the directly preceding identity, with first account from the list granting this role to the originating account (templated). :param buffer_size: Optional specification of the size in bytes of the chunks sent to Samba. Larger buffer lengths may decrease the time to upload large files. The default length is determined by shutil, which is 64 KB. """ template_fields: Sequence[str] = ( "source_bucket", "source_object", "destination_path", "impersonation_chain", ) ui_color = "#f0eee4" def __init__( self, *, source_bucket: str, source_object: str, destination_path: str, keep_directory_structure: bool = True, move_object: bool = False, gcp_conn_id: str = "google_cloud_default", samba_conn_id: str = "samba_default", impersonation_chain: str | Sequence[str] | None = None, buffer_size: int | None = None, **kwargs, ) -> None: super().__init__(**kwargs) self.source_bucket = source_bucket self.source_object = source_object self.destination_path = destination_path self.keep_directory_structure = keep_directory_structure self.move_object = move_object self.gcp_conn_id = gcp_conn_id self.samba_conn_id = samba_conn_id self.impersonation_chain = impersonation_chain self.sftp_dirs = None self.buffer_size = buffer_size def execute(self, context: Context): gcs_hook = GCSHook( gcp_conn_id=self.gcp_conn_id, impersonation_chain=self.impersonation_chain, ) samba_hook = SambaHook(samba_conn_id=self.samba_conn_id) if WILDCARD in self.source_object: total_wildcards = self.source_object.count(WILDCARD) if total_wildcards > 1: raise AirflowException( "Only one wildcard '*' is allowed in source_object parameter. " f"Found {total_wildcards} in {self.source_object}." ) prefix, delimiter = self.source_object.split(WILDCARD, 1) prefix_dirname = os.path.dirname(prefix) objects = gcs_hook.list(self.source_bucket, prefix=prefix, delimiter=delimiter) # TODO: After deprecating delimiter and wildcards in source objects, # remove the previous line and uncomment the following: # match_glob = f"**/*{delimiter}" if delimiter else None # objects = gcs_hook.list(self.source_bucket, prefix=prefix, match_glob=match_glob) for source_object in objects: destination_path = self._resolve_destination_path(source_object, prefix=prefix_dirname) self._copy_single_object( gcs_hook, samba_hook, source_object, destination_path, self.buffer_size ) self.log.info("Done. Uploaded '%d' files to %s", len(objects), self.destination_path) else: destination_path = self._resolve_destination_path(self.source_object) self._copy_single_object( gcs_hook, samba_hook, self.source_object, destination_path, self.buffer_size ) self.log.info("Done. Uploaded '%s' file to %s", self.source_object, destination_path) def _resolve_destination_path(self, source_object: str, prefix: str | None = None) -> str: if not self.keep_directory_structure: if prefix: source_object = os.path.relpath(source_object, start=prefix) else: source_object = os.path.basename(source_object) return os.path.join(self.destination_path, source_object) def _copy_single_object( self, gcs_hook: GCSHook, samba_hook: SambaHook, source_object: str, destination_path: str, buffer_size: int | None = None, ) -> None: """Copy single object.""" self.log.info( "Executing copy of gs://%s/%s to %s", self.source_bucket, source_object, destination_path, ) dir_path = os.path.dirname(destination_path) samba_hook.makedirs(dir_path, exist_ok=True) with NamedTemporaryFile("w") as tmp: gcs_hook.download( bucket_name=self.source_bucket, object_name=source_object, filename=tmp.name, ) samba_hook.push_from_local(destination_path, tmp.name, buffer_size=buffer_size) if self.move_object: self.log.info("Executing delete of gs://%s/%s", self.source_bucket, source_object) gcs_hook.delete(self.source_bucket, source_object)
GCSToSambaOperator
python
python-markdown__markdown
markdown/extensions/attr_list.py
{ "start": 2478, "end": 7508 }
class ____(Treeprocessor): BASE_RE = r'\{\:?[ ]*([^\}\n ][^\n]*)[ ]*\}' HEADER_RE = re.compile(r'[ ]+{}[ ]*$'.format(BASE_RE)) BLOCK_RE = re.compile(r'\n[ ]*{}[ ]*$'.format(BASE_RE)) INLINE_RE = re.compile(r'^{}'.format(BASE_RE)) NAME_RE = re.compile(r'[^A-Z_a-z\u00c0-\u00d6\u00d8-\u00f6\u00f8-\u02ff' r'\u0370-\u037d\u037f-\u1fff\u200c-\u200d' r'\u2070-\u218f\u2c00-\u2fef\u3001-\ud7ff' r'\uf900-\ufdcf\ufdf0-\ufffd' r'\:\-\.0-9\u00b7\u0300-\u036f\u203f-\u2040]+') def run(self, doc: Element) -> None: for elem in doc.iter(): if self.md.is_block_level(elem.tag): # Block level: check for `attrs` on last line of text RE = self.BLOCK_RE if isheader(elem) or elem.tag in ['dt', 'td', 'th']: # header, def-term, or table cell: check for attributes at end of element RE = self.HEADER_RE if len(elem) and elem.tag == 'li': # special case list items. children may include a `ul` or `ol`. pos = None # find the `ul` or `ol` position for i, child in enumerate(elem): if child.tag in ['ul', 'ol']: pos = i break if pos is None and elem[-1].tail: # use tail of last child. no `ul` or `ol`. m = RE.search(elem[-1].tail) if m: if not self.assign_attrs(elem, m.group(1), strict=True): elem[-1].tail = elem[-1].tail[:m.start()] elif pos is not None and pos > 0 and elem[pos-1].tail: # use tail of last child before `ul` or `ol` m = RE.search(elem[pos-1].tail) if m: if not self.assign_attrs(elem, m.group(1), strict=True): elem[pos-1].tail = elem[pos-1].tail[:m.start()] elif elem.text: # use text. `ul` is first child. m = RE.search(elem.text) if m: if not self.assign_attrs(elem, m.group(1), strict=True): elem.text = elem.text[:m.start()] elif len(elem) and elem[-1].tail: # has children. Get from tail of last child m = RE.search(elem[-1].tail) if m: if not self.assign_attrs(elem, m.group(1), strict=True): elem[-1].tail = elem[-1].tail[:m.start()] if isheader(elem): # clean up trailing #s elem[-1].tail = elem[-1].tail.rstrip('#').rstrip() elif elem.text: # no children. Get from text. m = RE.search(elem.text) if m: if not self.assign_attrs(elem, m.group(1), strict=True): elem.text = elem.text[:m.start()] if isheader(elem): # clean up trailing #s elem.text = elem.text.rstrip('#').rstrip() else: # inline: check for `attrs` at start of tail if elem.tail: m = self.INLINE_RE.match(elem.tail) if m: remainder = self.assign_attrs(elem, m.group(1)) elem.tail = elem.tail[m.end():] + remainder def assign_attrs(self, elem: Element, attrs_string: str, *, strict: bool = False) -> str: """ Assign `attrs` to element. If the `attrs_string` has an extra closing curly brace, the remaining text is returned. The `strict` argument controls whether to still assign `attrs` if there is a remaining `}`. """ attrs, remainder = get_attrs_and_remainder(attrs_string) if strict and remainder: return remainder for k, v in attrs: if k == '.': # add to class cls = elem.get('class') if cls: elem.set('class', '{} {}'.format(cls, v)) else: elem.set('class', v) else: # assign attribute `k` with `v` elem.set(self.sanitize_name(k), v) # The text that we initially over-matched will be put back. return remainder def sanitize_name(self, name: str) -> str: """ Sanitize name as 'an XML Name, minus the `:`.' See <https://www.w3.org/TR/REC-xml-names/#NT-NCName>. """ return self.NAME_RE.sub('_', name)
AttrListTreeprocessor
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 54649, "end": 55306 }
class ____(Elemwise): _parameters = ["frame", "name"] _defaults = {"name": no_default} _keyword_only = ["name"] operation = M.to_frame _filter_passthrough = True @functools.cached_property def unique_partition_mapping_columns_from_shuffle(self): result = set() name_mapping = dict(zip(self.frame.columns, self.columns)) for elem in self.frame.unique_partition_mapping_columns_from_shuffle: if isinstance(elem, tuple): result.add(tuple(name_mapping.get(v, v) for v in elem)) else: result.add(name_mapping.get(elem, elem)) return result
ToFrame
python
tox-dev__tox
src/tox/execute/request.py
{ "start": 601, "end": 2713 }
class ____: """Defines a commands execution request.""" def __init__( # noqa: PLR0913 self, cmd: Sequence[str | Path], cwd: Path, env: dict[str, str], stdin: StdinSource, run_id: str, allow: list[str] | None = None, ) -> None: """ Create a new execution request. :param cmd: the command to run :param cwd: the current working directory :param env: the environment variables :param stdin: the type of standard input allowed :param run_id: an id to identify this run """ if len(cmd) == 0: msg = "cannot execute an empty command" raise ValueError(msg) self.cmd: list[str] = [str(i) for i in cmd] #: the command to run self.cwd = cwd #: the working directory to use self.env = env #: the environment variables to use self.stdin = stdin #: the type of standard input interaction allowed self.run_id = run_id #: an id to identify this run if allow is not None and "*" in allow: allow = None # if we allow everything we can just disable the check self.allow = allow @property def shell_cmd(self) -> str: """:return: the command to run as a shell command""" try: exe = str(Path(self.cmd[0]).relative_to(self.cwd)) except ValueError: exe = self.cmd[0] cmd = [exe] cmd.extend(self.cmd[1:]) return shell_cmd(cmd) def __repr__(self) -> str: return f"{self.__class__.__name__}(cmd={self.cmd!r}, cwd={self.cwd!r}, env=..., stdin={self.stdin!r})" def shell_cmd(cmd: Sequence[str]) -> str: if sys.platform == "win32": # pragma: win32 cover from subprocess import list2cmdline # noqa: PLC0415 return list2cmdline(tuple(str(x) for x in cmd)) # pragma: win32 no cover from shlex import quote as shlex_quote # noqa: PLC0415 return " ".join(shlex_quote(str(x)) for x in cmd) __all__ = ( "ExecuteRequest", "StdinSource", "shell_cmd", )
ExecuteRequest
python
pytorch__pytorch
torch/_dynamo/compiled_autograd.py
{ "start": 8309, "end": 9493 }
class ____: def __init__(self) -> None: self.custom_function_name_counter: Counter[str] = Counter() def add( self, name: str, fn: Callable[..., Any], is_custom_function: bool, is_traceable: bool, ) -> str: if is_custom_function: name = "CppNode" + name count = self.custom_function_name_counter[name] self.custom_function_name_counter[name] += 1 name = f"{name}{count}" assert not hasattr(self, name) result = Op(name, fn, is_custom_function) if is_traceable: setattr(self, name, torch._dynamo.allow_in_graph(result)) else: # C++ autograd function was not marked as traceable # Dynamo can't dry run it at compile time, so must fallback to eager @torch._dynamo.disable # type: ignore[misc] def run_non_traceable_cpp_in_eager(*args: Any, **kwargs: Any) -> Any: return result(*args, **kwargs) setattr(self, name, run_non_traceable_cpp_in_eager) return name def get(self, name: str) -> Any: return getattr(self, name)
OpNamespace
python
ZoranPandovski__al-go-rithms
machine_learning/Neural_Networks/python/xor_nn.py
{ "start": 106, "end": 1361 }
class ____: def __init__(self, x, y): self.neurons = 5 self.x = x self.y = y self.err = 1 self.w1 = np.random.random((x.shape[1], self.neurons)) self.w2 = np.random.random((self.neurons, y.shape[1])) def forward(self): self.a1 = sigmoid(self.x @ self.w1) self.a2 = sigmoid(self.a1 @ self.w2) return self.a2 def backprop(self): self.err = self.y - self.a2 delta2 = self.a1.T @ self.err self.w2 += delta2 delta1 = self.x.T @ ((self.err @ self.w2.T) * dsigmoid(self.a1)) self.w1 += delta1 def train(self): while abs(np.sum(self.err)) > 10e-5: #print("Error:", abs(np.sum(self.err))) self.forward() self.backprop() def predict(self, xx): self.x = xx return self.forward() if __name__ == "__main__": network = NN(np.array([[0,0],[0,1],[1,0],[1,1]]).reshape(4, 2), np.array([1, 0, 0, 1]).reshape(4,1)) network.train() print("Prediction 0.1,0.1: ", network.predict([0.1, 0.1])) print("Prediction 0.9,0.9: ", network.predict([0.9,0.9])) print("prediction 1,0.2: ", network.predict([1,0.2])) print("prediction 0,0.9:", network.predict([0,0.9]))
NN
python
PrefectHQ__prefect
src/integrations/prefect-azure/prefect_azure/credentials.py
{ "start": 10154, "end": 14275 }
class ____(Block): """ Block used to manage Cosmos DB authentication with Azure. Azure authentication is handled via the `azure` module through a connection string. Args: connection_string: Includes the authorization information required. Example: Load stored Azure Cosmos DB credentials: ```python from prefect_azure import AzureCosmosDbCredentials azure_credentials_block = AzureCosmosDbCredentials.load("BLOCK_NAME") ``` """ _block_type_name = "Azure Cosmos DB Credentials" _logo_url = "https://cdn.sanity.io/images/3ugk85nk/production/54e3fa7e00197a4fbd1d82ed62494cb58d08c96a-250x250.png" # noqa _documentation_url = "https://docs.prefect.io/integrations/prefect-azure" # noqa connection_string: SecretStr = Field( default=..., description="Includes the authorization information required." ) @_raise_help_msg("cosmos_db") def get_client(self) -> "CosmosClient": """ Returns an authenticated Cosmos client that can be used to create other clients for Azure services. Example: Create an authorized Cosmos session ```python import os from prefect import flow from prefect_azure import AzureCosmosDbCredentials @flow def example_get_client_flow(): connection_string = os.getenv("AZURE_COSMOS_CONNECTION_STRING") azure_credentials = AzureCosmosDbCredentials( connection_string=connection_string, ) cosmos_client = azure_credentials.get_client() return cosmos_client example_get_client_flow() ``` """ return CosmosClient.from_connection_string( self.connection_string.get_secret_value() ) def get_database_client(self, database: str) -> "DatabaseProxy": """ Returns an authenticated Database client. Args: database: Name of the database. Example: Create an authorized Cosmos session ```python import os from prefect import flow from prefect_azure import AzureCosmosDbCredentials @flow def example_get_client_flow(): connection_string = os.getenv("AZURE_COSMOS_CONNECTION_STRING") azure_credentials = AzureCosmosDbCredentials( connection_string=connection_string, ) cosmos_client = azure_credentials.get_database_client() return cosmos_client example_get_database_client_flow() ``` """ cosmos_client = self.get_client() database_client = cosmos_client.get_database_client(database=database) return database_client def get_container_client(self, container: str, database: str) -> "ContainerProxy": """ Returns an authenticated Container client used for querying. Args: container: Name of the Cosmos DB container to retrieve from. database: Name of the Cosmos DB database. Example: Create an authorized Container session ```python import os from prefect import flow from prefect_azure import AzureBlobStorageCredentials @flow def example_get_container_client_flow(): connection_string = os.getenv("AZURE_COSMOS_CONNECTION_STRING") azure_credentials = AzureCosmosDbCredentials( connection_string=connection_string, ) container_client = azure_credentials.get_container_client(container) return container_client example_get_container_client_flow() ``` """ database_client = self.get_database_client(database) container_client = database_client.get_container_client(container=container) return container_client
AzureCosmosDbCredentials
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1386845, "end": 1387739 }
class ____(sgqlc.types.Type, Node): """An emoji reaction to a particular piece of content.""" __schema__ = github_schema __field_names__ = ("content", "created_at", "database_id", "reactable", "user") content = sgqlc.types.Field(sgqlc.types.non_null(ReactionContent), graphql_name="content") """Identifies the emoji reaction.""" created_at = sgqlc.types.Field(sgqlc.types.non_null(DateTime), graphql_name="createdAt") """Identifies the date and time when the object was created.""" database_id = sgqlc.types.Field(Int, graphql_name="databaseId") """Identifies the primary key from the database.""" reactable = sgqlc.types.Field(sgqlc.types.non_null(Reactable), graphql_name="reactable") """The reactable piece of content""" user = sgqlc.types.Field("User", graphql_name="user") """Identifies the user who created this reaction."""
Reaction
python
pyca__cryptography
src/cryptography/x509/base.py
{ "start": 1268, "end": 2509 }
class ____(Exception): def __init__(self, msg: str, oid: ObjectIdentifier) -> None: super().__init__(msg) self.oid = oid def _reject_duplicate_extension( extension: Extension[ExtensionType], extensions: list[Extension[ExtensionType]], ) -> None: # This is quadratic in the number of extensions for e in extensions: if e.oid == extension.oid: raise ValueError("This extension has already been set.") def _reject_duplicate_attribute( oid: ObjectIdentifier, attributes: list[tuple[ObjectIdentifier, bytes, int | None]], ) -> None: # This is quadratic in the number of attributes for attr_oid, _, _ in attributes: if attr_oid == oid: raise ValueError("This attribute has already been set.") def _convert_to_naive_utc_time(time: datetime.datetime) -> datetime.datetime: """Normalizes a datetime to a naive datetime in UTC. time -- datetime to normalize. Assumed to be in UTC if not timezone aware. """ if time.tzinfo is not None: offset = time.utcoffset() offset = offset if offset else datetime.timedelta() return time.replace(tzinfo=None) - offset else: return time
AttributeNotFound
python
PrefectHQ__prefect
src/prefect/_vendor/croniter/croniter.py
{ "start": 4592, "end": 4688 }
class ____(CroniterError): """Unable to find next/prev timestamp match"""
CroniterBadDateError
python
Textualize__textual
docs/examples/widgets/markdown_viewer.py
{ "start": 1693, "end": 2007 }
class ____(App): def compose(self) -> ComposeResult: markdown_viewer = MarkdownViewer(EXAMPLE_MARKDOWN, show_table_of_contents=True) markdown_viewer.code_indent_guides = False yield markdown_viewer if __name__ == "__main__": app = MarkdownExampleApp() app.run()
MarkdownExampleApp
python
django-debug-toolbar__django-debug-toolbar
debug_toolbar/toolbar.py
{ "start": 1019, "end": 7133 }
class ____: # for internal testing use only _created = Signal() store: BaseStore = None def __init__( self, request: HttpRequest, get_response: GetResponse, request_id: str | None = None, ): self.request = request self.config = dt_settings.get_config().copy() panels = [] for panel_class in reversed(self.get_panel_classes()): panel = panel_class(self, get_response) panels.append(panel) if panel.enabled: get_response = panel.process_request self.process_request = get_response self._panels = {panel.panel_id: panel for panel in reversed(panels)} self.stats = {} self.server_timing_stats = {} self.request_id = request_id self.init_store() self._created.send(request, toolbar=self) # Manage panels @property def panels(self) -> list[Panel]: """ Get a list of all available panels. """ return list(self._panels.values()) @property def enabled_panels(self) -> list[Panel]: """ Get a list of panels enabled for the current request. """ return [panel for panel in self._panels.values() if panel.enabled] @property def csp_nonce(self) -> str | None: """ Look up the Content Security Policy nonce if there is one. """ return get_csp_nonce(self.request) def get_panel_by_id(self, panel_id: str) -> Panel: """ Get the panel with the given id, which is the class name by default. """ return self._panels[panel_id] # Handle rendering the toolbar in HTML def render_toolbar(self) -> str: """ Renders the overall Toolbar with panels inside. """ if not self.should_render_panels(): self.init_store() try: context = {"toolbar": self} lang = self.config["TOOLBAR_LANGUAGE"] or get_language() with lang_override(lang): return render_to_string("debug_toolbar/base.html", context) except TemplateSyntaxError: if not apps.is_installed("django.contrib.staticfiles"): raise ImproperlyConfigured( "The debug toolbar requires the staticfiles contrib app. " "Add 'django.contrib.staticfiles' to INSTALLED_APPS and " "define STATIC_URL in your settings." ) from None else: raise def should_render_panels(self) -> bool: """Determine whether the panels should be rendered during the request If False, the panels will be loaded via Ajax. """ return self.config["RENDER_PANELS"] or False # Handle storing toolbars in memory and fetching them later on def init_store(self): # Store already initialized. if self.store is None: self.store = get_store() if self.request_id: return self.request_id = uuid.uuid4().hex self.store.set(self.request_id) @classmethod def fetch( cls, request_id: str, panel_id: str | None = None ) -> StoredDebugToolbar | None: if get_store().exists(request_id): return StoredDebugToolbar.from_store(request_id, panel_id=panel_id) # Manually implement class-level caching of panel classes and url patterns # because it's more obvious than going through an abstraction. _panel_classes: list[Panel] | None = None @classmethod def get_panel_classes(cls) -> list[type[Panel]] | None: if cls._panel_classes is None: # Load panels in a temporary variable for thread safety. panel_classes = [ import_string(panel_path) for panel_path in dt_settings.get_panels() ] cls._panel_classes = panel_classes return cls._panel_classes _urlpatterns: list[URLPattern | URLResolver] | None = None @classmethod def get_urls(cls) -> list[URLPattern | URLResolver]: if cls._urlpatterns is None: from . import views # Load URLs in a temporary variable for thread safety. # Global URLs urlpatterns = [ path("render_panel/", views.render_panel, name="render_panel"), ] # Per-panel URLs for panel_class in cls.get_panel_classes(): urlpatterns += panel_class.get_urls() cls._urlpatterns = urlpatterns return cls._urlpatterns @classmethod def is_toolbar_request(cls, request: HttpRequest) -> bool: """ Determine if the request is for a DebugToolbar view. """ # The primary caller of this function is in the middleware which may # not have resolver_match set. try: resolver_match = request.resolver_match or resolve( request.path_info, getattr(request, "urlconf", None) ) except Resolver404: return False return ( bool(resolver_match.namespaces) and resolver_match.namespaces[-1] == APP_NAME ) @staticmethod @cache def get_observe_request() -> Callable: # If OBSERVE_REQUEST_CALLBACK is a string, which is the recommended # setup, resolve it to the corresponding callable. func_or_path = dt_settings.get_config()["OBSERVE_REQUEST_CALLBACK"] if isinstance(func_or_path, str): return import_string(func_or_path) else: return func_or_path def observe_request(request: HttpRequest) -> bool: """ Determine whether to update the toolbar from a client side request. """ return True def from_store_get_response(request: HttpRequest | None) -> None: logger.warning( "get_response was called for debug toolbar after being loaded from the store. No request exists in this scenario as the request is not stored, only the panel's data." ) return None
DebugToolbar
python
pytest-dev__pytest
src/_pytest/subtests.py
{ "start": 1749, "end": 2150 }
class ____: """The values passed to Subtests.test() that are included in the test report.""" msg: str | None kwargs: Mapping[str, Any] def _to_json(self) -> dict[str, Any]: return dataclasses.asdict(self) @classmethod def _from_json(cls, d: dict[str, Any]) -> Self: return cls(msg=d["msg"], kwargs=d["kwargs"]) @dataclasses.dataclass(init=False)
SubtestContext
python
kamyu104__LeetCode-Solutions
Python/number-of-good-leaf-nodes-pairs.py
{ "start": 1649, "end": 2502 }
class ____(object): def countPairs(self, root, distance): """ :type root: TreeNode :type distance: int :rtype: int """ def dfs(distance, node): if not node: return 0, collections.Counter() if not node.left and not node.right: return 0, collections.Counter([0]) left, right = dfs(distance, node.left), dfs(distance, node.right) result = left[0]+right[0] for left_d, left_c in left[1].iteritems(): for right_d,right_c in right[1].iteritems(): if left_d+right_d+2 <= distance: result += left_c*right_c return result, collections.Counter({k+1:v for k,v in (left[1]+right[1]).iteritems()}) return dfs(distance, root)[0]
Solution2
python
spack__spack
lib/spack/spack/vendor/pyrsistent/_pmap.py
{ "start": 192, "end": 14717 }
class ____(object): """ Persistent map/dict. Tries to follow the same naming conventions as the built in dict where feasible. Do not instantiate directly, instead use the factory functions :py:func:`m` or :py:func:`pmap` to create an instance. Was originally written as a very close copy of the Clojure equivalent but was later rewritten to closer re-assemble the python dict. This means that a sparse vector (a PVector) of buckets is used. The keys are hashed and the elements inserted at position hash % len(bucket_vector). Whenever the map size exceeds 2/3 of the containing vectors size the map is reallocated to a vector of double the size. This is done to avoid excessive hash collisions. This structure corresponds most closely to the built in dict type and is intended as a replacement. Where the semantics are the same (more or less) the same function names have been used but for some cases it is not possible, for example assignments and deletion of values. PMap implements the Mapping protocol and is Hashable. It also supports dot-notation for element access. Random access and insert is log32(n) where n is the size of the map. The following are examples of some common operations on persistent maps >>> m1 = m(a=1, b=3) >>> m2 = m1.set('c', 3) >>> m3 = m2.remove('a') >>> m1 pmap({'b': 3, 'a': 1}) >>> m2 pmap({'c': 3, 'b': 3, 'a': 1}) >>> m3 pmap({'c': 3, 'b': 3}) >>> m3['c'] 3 >>> m3.c 3 """ __slots__ = ('_size', '_buckets', '__weakref__', '_cached_hash') def __new__(cls, size, buckets): self = super(PMap, cls).__new__(cls) self._size = size self._buckets = buckets return self @staticmethod def _get_bucket(buckets, key): index = hash(key) % len(buckets) bucket = buckets[index] return index, bucket @staticmethod def _getitem(buckets, key): _, bucket = PMap._get_bucket(buckets, key) if bucket: for k, v in bucket: if k == key: return v raise KeyError(key) def __getitem__(self, key): return PMap._getitem(self._buckets, key) @staticmethod def _contains(buckets, key): _, bucket = PMap._get_bucket(buckets, key) if bucket: for k, _ in bucket: if k == key: return True return False return False def __contains__(self, key): return self._contains(self._buckets, key) get = Mapping.get def __iter__(self): return self.iterkeys() def __getattr__(self, key): try: return self[key] except KeyError as e: raise AttributeError( "{0} has no attribute '{1}'".format(type(self).__name__, key) ) from e def iterkeys(self): for k, _ in self.iteritems(): yield k # These are more efficient implementations compared to the original # methods that are based on the keys iterator and then calls the # accessor functions to access the value for the corresponding key def itervalues(self): for _, v in self.iteritems(): yield v def iteritems(self): for bucket in self._buckets: if bucket: for k, v in bucket: yield k, v def values(self): return pvector(self.itervalues()) def keys(self): return pvector(self.iterkeys()) def items(self): return pvector(self.iteritems()) def __len__(self): return self._size def __repr__(self): return 'pmap({0})'.format(str(dict(self))) def __eq__(self, other): if self is other: return True if not isinstance(other, Mapping): return NotImplemented if len(self) != len(other): return False if isinstance(other, PMap): if (hasattr(self, '_cached_hash') and hasattr(other, '_cached_hash') and self._cached_hash != other._cached_hash): return False if self._buckets == other._buckets: return True return dict(self.iteritems()) == dict(other.iteritems()) elif isinstance(other, dict): return dict(self.iteritems()) == other return dict(self.iteritems()) == dict(other.items()) __ne__ = Mapping.__ne__ def __lt__(self, other): raise TypeError('PMaps are not orderable') __le__ = __lt__ __gt__ = __lt__ __ge__ = __lt__ def __str__(self): return self.__repr__() def __hash__(self): if not hasattr(self, '_cached_hash'): self._cached_hash = hash(frozenset(self.iteritems())) return self._cached_hash def set(self, key, val): """ Return a new PMap with key and val inserted. >>> m1 = m(a=1, b=2) >>> m2 = m1.set('a', 3) >>> m3 = m1.set('c' ,4) >>> m1 pmap({'b': 2, 'a': 1}) >>> m2 pmap({'b': 2, 'a': 3}) >>> m3 pmap({'c': 4, 'b': 2, 'a': 1}) """ return self.evolver().set(key, val).persistent() def remove(self, key): """ Return a new PMap without the element specified by key. Raises KeyError if the element is not present. >>> m1 = m(a=1, b=2) >>> m1.remove('a') pmap({'b': 2}) """ return self.evolver().remove(key).persistent() def discard(self, key): """ Return a new PMap without the element specified by key. Returns reference to itself if element is not present. >>> m1 = m(a=1, b=2) >>> m1.discard('a') pmap({'b': 2}) >>> m1 is m1.discard('c') True """ try: return self.remove(key) except KeyError: return self def update(self, *maps): """ Return a new PMap with the items in Mappings inserted. If the same key is present in multiple maps the rightmost (last) value is inserted. >>> m1 = m(a=1, b=2) >>> m1.update(m(a=2, c=3), {'a': 17, 'd': 35}) pmap({'c': 3, 'b': 2, 'a': 17, 'd': 35}) """ return self.update_with(lambda l, r: r, *maps) def update_with(self, update_fn, *maps): """ Return a new PMap with the items in Mappings maps inserted. If the same key is present in multiple maps the values will be merged using merge_fn going from left to right. >>> from operator import add >>> m1 = m(a=1, b=2) >>> m1.update_with(add, m(a=2)) pmap({'b': 2, 'a': 3}) The reverse behaviour of the regular merge. Keep the leftmost element instead of the rightmost. >>> m1 = m(a=1) >>> m1.update_with(lambda l, r: l, m(a=2), {'a':3}) pmap({'a': 1}) """ evolver = self.evolver() for map in maps: for key, value in map.items(): evolver.set(key, update_fn(evolver[key], value) if key in evolver else value) return evolver.persistent() def __add__(self, other): return self.update(other) __or__ = __add__ def __reduce__(self): # Pickling support return pmap, (dict(self),) def transform(self, *transformations): """ Transform arbitrarily complex combinations of PVectors and PMaps. A transformation consists of two parts. One match expression that specifies which elements to transform and one transformation function that performs the actual transformation. >>> from spack.vendor.pyrsistent import freeze, ny >>> news_paper = freeze({'articles': [{'author': 'Sara', 'content': 'A short article'}, ... {'author': 'Steve', 'content': 'A slightly longer article'}], ... 'weather': {'temperature': '11C', 'wind': '5m/s'}}) >>> short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:25] + '...' if len(c) > 25 else c) >>> very_short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:15] + '...' if len(c) > 15 else c) >>> very_short_news.articles[0].content 'A short article' >>> very_short_news.articles[1].content 'A slightly long...' When nothing has been transformed the original data structure is kept >>> short_news is news_paper True >>> very_short_news is news_paper False >>> very_short_news.articles[0] is news_paper.articles[0] True """ return transform(self, transformations) def copy(self): return self class _Evolver(object): __slots__ = ('_buckets_evolver', '_size', '_original_pmap') def __init__(self, original_pmap): self._original_pmap = original_pmap self._buckets_evolver = original_pmap._buckets.evolver() self._size = original_pmap._size def __getitem__(self, key): return PMap._getitem(self._buckets_evolver, key) def __setitem__(self, key, val): self.set(key, val) def set(self, key, val): if len(self._buckets_evolver) < 0.67 * self._size: self._reallocate(2 * len(self._buckets_evolver)) kv = (key, val) index, bucket = PMap._get_bucket(self._buckets_evolver, key) if bucket: for k, v in bucket: if k == key: if v is not val: new_bucket = [(k2, v2) if k2 != k else (k2, val) for k2, v2 in bucket] self._buckets_evolver[index] = new_bucket return self new_bucket = [kv] new_bucket.extend(bucket) self._buckets_evolver[index] = new_bucket self._size += 1 else: self._buckets_evolver[index] = [kv] self._size += 1 return self def _reallocate(self, new_size): new_list = new_size * [None] buckets = self._buckets_evolver.persistent() for k, v in chain.from_iterable(x for x in buckets if x): index = hash(k) % new_size if new_list[index]: new_list[index].append((k, v)) else: new_list[index] = [(k, v)] # A reallocation should always result in a dirty buckets evolver to avoid # possible loss of elements when doing the reallocation. self._buckets_evolver = pvector().evolver() self._buckets_evolver.extend(new_list) def is_dirty(self): return self._buckets_evolver.is_dirty() def persistent(self): if self.is_dirty(): self._original_pmap = PMap(self._size, self._buckets_evolver.persistent()) return self._original_pmap def __len__(self): return self._size def __contains__(self, key): return PMap._contains(self._buckets_evolver, key) def __delitem__(self, key): self.remove(key) def remove(self, key): index, bucket = PMap._get_bucket(self._buckets_evolver, key) if bucket: new_bucket = [(k, v) for (k, v) in bucket if k != key] if len(bucket) > len(new_bucket): self._buckets_evolver[index] = new_bucket if new_bucket else None self._size -= 1 return self raise KeyError('{0}'.format(key)) def evolver(self): """ Create a new evolver for this pmap. For a discussion on evolvers in general see the documentation for the pvector evolver. Create the evolver and perform various mutating updates to it: >>> m1 = m(a=1, b=2) >>> e = m1.evolver() >>> e['c'] = 3 >>> len(e) 3 >>> del e['a'] The underlying pmap remains the same: >>> m1 pmap({'b': 2, 'a': 1}) The changes are kept in the evolver. An updated pmap can be created using the persistent() function on the evolver. >>> m2 = e.persistent() >>> m2 pmap({'c': 3, 'b': 2}) The new pmap will share data with the original pmap in the same way that would have been done if only using operations on the pmap. """ return self._Evolver(self) Mapping.register(PMap) Hashable.register(PMap) def _turbo_mapping(initial, pre_size): if pre_size: size = pre_size else: try: size = 2 * len(initial) or 8 except Exception: # Guess we can't figure out the length. Give up on length hinting, # we can always reallocate later. size = 8 buckets = size * [None] if not isinstance(initial, Mapping): # Make a dictionary of the initial data if it isn't already, # that will save us some job further down since we can assume no # key collisions initial = dict(initial) for k, v in initial.items(): h = hash(k) index = h % size bucket = buckets[index] if bucket: bucket.append((k, v)) else: buckets[index] = [(k, v)] return PMap(len(initial), pvector().extend(buckets)) _EMPTY_PMAP = _turbo_mapping({}, 0) def pmap(initial={}, pre_size=0): """ Create new persistent map, inserts all elements in initial into the newly created map. The optional argument pre_size may be used to specify an initial size of the underlying bucket vector. This may have a positive performance impact in the cases where you know beforehand that a large number of elements will be inserted into the map eventually since it will reduce the number of reallocations required. >>> pmap({'a': 13, 'b': 14}) pmap({'b': 14, 'a': 13}) """ if not initial and pre_size == 0: return _EMPTY_PMAP return _turbo_mapping(initial, pre_size) def m(**kwargs): """ Creates a new persistent map. Inserts all key value arguments into the newly created map. >>> m(a=13, b=14) pmap({'b': 14, 'a': 13}) """ return pmap(kwargs)
PMap
python
kamyu104__LeetCode-Solutions
Python/find-the-largest-area-of-square-inside-two-rectangles.py
{ "start": 761, "end": 1227 }
class ____(object): def largestSquareArea(self, bottomLeft, topRight): """ :type bottomLeft: List[List[int]] :type topRight: List[List[int]] :rtype: int """ return max(max(min(min(topRight[i][0], topRight[j][0])-max(bottomLeft[i][0], bottomLeft[j][0]), min(topRight[i][1], topRight[j][1])-max(bottomLeft[i][1], bottomLeft[j][1])) for i in xrange(len(bottomLeft)) for j in xrange(i+1, len(bottomLeft))), 0)**2
Solution2
python
encode__starlette
starlette/websockets.py
{ "start": 8004, "end": 8336 }
class ____: def __init__(self, code: int = 1000, reason: str | None = None) -> None: self.code = code self.reason = reason or "" async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: await send({"type": "websocket.close", "code": self.code, "reason": self.reason})
WebSocketClose
python
kamyu104__LeetCode-Solutions
Python/maximum-performance-of-a-team.py
{ "start": 65, "end": 665 }
class ____(object): def maxPerformance(self, n, speed, efficiency, k): """ :type n: int :type speed: List[int] :type efficiency: List[int] :type k: int :rtype: int """ MOD = 10**9 + 7 result, s_sum = 0, 0 min_heap = [] for e, s in sorted(itertools.izip(efficiency, speed), reverse=True): s_sum += s heapq.heappush(min_heap, s) if len(min_heap) > k: s_sum -= heapq.heappop(min_heap) result = max(result, s_sum*e) return result % MOD
Solution
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_set.py
{ "start": 56337, "end": 56630 }
class ____(_TestOnlySetsInBinaryOps, __TestCase): def setUp(self): self.set = set((1, 2, 3)) self.other = (2, 4, 6) self.otherIsIterable = True super().setUp() #------------------------------------------------------------------------------
TestOnlySetsTuple
python
openai__openai-python
src/openai/types/chat/chat_completion_content_part_refusal_param.py
{ "start": 237, "end": 467 }
class ____(TypedDict, total=False): refusal: Required[str] """The refusal message generated by the model.""" type: Required[Literal["refusal"]] """The type of the content part."""
ChatCompletionContentPartRefusalParam
python
django__django
tests/model_forms/tests.py
{ "start": 32676, "end": 33302 }
class ____(SimpleTestCase): def test_validates_with_replaced_field_not_specified(self): form = IncompleteCategoryFormWithFields( data={"name": "some name", "slug": "some-slug"} ) self.assertIs(form.is_valid(), True) def test_validates_with_replaced_field_excluded(self): form = IncompleteCategoryFormWithExclude( data={"name": "some name", "slug": "some-slug"} ) self.assertIs(form.is_valid(), True) def test_notrequired_overrides_notblank(self): form = CustomWriterForm({}) self.assertIs(form.is_valid(), True)
ValidationTest
python
pytorch__pytorch
test/distributed/test_c10d_pypg.py
{ "start": 4990, "end": 5255 }
class ____(dist._Work): """ Dummy work that is used to test blocking the current stream. """ def __init__(self): super().__init__() self.future_ = torch.futures.Future() def get_future(self): return self.future_
BlockWork
python
pennersr__django-allauth
tests/apps/socialaccount/providers/trello/tests.py
{ "start": 239, "end": 659 }
class ____(OAuthTestsMixin, TestCase): provider_id = TrelloProvider.id def get_mocked_response(self): return [ MockedResponse( HTTPStatus.OK, r""" {"id": "123", "email": "raymond.penners@example.com", "username": "pennersr", "name": "Raymond"} """, ), ] # noqa def get_expected_to_str(self): return "pennersr"
TrelloTests
python
tiangolo__fastapi
docs_src/body_multiple_params/tutorial002.py
{ "start": 236, "end": 490 }
class ____(BaseModel): username: str full_name: Union[str, None] = None @app.put("/items/{item_id}") async def update_item(item_id: int, item: Item, user: User): results = {"item_id": item_id, "item": item, "user": user} return results
User
python
Textualize__textual
docs/examples/widgets/data_table.py
{ "start": 553, "end": 844 }
class ____(App): def compose(self) -> ComposeResult: yield DataTable() def on_mount(self) -> None: table = self.query_one(DataTable) table.add_columns(*ROWS[0]) table.add_rows(ROWS[1:]) app = TableApp() if __name__ == "__main__": app.run()
TableApp