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
django__django
tests/admin_inlines/admin.py
{ "start": 2512, "end": 2588 }
class ____(PhotoInlineMixin, admin.TabularInline): pass
PhotoTabularInline
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/datacatalog.py
{ "start": 69635, "end": 74051 }
class ____(GoogleCloudBaseOperator): """ Renames a field in a tag template. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudDataCatalogRenameTagTemplateFieldOperator` :param location: Required. The location of the tag t...
CloudDataCatalogRenameTagTemplateFieldOperator
python
dagster-io__dagster
python_modules/dagster/dagster/_core/execution/context/invocation.py
{ "start": 34978, "end": 45559 }
class ____(AssetExecutionContext, BaseDirectExecutionContext): """The ``context`` object available as the first argument to an asset's compute function when being invoked directly. Can also be used as a context manager. """ def __init__(self, op_execution_context: DirectOpExecutionContext): sel...
DirectAssetExecutionContext
python
django__django
tests/db_functions/tests.py
{ "start": 303, "end": 2552 }
class ____(TestCase): def test_nested_function_ordering(self): Author.objects.create(name="John Smith") Author.objects.create(name="Rhonda Simpson", alias="ronny") authors = Author.objects.order_by(Length(Coalesce("alias", "name"))) self.assertQuerySetEqual( authors, ...
FunctionTests
python
ray-project__ray
ci/ray_ci/bisect/generic_validator.py
{ "start": 705, "end": 2333 }
class ____(Validator): def _get_buildkite(self) -> Buildkite: buildkite = Buildkite() buildkite.set_access_token( get_secret_token(get_global_config()["ci_pipeline_buildkite_secret"]), ) return buildkite def _get_rayci_select(self, test: Test) -> str: return...
GenericValidator
python
mlflow__mlflow
mlflow/utils/search_utils.py
{ "start": 47357, "end": 47882 }
class ____: def __init__(self, obj): self.obj = obj # Only need < and == are needed for use as a key parameter in the sorted function def __eq__(self, other): return other.obj == self.obj def __lt__(self, other): if self.obj is None: return False if other.ob...
_Reversor
python
tornadoweb__tornado
tornado/netutil.py
{ "start": 12349, "end": 15432 }
class ____(Configurable): """Configurable asynchronous DNS resolver interface. By default, a blocking implementation is used (which simply calls `socket.getaddrinfo`). An alternative implementation can be chosen with the `Resolver.configure <.Configurable.configure>` class method:: Resolv...
Resolver
python
kubernetes-client__python
kubernetes/client/models/v1_pod_dns_config.py
{ "start": 383, "end": 6059 }
class ____(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attri...
V1PodDNSConfig
python
mlflow__mlflow
mlflow/system_metrics/system_metrics_monitor.py
{ "start": 756, "end": 8738 }
class ____: """Class for monitoring system stats. This class is used for pulling system metrics and logging them to MLflow. Calling `start()` will spawn a thread that logs system metrics periodically. Calling `finish()` will stop the thread. Logging is done on a different frequency from pulling metrics...
SystemMetricsMonitor
python
Textualize__textual
src/textual/driver.py
{ "start": 373, "end": 10329 }
class ____(ABC): """A base class for drivers.""" def __init__( self, app: App[Any], *, debug: bool = False, mouse: bool = True, size: tuple[int, int] | None = None, ) -> None: """Initialize a driver. Args: app: The App instance. ...
Driver
python
google__jax
tests/lax_numpy_indexing_test.py
{ "start": 18044, "end": 52563 }
class ____(jtu.JaxTestCase): """Tests for Numpy indexing translation rules.""" @jtu.sample_product( [dict(name=name, shape=shape, indexer=indexer) for name, index_specs in STATIC_INDEXING_TESTS for shape, indexer, _ in index_specs], dtype=all_dtypes ) def testStaticIndexing(self, name, shape,...
IndexingTest
python
readthedocs__readthedocs.org
readthedocs/api/v3/proxied_views.py
{ "start": 171, "end": 240 }
class ____(ProxiedAPIMixin, EmbedAPIBase): pass
ProxiedEmbedAPIBase
python
streamlit__streamlit
lib/streamlit/components/v2/types.py
{ "start": 1720, "end": 12505 }
class ____(Protocol): '''Signature of the mounting command returned by ``st.components.v2.component``. This callable mounts a bidirectional component in a Streamlit app and returns a ``BidiComponentResult`` object that exposes the component's state and trigger values. For published components, thi...
BidiComponentCallable
python
facebook__pyre-check
client/language_server/tests/protocol_test.py
{ "start": 1231, "end": 1600 }
class ____(AsyncBytesWriter): """ An AsyncBytesWriter that always raises a given except when write is invoked. """ def __init__(self, exception: Exception) -> None: self.exception = exception async def write(self, data: bytes) -> None: raise self.exception async def close(self...
ExceptionRaisingBytesWriter
python
walkccc__LeetCode
solutions/2248. Intersection of Multiple Arrays/2248.py
{ "start": 0, "end": 240 }
class ____: def intersection(self, nums: list[list[int]]) -> list[int]: count = [0] * 1001 for row in nums: for a in row: count[a] += 1 return [i for i, c in enumerate(count) if c == len(nums)]
Solution
python
py-pdf__pypdf
pypdf/generic/_data_structures.py
{ "start": 39134, "end": 39186 }
class ____(StreamObject): pass
DecodedStreamObject
python
dask__distributed
distributed/comm/inproc.py
{ "start": 3715, "end": 6934 }
class ____(Comm): """ An established communication based on a pair of in-process queues. Reminder: a Comm must always be used from a single thread. Its peer Comm can be running in any thread. """ _initialized = False def __init__( # type: ignore[no-untyped-def] self, loca...
InProc
python
doocs__leetcode
solution/3100-3199/3165.Maximum Sum of Subsequence With Non-adjacent Elements/Solution.py
{ "start": 1721, "end": 2126 }
class ____: def maximumSumSubsequence(self, nums: List[int], queries: List[List[int]]) -> int: n = len(nums) tree = SegmentTree(n) for i, x in enumerate(nums, 1): tree.modify(1, i, x) ans = 0 mod = 10**9 + 7 for i, x in queries: tree.modify(1, ...
Solution
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/sparse_ops/sparse_ops_test.py
{ "start": 46658, "end": 49950 }
class ____(test_util.TensorFlowTestCase): def _assertSparseTensorValueEqual(self, a, b): self.assertAllEqual(a.indices, b.indices) self.assertAllEqual(a.values, b.values) self.assertAllEqual(a.dense_shape, b.dense_shape) def testBasic(self): with test_util.force_cpu(): # 1-D, values at index...
SparseMinimumMaximumTest
python
tensorflow__tensorflow
tensorflow/python/debug/wrappers/framework_test.py
{ "start": 15112, "end": 16637 }
class ____(test_util.TensorFlowTestCase): def testWrapperHasAllPublicMethodsOfSession(self): session_public_methods = [ method_tuple[0] for method_tuple in tf_inspect.getmembers(session.Session, predicate=tf_inspect.ismethod) if _is_public_method_name(method_tuple[0])] wrapper_public_...
SessionWrapperPublicMethodParityTest
python
ray-project__ray
python/ray/serve/_private/benchmarks/serialization/common.py
{ "start": 385, "end": 605 }
class ____(BaseModel): text: Optional[str] = None floats: Optional[List[float]] = None ints: Optional[List[int]] = None ts: Optional[float] = None reason: Optional[str] = None @dataclass
PayloadPydantic
python
jazzband__django-waffle
test_app/models.py
{ "start": 446, "end": 631 }
class ____(AbstractBaseUser): company = models.ForeignKey( Company, on_delete=CASCADE ) username = models.CharField( max_length=100, )
CompanyUser
python
chroma-core__chroma
chromadb/api/types.py
{ "start": 21422, "end": 21954 }
class ____(TypedDict): dimensionality: int # The current number of elements in the index (total = additions - deletes) curr_elements: int # The auto-incrementing ID of the last inserted element, never decreases so # can be used as a count of total historical size. Should increase by 1 every add. ...
IndexMetadata
python
mozilla__bleach
bleach/_vendor/html5lib/_inputstream.py
{ "start": 13677, "end": 21145 }
class ____(HTMLUnicodeInputStream): """Provides a unicode stream of characters to the HTMLTokenizer. This class takes care of character encoding and removing or replacing incorrect byte-sequences and also provides column and line tracking. """ def __init__(self, source, override_encoding=None, tr...
HTMLBinaryInputStream
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/genericType28.py
{ "start": 3081, "end": 3154 }
class ____(Variadic[T]): ... # This should generate an error.
VariadicChild
python
FactoryBoy__factory_boy
tests/alchemyapp/models.py
{ "start": 1098, "end": 1254 }
class ____(Base): __tablename__ = 'SpecialFieldModelTable' id = Column(Integer(), primary_key=True) session = Column(Unicode(20))
SpecialFieldModel
python
google__jax
tests/lax_autodiff_test.py
{ "start": 9308, "end": 49064 }
class ____(jtu.JaxTestCase): @parameterized.parameters(itertools.chain.from_iterable( jtu.sample_product_testcases( [dict(op=rec.op, rng_factory=rec.rng_factory, order=rec.order, tol=rec.tol)], shapes=[ shapes for shape_group in compatible_shapes for shapes in itertools.combinations_w...
LaxAutodiffTest
python
getsentry__sentry
src/sentry/tasks/check_am2_compatibility.py
{ "start": 9140, "end": 9214 }
class ____(Enum): ERROR = 0 IN_PROGRESS = 1 DONE = 2
CheckStatus
python
google__pytype
pytype/annotation_utils.py
{ "start": 518, "end": 588 }
class ____: typ: Any value: Any final: bool = False
AnnotatedValue
python
pydantic__pydantic
tests/mypy/modules/plugin_fail.py
{ "start": 2320, "end": 2498 }
class ____(BaseModel, Generic[T]): data: T error: Optional[str] response = Response[Model](data=model, error=None) response = Response[Model](data=1, error=None)
Response
python
python__mypy
mypy/test/testexportjson.py
{ "start": 486, "end": 2574 }
class ____(DataSuite): required_out_section = True files = ["exportjson.test"] def run_case(self, testcase: DataDrivenTestCase) -> None: error = False src = "\n".join(testcase.input) try: options = Options() options.use_builtins_fixtures = True op...
TypeExportSuite
python
tornadoweb__tornado
tornado/test/web_test.py
{ "start": 93998, "end": 94430 }
class ____( BaseStreamingRequestFlowControlTest, WebTestCase ): def get_handlers(self): class DecoratedFlowControlHandler(BaseFlowControlHandler): @gen.coroutine def data_received(self, data): with self.in_method("data_received"): yield gen.mom...
DecoratedStreamingRequestFlowControlTest
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/utils/sagemaker.py
{ "start": 846, "end": 1040 }
class ____(Enum): """Approval statuses for a Sagemaker Model Package.""" APPROVED = "Approved" REJECTED = "Rejected" PENDING_MANUAL_APPROVAL = "PendingManualApproval"
ApprovalStatus
python
scrapy__scrapy
tests/test_command_crawl.py
{ "start": 2721, "end": 3178 }
class ____(scrapy.Spider): name = 'myspider' async def start(self): return yield """ args = ["-o", "example1.json", "-O", "example2.json"] log = self.get_log(spider_code, proj_path, args=args) assert ( "error: Please use only one of -o/--output and -O/--overw...
MySpider
python
django__django
tests/forms_tests/tests/test_forms.py
{ "start": 232650, "end": 232853 }
class ____(BoundField): def css_classes(self, extra_classes=None): parent_classes = super().css_classes(extra_classes) return f"field-class {parent_classes}"
BoundFieldWithWrappingClass
python
huggingface__transformers
src/transformers/models/qwen2_vl/video_processing_qwen2_vl.py
{ "start": 2898, "end": 13751 }
class ____(BaseVideoProcessor): resample = PILImageResampling.BICUBIC size = {"shortest_edge": 128 * 28 * 28, "longest_edge": 28 * 28 * 768} image_mean = OPENAI_CLIP_MEAN image_std = OPENAI_CLIP_STD do_resize = True do_rescale = True do_normalize = True do_convert_rgb = True min_pixe...
Qwen2VLVideoProcessor
python
automl__auto-sklearn
test/test_pipeline/components/feature_preprocessing/test_feature_agglomeration.py
{ "start": 321, "end": 1853 }
class ____(PreprocessingTestCase): def test_default_configuration(self): transformation, original = _test_preprocessing(FeatureAgglomeration) self.assertEqual(transformation.shape[0], original.shape[0]) self.assertFalse((transformation == 0).all()) def test_default_configuration_classif...
FeatureAgglomerationComponentTest
python
patrick-kidger__equinox
equinox/nn/_dropout.py
{ "start": 197, "end": 3182 }
class ____(Module): """Applies dropout. Note that this layer behaves differently during training and inference. During training then dropout is randomly applied; during inference this layer does nothing. Whether the model is in training or inference mode should be toggled using [`equinox.nn.inferen...
Dropout
python
fluentpython__example-code-2e
21-async/mojifinder/bottle.py
{ "start": 90107, "end": 90572 }
class ____(object): def __init__(self, fp, buffer_size=1024*64): self.fp, self.buffer_size = fp, buffer_size for attr in ('fileno', 'close', 'read', 'readlines', 'tell', 'seek'): if hasattr(fp, attr): setattr(self, attr, getattr(fp, attr)) def __iter__(self): buff, read = s...
WSGIFileWrapper
python
jackfrued__Python-100-Days
Day31-35/code/example18.py
{ "start": 94, "end": 535 }
class ____(type): """自定义元类""" def __init__(cls, *args, **kwargs): cls.__instance = None cls.lock = threading.Lock() super().__init__(*args, **kwargs) def __call__(cls, *args, **kwargs): if cls.__instance is None: with cls.lock: if cls.__instance ...
SingletonMeta
python
apache__airflow
dev/breeze/tests/test_docs_version_validation.py
{ "start": 976, "end": 2290 }
class ____: def setup_method(self): os.environ["AIRFLOW_SITE_DIRECTORY"] = "/path/to/docs-archive" error_versions.clear() @patch("os.listdir") @patch("os.path.join") def test_validate_docs_version_with_invalid_versions(self, mock_path_join, mock_listdir): mock_listdir.side_effec...
TestValidateDocsVersion
python
scipy__scipy
benchmarks/benchmarks/go_benchmark_functions/go_funcs_N.py
{ "start": 1597, "end": 2771 }
class ____(Benchmark): r""" NewFunction01 objective function. This class defines the NewFunction01 [1]_ global optimization problem. This is a multimodal minimization problem defined as follows: .. math:: f_{\text{NewFunction01}}(x) = \left | {\cos\left(\sqrt{\left|{x_{1}^{2} + x_{...
NewFunction01
python
ipython__ipython
tests/test_debugger.py
{ "start": 1178, "end": 25315 }
class ____(object): """Context manager that makes testing Pdb in doctests easier.""" def __init__(self, input): self.input = input def __enter__(self): self.real_stdin = sys.stdin sys.stdin = _FakeInput(self.input) def __exit__(self, *exc): sys.stdin = self.real_stdin ...
PdbTestInput
python
facebook__pyre-check
client/commands/pyre_language_server.py
{ "start": 4864, "end": 17962 }
class ____(PyreLanguageServerApi): # Channel to send responses to the editor output_channel: connections.AsyncTextWriter # NOTE: The fields inside `server_state` are mutable and can be changed by the background # task. server_state: state.ServerState querier: daemon_querier.AbstractDaemonQueri...
PyreLanguageServer
python
huggingface__transformers
src/transformers/models/ernie/modular_ernie.py
{ "start": 12016, "end": 12086 }
class ____(BertForPreTrainingOutput): pass
ErnieForPreTrainingOutput
python
pytorch__pytorch
torch/testing/_internal/autograd_function_db.py
{ "start": 11451, "end": 12123 }
class ____(torch.autograd.Function): @staticmethod def forward(x, idx): return x[idx] @staticmethod def setup_context(ctx, inputs, output): x, idx = inputs ctx.x_shape = x.shape ctx.idx = idx @staticmethod def backward(ctx, grad_output): result = grad_ou...
Select
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/pool/base.py
{ "start": 4422, "end": 16077 }
class ____(log.Identified, event.EventTarget): """Abstract base class for connection pools.""" dispatch: dispatcher[Pool] echo: log._EchoFlagType _orig_logging_name: Optional[str] _dialect: Union[_ConnDialect, Dialect] = _ConnDialect() _creator_arg: Union[_CreatorFnType, _CreatorWRecFnType] ...
Pool
python
doocs__leetcode
lcci/16.07.Maximum/Solution.py
{ "start": 0, "end": 157 }
class ____: def maximum(self, a: int, b: int) -> int: k = (int(((a - b) & 0xFFFFFFFFFFFFFFFF) >> 63)) & 1 return a * (k ^ 1) + b * k
Solution
python
matplotlib__matplotlib
lib/matplotlib/colors.py
{ "start": 108376, "end": 110086 }
class ____(Normalize): """ Arbitrary normalization using functions for the forward and inverse. Parameters ---------- functions : (callable, callable) two-tuple of the forward and inverse functions for the normalization. The forward function must be monotonic. Both function...
FuncNorm
python
getsentry__sentry
src/sentry/dynamic_sampling/tasks/boost_low_volume_transactions.py
{ "start": 8134, "end": 11970 }
class ____: """ Fetches the total number of transactions and the number of distinct transaction types for each project in the given organizations """ def __init__(self, orgs: Sequence[int]): transaction_string_id = indexer.resolve_shared_org("transaction") self.transaction_tag = f"t...
FetchProjectTransactionTotals
python
huggingface__transformers
src/transformers/models/dinov2_with_registers/modular_dinov2_with_registers.py
{ "start": 8302, "end": 8378 }
class ____(Dinov2PatchEmbeddings): pass
Dinov2WithRegistersPatchEmbeddings
python
tornadoweb__tornado
tornado/testing.py
{ "start": 13493, "end": 18102 }
class ____(AsyncTestCase): """A test case that starts up an HTTP server. Subclasses must override `get_app()`, which returns the `tornado.web.Application` (or other `.HTTPServer` callback) to be tested. Tests will typically use the provided ``self.http_client`` to fetch URLs from this server. ...
AsyncHTTPTestCase
python
RaRe-Technologies__gensim
gensim/models/fasttext.py
{ "start": 38583, "end": 55108 }
class ____(KeyedVectors): def __init__(self, vector_size, min_n, max_n, bucket, count=0, dtype=REAL): """Vectors and vocab for :class:`~gensim.models.fasttext.FastText`. Implements significant parts of the FastText algorithm. For example, the :func:`word_vec` calculates vectors for out-of-...
FastTextKeyedVectors
python
openai__gym
gym/vector/sync_vector_env.py
{ "start": 357, "end": 8760 }
class ____(VectorEnv): """Vectorized environment that serially runs multiple environments. Example:: >>> import gym >>> env = gym.vector.SyncVectorEnv([ ... lambda: gym.make("Pendulum-v0", g=9.81), ... lambda: gym.make("Pendulum-v0", g=1.62) ... ]) >>> e...
SyncVectorEnv
python
crytic__slither
slither/solc_parsing/yul/parse_yul.py
{ "start": 6529, "end": 7204 }
class ____: # pylint: disable=too-few-public-methods __slots__ = ["_variable", "_root"] def __init__(self, var: LocalVariable, root: YulScope, ast: Dict) -> None: assert ast["nodeType"] == "YulTypedName" self._variable = var self._root = root # start initializing the underlyi...
YulLocalVariable
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/asset_selection.py
{ "start": 48046, "end": 48789 }
class ____(AssetSelection): selected_key_substring: str include_sources: bool def resolve_inner( self, asset_graph: BaseAssetGraph, allow_missing: bool ) -> AbstractSet[AssetKey]: base_set = ( asset_graph.get_all_asset_keys() if self.include_sources e...
KeySubstringAssetSelection
python
Pylons__pyramid
src/pyramid/path.py
{ "start": 3851, "end": 7917 }
class ____(Resolver): """A class used to resolve an :term:`asset specification` to an :term:`asset descriptor`. .. versionadded:: 1.3 The constructor accepts a single argument named ``package`` which may be any of: - A fully qualified (not relative) dotted name to a module or package - a...
AssetResolver
python
PrefectHQ__prefect
tests/utilities/test_callables.py
{ "start": 25276, "end": 49831 }
class ____: def test_function_not_found(self, tmp_path: Path): source_code = dedent( """ def f(): pass """ ) tmp_path.joinpath("test.py").write_text(source_code) with pytest.raises(ValueError): callables.parameter_schema_from_entry...
TestEntrypointToSchema
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 67185, "end": 67639 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.conv1 = torch.nn.Conv2d(3, 5, 3, bias=False).to(dtype=torch.float) self.conv2 = torch.nn.Conv2d(5, 5, 1, bias=False).to(dtype=torch.float) def forward(self, x): x = self.conv1(x) x = self.co...
TwoLayerConvModel
python
apache__airflow
providers/google/tests/unit/google/cloud/transfers/test_gcs_to_bigquery.py
{ "start": 3253, "end": 69534 }
class ____: @mock.patch(GCS_TO_BQ_PATH.format("BigQueryHook")) def test_max_value_external_table_should_execute_successfully(self, hook): hook.return_value.insert_job.side_effect = [ MagicMock(job_id=REAL_JOB_ID, error_result=False), REAL_JOB_ID, ] hook.return_val...
TestGCSToBigQueryOperator
python
pytest-dev__pytest-mock
tests/test_pytest_mock.py
{ "start": 1264, "end": 1541 }
class ____: """ Wrapper to os functions to simulate a Unix file system, used for testing the mock fixture. """ @classmethod def rm(cls, filename): os.remove(filename) @classmethod def ls(cls, path): return os.listdir(path)
UnixFS
python
sympy__sympy
sympy/stats/matrix_distributions.py
{ "start": 2665, "end": 4196 }
class ____: """Returns the sample from scipy of the given distribution""" def __new__(cls, dist, size, seed=None): return cls._sample_scipy(dist, size, seed) @classmethod def _sample_scipy(cls, dist, size, seed): """Sample from SciPy.""" from scipy import stats as scipy_stats ...
SampleMatrixScipy
python
pydantic__pydantic
pydantic-core/tests/validators/test_model_fields.py
{ "start": 52122, "end": 68742 }
class ____: def test_on_error_bad_default(self): with pytest.raises(SchemaError, match="'on_error = default' requires a `default` or `default_factory`"): SchemaValidator( schema=core_schema.model_fields_schema( fields={ 'x': core_schema...
TestOnError
python
mlflow__mlflow
mlflow/entities/span_status.py
{ "start": 324, "end": 1882 }
class ____(str, Enum): """Enum for status code of a span""" # Uses the same set of status codes as OpenTelemetry UNSET = "UNSET" OK = "OK" ERROR = "ERROR" def to_otel_proto_status_code_name(self) -> str: """ Convert the SpanStatusCode to the corresponding OpenTelemetry protobuf...
SpanStatusCode
python
gevent__gevent
src/gevent/threadpool.py
{ "start": 9189, "end": 22453 }
class ____(GroupMappingMixin): """ A pool of native worker threads. This can be useful for CPU intensive functions, or those that otherwise will not cooperate with gevent. The best functions to execute in a thread pool are small functions with a single purpose; ideally they release the CPython ...
ThreadPool
python
explosion__spaCy
spacy/lang/eu/__init__.py
{ "start": 161, "end": 294 }
class ____(BaseDefaults): suffixes = TOKENIZER_SUFFIXES stop_words = STOP_WORDS lex_attr_getters = LEX_ATTRS
BasqueDefaults
python
Farama-Foundation__Gymnasium
gymnasium/envs/functional_jax_env.py
{ "start": 510, "end": 3294 }
class ____(gym.Env, Generic[StateType]): """A conversion layer for jax-based environments.""" state: StateType rng: PRNGKeyType def __init__( self, func_env: FuncEnv, metadata: dict[str, Any] | None = None, render_mode: str | None = None, spec: EnvSpec | None = ...
FunctionalJaxEnv
python
TheAlgorithms__Python
graphs/depth_first_search_2.py
{ "start": 48, "end": 3319 }
class ____: def __init__(self): self.vertex = {} # for printing the Graph vertices def print_graph(self) -> None: """ Print the graph vertices. Example: >>> g = Graph() >>> g.add_edge(0, 1) >>> g.add_edge(0, 2) >>> g.add_edge(1, 2) >>...
Graph
python
airbytehq__airbyte
airbyte-integrations/connectors/source-gridly/source_gridly/source.py
{ "start": 2712, "end": 4288 }
class ____(AbstractSource): def check_connection(self, logger, config) -> Tuple[bool, any]: api_key = config.get("api_key") grid_id = config.get("grid_id") auth = TokenAuthenticator(auth_method="ApiKey", token=api_key) logger.info(f"Checking connection on grid {grid_id}") He...
SourceGridly
python
ApeWorX__ape
src/ape_pm/project.py
{ "start": 571, "end": 4224 }
class ____(ProjectAPI): """ Allows traditional Brownie projects to work with Ape. This class implements the necessary methods in order to detect config settings in a Brownie project and treat it like an Ape project. """ @property def brownie_config_file(self) -> Path: return sel...
BrownieProject
python
pytorch__pytorch
torch/testing/_internal/distributed/rpc/rpc_test.py
{ "start": 16299, "end": 17464 }
class ____: def __init__(self, trainers): self.lock = Lock() self.trainers = trainers self.iteration = 0 self.updates = 0 self.futures = [] self.total = None self.gradient = None @staticmethod def get_gradient(rref): return rref.local_value()....
MyParameterServer
python
gevent__gevent
src/gevent/monkey/_errors.py
{ "start": 145, "end": 425 }
class ____(AttributeError): """ Raised when ``__implements__`` is incorrect. """ def __init__(self, module): AttributeError.__init__( self, "Module %r has a bad or missing value for __implements__" % (module,) )
_BadImplements
python
ansible__ansible
lib/ansible/module_utils/facts/hardware/base.py
{ "start": 2003, "end": 2724 }
class ____(BaseFactCollector): name = 'hardware' _fact_ids = set(['processor', 'processor_cores', 'processor_count', # TODO: mounts isn't exactly hardware 'mounts', 'devices']) # type: t.Set[str] _fact_...
HardwareCollector
python
plotly__plotly.py
plotly/graph_objs/carpet/aaxis/_tickfont.py
{ "start": 233, "end": 9881 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "carpet.aaxis" _path_str = "carpet.aaxis.tickfont" _valid_props = { "color", "family", "lineposition", "shadow", "size", "style", "textcase", "variant", "weight", } @prope...
Tickfont
python
langchain-ai__langchain
libs/langchain/langchain_classic/agents/agent.py
{ "start": 20143, "end": 22697 }
class ____(BaseSingleActionAgent): """Base class for single action agents.""" llm_chain: LLMChain """LLMChain to use for agent.""" output_parser: AgentOutputParser """Output parser to use for agent.""" stop: list[str] """List of strings to stop on.""" @property def input_keys(self)...
LLMSingleActionAgent
python
geekcomputers__Python
nitkarshchourasia/to_sort/determine_sign.py
{ "start": 436, "end": 1827 }
class ____: def __init__(self, num=None): if num is None: self.get_number() else: self.num = round(self.convert_to_float(num), 1) # TODO: Word2number # Need to further understand this. # ? NEED TO UNDERSTAND THIS. FOR SURETY. def convert_to_float(self, input...
DetermineSign
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 357853, "end": 358597 }
class ____(sgqlc.types.Input): """Autogenerated input type of UpdateProjectCard""" __schema__ = github_schema __field_names__ = ("project_card_id", "is_archived", "note", "client_mutation_id") project_card_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectCardId") """The Project...
UpdateProjectCardInput
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 1209713, "end": 1210127 }
class ____(sgqlc.types.Type, Node): """Represents a given language found in repositories.""" __schema__ = github_schema __field_names__ = ("color", "name") color = sgqlc.types.Field(String, graphql_name="color") """The color defined for the current language.""" name = sgqlc.types.Field(sgqlc.t...
Language
python
jina-ai__jina
jina/proto/docarray_v1/pb/jina_pb2_grpc.py
{ "start": 24547, "end": 25082 }
class ____(object): """* jina gRPC service to trigger a snapshot at the Executor Runtime. """ def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.restore_status = channel.unary_unary( '/jina.JinaExecutorRestorePro...
JinaExecutorRestoreProgressStub
python
gevent__gevent
src/gevent/tests/test__compat.py
{ "start": 1295, "end": 1439 }
class ____(TestFSPath): def _callFUT(self, arg): return os.fspath(arg) if __name__ == '__main__': unittest.main()
TestNativeFSPath
python
wandb__wandb
wandb/errors/term.py
{ "start": 1759, "end": 10429 }
class ____(Protocol): """Portion of the standard logging.Logger used in this module.""" def info(self, msg: str) -> None: ... def warning(self, msg: str) -> None: ... def error(self, msg: str) -> None: ... def termsetup( settings: wandb.Settings, logger: SupportsLeveledLogging | None, ) -> No...
SupportsLeveledLogging
python
pytorch__pytorch
torch/ao/nn/quantized/modules/batchnorm.py
{ "start": 3156, "end": 4519 }
class ____(_BatchNorm): r"""This is the quantized version of :class:`~torch.nn.BatchNorm3d`.""" _NNI_BN_RELU_MODULE = nni.BNReLU3d def __init__(self, num_features, eps=1e-5, momentum=0.1, device=None, dtype=None): factory_kwargs = {"device": device, "dtype": dtype} super().__init__(num_fea...
BatchNorm3d
python
run-llama__llama_index
llama-index-core/llama_index/core/voice_agents/base.py
{ "start": 312, "end": 5197 }
class ____(ABC): """ Abstract class that serves as base for any Voice Agent. Attributes: ws (BaseVoiceAgentWebSocket): The websocket underlying the agent and providing the voice service. interface (BaseVoiceAgentInterface): The audio input/output interface. api_key (Optional[str]): ...
BaseVoiceAgent
python
Netflix__metaflow
metaflow/parameters.py
{ "start": 8843, "end": 9993 }
class ____(object): """ This is a very simple wrapper to allow parameter "conversion" to be delayed until the `_set_constants` function in FlowSpec. Typically, parameters are converted by click when the command line option is processed. For some parameters, like IncludeFile, this is too early as it ...
DelayedEvaluationParameter
python
keras-team__keras
keras/src/ops/einops.py
{ "start": 2587, "end": 6268 }
class ____(Operation): def call(self, tensor, pattern, **axes_lengths): return rearrange(tensor, pattern, **axes_lengths) def compute_output_spec(self, tensor, pattern, **axes_lengths): input_pattern, output_pattern = re.split(r"\s*->\s*", pattern) input_axes = re.findall(r"\w+|\(.*?\)"...
Rearrange
python
tensorflow__tensorflow
tensorflow/python/tools/api/generator2/generator/generator_test.py
{ "start": 1872, "end": 14870 }
class ____(parameterized.TestCase): def test_get_public_api(self): tmp_dir = self.create_tempdir() write_test_data(tmp_dir.full_path) expected_tensor_top_level = generator._Entrypoint( module='tf', name='Tensor', exported_symbol=tensor_es, ) expected = generator.PublicAP...
GeneratorTest
python
getsentry__sentry-python
sentry_sdk/worker.py
{ "start": 360, "end": 4464 }
class ____: def __init__(self, queue_size=DEFAULT_QUEUE_SIZE): # type: (int) -> None self._queue = Queue(queue_size) # type: Queue self._lock = threading.Lock() self._thread = None # type: Optional[threading.Thread] self._thread_for_pid = None # type: Optional[int] @p...
BackgroundWorker
python
spack__spack
lib/spack/spack/error.py
{ "start": 6004, "end": 6400 }
class ____(SpackError): """ Raised if file fails checksum verification. """ def __init__(self, path, size, contents, algorithm, expected, computed): super().__init__( f"{algorithm} checksum failed for {path}", f"Expected {expected} but got {computed}. " f"Fil...
NoChecksumException
python
mlflow__mlflow
mlflow/genai/judges/tools/search_trace_regex.py
{ "start": 618, "end": 806 }
class ____: """Represents a single regex match found in a trace.""" span_id: str matched_text: str surrounding_text: str @experimental(version="3.4.0") @dataclass
RegexMatch
python
PrefectHQ__prefect
tests/test_task_engine.py
{ "start": 27730, "end": 28429 }
class ____: async def test_return_state(self, prefect_client): @task async def foo(): return 42 state = await run_task_async(foo, return_type="state") assert isinstance(state, State) assert state.is_completed() assert await state.result() == 42 as...
TestReturnState
python
tiangolo__fastapi
tests/test_jsonable_encoder.py
{ "start": 712, "end": 826 }
class ____(Person): def __iter__(self): return ((k, v) for k, v in self.__dict__.items())
DictablePerson
python
pyca__cryptography
src/cryptography/hazmat/primitives/serialization/ssh.py
{ "start": 18985, "end": 27447 }
class ____: """ The format of a sk-ecdsa-sha2-nistp256@openssh.com public key is: string "sk-ecdsa-sha2-nistp256@openssh.com" string curve name ec_point Q string application (user-specified, but typically "ssh:") """ def load_public( self, data: memoryview ...
_SSHFormatSKECDSA
python
realpython__materials
python-yaml/models.py
{ "start": 129, "end": 316 }
class ____: __slots__ = ["name"] def __init__(self, name): self.name = name def __setstate__(self, state): self.name = codecs.decode(state["name"], "rot13")
User
python
django__django
tests/admin_views/test_autocomplete_view.py
{ "start": 999, "end": 1106 }
class ____(admin.TabularInline): model = Authorship autocomplete_fields = ["author"]
AuthorshipInline
python
facebookresearch__faiss
tests/test_meta_index.py
{ "start": 1793, "end": 5872 }
class ____(unittest.TestCase): @unittest.skipIf(os.name == "posix" and os.uname().sysname == "Darwin", "There is a bug in the OpenMP implementation on OSX.") def test_shards(self): k = 32 ref_index = faiss.IndexFlatL2(d) ref_index.add(xb) _Dref, Iref = ref_...
Shards
python
numpy__numpy
numpy/f2py/tests/test_regression.py
{ "start": 5762, "end": 6182 }
class ____(util.F2PyTest): # Ensure that variables are exposed without functions or subroutines in a module sources = [util.getpath("tests", "src", "regression", "assignOnlyModule.f90")] @pytest.mark.slow def test_gh27167(self): assert (self.module.f_globals.n_max == 16) assert (self.mo...
TestAssignmentOnlyModules
python
ansible__ansible
lib/ansible/_internal/_errors/_handler.py
{ "start": 1689, "end": 3455 }
class ____: """ Provides a configurable error handler context manager for a specific list of exception types. Unhandled errors leaving the context manager can be ignored, treated as warnings, or allowed to raise by setting `ErrorAction`. """ def __init__(self, action: ErrorAction) -> None: ...
ErrorHandler
python
walkccc__LeetCode
solutions/3485. Longest Common Prefix of K Strings After Removal/3485.py
{ "start": 1051, "end": 1354 }
class ____: def longestCommonPrefix(self, words: list[str], k: int) -> list[int]: ans = [] trie = Trie(k) for word in words: trie.insert(word) for word in words: trie.erase(word) ans.append(trie.getLongestCommonPrefix()) trie.insert(word) return ans
Solution
python
conda__conda
conda/models/match_spec.py
{ "start": 3461, "end": 33116 }
class ____(metaclass=MatchSpecType): """The query language for conda packages. Any of the fields that comprise a :class:`PackageRecord` can be used to compose a :class:`MatchSpec`. :class:`MatchSpec` can be composed with keyword arguments, where keys are any of the attributes of :class:`PackageRec...
MatchSpec
python
pytorch__pytorch
torch/_higher_order_ops/aoti_call_delegate.py
{ "start": 643, "end": 6126 }
class ____(HigherOrderOperator): """aoti_call_delegate is a HOP for calling AOTInductor lowered submodule in ExportedProgram. It has the following signature: aoti_call_delegate( lowered_module: Union[AOTInductorEPModule, AOTInductorRunnerWrapper] original_gm:fx.GraphModule, weight_a...
AOTICallDelegate