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
scrapy__scrapy
tests/test_command_runspider.py
{ "start": 10070, "end": 10765 }
class ____(scrapy.Spider): name = 'myspider' @classmethod def from_crawler(cls, crawler, *args, **kwargs): spider = super().from_crawler(crawler, *args, **kwargs) spider.settings.set("FOO", kwargs.get("foo")) return spider async def start(self): self.logger.info(f"The v...
MySpider
python
hynek__structlog
tests/test_twisted.py
{ "start": 8173, "end": 8373 }
class ____: def test_repr(self): """ The repr of the wrapped string is the vanilla string without quotes. """ assert "foo" == repr(ReprWrapper("foo"))
TestReprWrapper
python
facebookresearch__faiss
tests/test_index_accuracy.py
{ "start": 10562, "end": 12742 }
class ____(unittest.TestCase): def subtest_8bit_direct(self, metric_type, d, quantizer_type): xt, xb, xq = get_dataset_2(d, 500, 1000, 30) # rescale everything to get integer tmin, tmax = xt.min(), xt.max() def rescale(x): x = np.floor((x - tmin) * 256 / (tmax - tmin)) ...
TestSQByte
python
tensorflow__tensorflow
tensorflow/python/keras/initializers/initializers_v2.py
{ "start": 11658, "end": 13899 }
class ____(Initializer): """Initializer that generates a truncated normal distribution. Also available via the shortcut function `tf.keras.initializers.truncated_normal`. The values generated are similar to values from a `tf.keras.initializers.RandomNormal` initializer except that values more than two sta...
TruncatedNormal
python
sqlalchemy__sqlalchemy
test/orm/test_selectin_relations.py
{ "start": 65805, "end": 70779 }
class ____(fixtures.DeclarativeMappedTest): @classmethod def setup_classes(cls): Base = cls.DeclarativeBasic class Company(Base): __tablename__ = "company" id = Column(Integer, primary_key=True) name = Column(String(50)) employees = relationship("...
HeterogeneousSubtypesTest
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI045.py
{ "start": 1374, "end": 1476 }
class ____: def __aiter__(self) -> typing.AsyncIterable[int]: ...
TypingAsyncIterableTReturn
python
wandb__wandb
wandb/sdk/artifacts/_generated/project_artifact_collection.py
{ "start": 259, "end": 361 }
class ____(GQLResult): project: Optional[ProjectArtifactCollectionProject]
ProjectArtifactCollection
python
dagster-io__dagster
python_modules/libraries/dagster-gcp-pyspark/dagster_gcp_pyspark/bigquery/bigquery_pyspark_type_handler.py
{ "start": 1131, "end": 7348 }
class ____(DbTypeHandler[DataFrame]): """Plugin for the BigQuery I/O Manager that can store and load PySpark DataFrames as BigQuery tables. Examples: .. code-block:: python from dagster_gcp import BigQueryIOManager from dagster_bigquery_pandas import BigQueryPySparkTypeHandler ...
BigQueryPySparkTypeHandler
python
django__django
tests/queries/models.py
{ "start": 9494, "end": 9714 }
class ____(models.Model): name = models.CharField(max_length=50) objecta = models.ForeignKey(ObjectA, models.CASCADE) num = models.PositiveIntegerField() def __str__(self): return self.name
ObjectB
python
pytorch__pytorch
torch/distributions/independent.py
{ "start": 372, "end": 5019 }
class ____(Distribution, Generic[D]): r""" Reinterprets some of the batch dims of a distribution as event dims. This is mainly useful for changing the shape of the result of :meth:`log_prob`. For example to create a diagonal Normal distribution with the same shape as a Multivariate Normal distribut...
Independent
python
numba__numba
numba/core/typing/npdatetime.py
{ "start": 7947, "end": 8033 }
class ____(DatetimeCmpOp): key = operator.eq @infer_global(operator.ne)
DatetimeCmpEq
python
fastai__fastai
fastai/optimizer.py
{ "start": 3731, "end": 15942 }
class ____(_BaseOptimizer): "Base optimizer class for the fastai library, updating `params` with `cbs`" _keep_on_clear = ['force_train', 'do_wd'] def __init__(self, params:Tensor|Iterable, # Model parameters cbs:Callable|MutableSequence, # `Optimizer` step callbacks **defaults # Hype...
Optimizer
python
getsentry__sentry
src/sentry/features/manager.py
{ "start": 936, "end": 5070 }
class ____: """ Feature functions that are built around the need to register feature handlers TODO: Once features have been audited and migrated to the entity handler, remove this class entirely """ def __init__(self) -> None: self._handler_registry: dict[str, list[FeatureHandler]]...
RegisteredFeatureManager
python
getsentry__sentry
src/sentry/releases/endpoints/release_deploys.py
{ "start": 1197, "end": 1927 }
class ____(serializers.Serializer): """Serializer for Deploy response objects""" id = serializers.CharField(help_text="The ID of the deploy") environment = serializers.CharField(help_text="The environment name") dateStarted = serializers.DateTimeField( allow_null=True, help_text="An optional da...
DeployResponseSerializer
python
realpython__materials
python-protocol/animals_v1.py
{ "start": 280, "end": 361 }
class ____(Animal): def meow(self): print(f"{self.name} is meowing.")
Cat
python
pandas-dev__pandas
pandas/tests/scalar/timestamp/methods/test_round.py
{ "start": 395, "end": 12705 }
class ____: def test_round_division_by_zero_raises(self): ts = Timestamp("2016-01-01") msg = "Division by zero in rounding" with pytest.raises(ValueError, match=msg): ts.round("0ns") @pytest.mark.parametrize( "timestamp, freq, expected", [ ("2013...
TestTimestampRound
python
huggingface__transformers
src/transformers/models/megatron_bert/modeling_megatron_bert.py
{ "start": 20030, "end": 20839 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) if isinstance(config.hidden_act, str): self.transform_act_fn = ACT2FN[config.hidden_act] else: self.transform_act_fn = config.h...
MegatronBertPredictionHeadTransform
python
python-poetry__poetry
tests/plugins/test_plugin_manager.py
{ "start": 1749, "end": 1842 }
class ____(ApplicationPlugin): commands: ClassVar[list[type[Command]]] = []
MyCommandPlugin
python
getsentry__sentry
src/sentry/rules/filters/latest_release.py
{ "start": 1886, "end": 4292 }
class ____(EventFilter): id = "sentry.rules.filters.latest_release.LatestReleaseFilter" label = "The event is from the latest release" def get_latest_release(self, event: GroupEvent) -> Release | None: environment_id = None if self.rule is None else self.rule.environment_id cache_key = get_...
LatestReleaseFilter
python
openai__gym
gym/error.py
{ "start": 1727, "end": 1887 }
class ____(Error): """When the monitor is active, raised when the user tries to step an environment that's not yet terminated or truncated."""
ResetNotAllowed
python
fabric__fabric
fabric/transfer.py
{ "start": 13018, "end": 14760 }
class ____: """ A container for information about the result of a file transfer. See individual attribute/method documentation below for details. .. note:: Unlike similar classes such as `invoke.runners.Result` or `fabric.runners.Result` (which have a concept of "warn and return ...
Result
python
numba__numba
numba/misc/help/inspector.py
{ "start": 5855, "end": 7798 }
class ____(Formatter): """Formatter that outputs HTML """ def escape(self, text): import html return html.escape(text) def title(self, text): self.print('<h1>', text, '</h2>') def begin_module_section(self, modname): self.print('<h2>', modname, '</h2>') sel...
HTMLFormatter
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/common.py
{ "start": 3537, "end": 4006 }
class ____(StrictBaseModel, Generic[T]): """Serializer for bulk entity operations.""" actions: list[ Annotated[ Union[ Annotated[BulkCreateAction[T], Tag(BulkAction.CREATE.value)], Annotated[BulkUpdateAction[T], Tag(BulkAction.UPDATE.value)], ...
BulkBody
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-guru/llama_index/readers/guru/base.py
{ "start": 365, "end": 5459 }
class ____(BaseReader): """Guru cards / collections reader.""" def __init__(self, guru_username: str, api_token: str) -> None: """ Initialize GuruReader. Args: guru_username: Guru username. api_token: Guru API token. This can be personal API keys or collection b...
GuruReader
python
joke2k__faker
faker/providers/lorem/he_IL/__init__.py
{ "start": 68, "end": 2655 }
class ____(LoremProvider): """Implement lorem provider for ``he_IL`` locale.""" word_list = ( "אאוגו", "אגת", "אדיפיסינג", "אדנדום", "אט", "איאקוליס", "איבן", "איף", "איפסום", "אלית", "אלמנקום", "אמט", "אס",...
Provider
python
dagster-io__dagster
python_modules/dagster/dagster/_core/scheduler/instigation.py
{ "start": 1366, "end": 1739 }
class ____(EnumSerializer): def unpack(self, value: str): if value == InstigatorStatus.AUTOMATICALLY_RUNNING.name: value = InstigatorStatus.DECLARED_IN_CODE.name return super().unpack(value) @whitelist_for_serdes( serializer=InstigatorStatusBackcompatSerializer, old_storage_na...
InstigatorStatusBackcompatSerializer
python
boto__boto3
boto3/resources/action.py
{ "start": 865, "end": 3546 }
class ____: """ A class representing a callable action on a resource, for example ``sqs.get_queue_by_name(...)`` or ``s3.Bucket('foo').delete()``. The action may construct parameters from existing resource identifiers and may return either a raw response or a new resource instance. :type action...
ServiceAction
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 908854, "end": 911245 }
class ____( sgqlc.types.Type, Node, Comment, Deletable, Updatable, UpdatableComment, Reactable, RepositoryNode, ): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ( "author_can_push_to_repository", "comments", ...
PullRequestReview
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/layout/containers.py
{ "start": 46631, "end": 94414 }
class ____(Container): """ Container that holds a control. :param content: :class:`.UIControl` instance. :param width: :class:`.Dimension` instance or callable. :param height: :class:`.Dimension` instance or callable. :param z_index: When specified, this can be used to bring element in front ...
Window
python
getsentry__sentry
src/sentry/monitors/types.py
{ "start": 433, "end": 484 }
class ____(TypedDict): trace_id: str
CheckinTrace
python
pytorch__pytorch
torch/distributed/tensor/debug/_comm_mode.py
{ "start": 2189, "end": 7938 }
class ____(ModTracker): """ Inherits ModuleTracker and expands on its functionality to track the parameters and sharding information of a model at a module-level """ def __init__(self): super().__init__() self.module_helper_dict = {} self.module_parameters_dict = {} ...
_CommModeModuleTracker
python
numba__numba
numba/core/types/containers.py
{ "start": 5359, "end": 5802 }
class ____(Sequence, BaseTuple): @property def iterator_type(self): return UniTupleIter(self) def __getitem__(self, i): """ Return element at position i """ return self.dtype def __iter__(self): return iter([self.dtype] * self.count) def __len__(sel...
_HomogeneousTuple
python
dask__distributed
distributed/worker_state_machine.py
{ "start": 21398, "end": 21499 }
class ____(StateMachineEvent): worker: str __slots__ = ("worker",) @dataclass
RemoveWorkerEvent
python
getsentry__sentry
src/sentry/users/api/serializers/user.py
{ "start": 1938, "end": 2189 }
class ____(int, Enum): DEFAULT = int(StacktraceOrder.DEFAULT) # Equivalent to `MOST_RECENT_FIRST` MOST_RECENT_LAST = int(StacktraceOrder.MOST_RECENT_LAST) MOST_RECENT_FIRST = int(StacktraceOrder.MOST_RECENT_FIRST)
_SerializedStacktraceOrder
python
plotly__plotly.py
plotly/graph_objs/histogram2dcontour/_hoverlabel.py
{ "start": 233, "end": 11319 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "histogram2dcontour" _path_str = "histogram2dcontour.hoverlabel" _valid_props = { "align", "alignsrc", "bgcolor", "bgcolorsrc", "bordercolor", "bordercolorsrc", "font", "namelength", ...
Hoverlabel
python
getsentry__sentry
src/sentry/tsdb/snuba.py
{ "start": 2508, "end": 34571 }
class ____(BaseTSDB): """ A time series query interface to Snuba Write methods are not supported, as the raw data from which we generate our time series is assumed to already exist in snuba. Read methods are supported only for models based on group/event data and will return empty results for ...
SnubaTSDB
python
getsentry__sentry
src/sentry/integrations/discord/message_builder/base/component/select_menu.py
{ "start": 661, "end": 1333 }
class ____: """ An option for a DiscordSelectMenu. """ def __init__( self, label: str, value: str, description: str | None = None, default: bool = False ) -> None: self.label = label self.value = value self.description = description self.default = default ...
DiscordSelectMenuOption
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 17932, "end": 18012 }
class ____(TrackedAbstractBaseA, UntrackedConcreteBase): pass
InheritTracking1
python
fluentpython__example-code
20-descriptor/bulkfood/model_v5_check.py
{ "start": 13, "end": 509 }
class ____: __counter = 0 def __init__(self): cls = self.__class__ prefix = cls.__name__ index = cls.__counter self.storage_name = '_{}#{}'.format(prefix, index) cls.__counter += 1 def __get__(self, instance, owner): if instance is None: return s...
AutoStorage
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_default_date_format01.py
{ "start": 346, "end": 2979 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("default_date_format01.xlsx") def test_create_file_user_date_format(self): """Test write_datetime with explicit date format.""" wor...
TestCompareXLSXFiles
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/datastore.py
{ "start": 23413, "end": 25286 }
class ____(GoogleCloudBaseOperator): """ Deletes the long-running operation. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:CloudDatastoreDeleteOperationOperator` .. seealso:: https://cloud.google.com/datastore/docs...
CloudDatastoreDeleteOperationOperator
python
pydata__xarray
xarray/tests/test_duck_array_ops.py
{ "start": 2132, "end": 7852 }
class ____: @pytest.fixture(autouse=True) def setUp(self): self.x = array( [ [ [nan, nan, 2.0, nan], [nan, 5.0, 6.0, nan], [8.0, 9.0, 10.0, nan], ], [ [nan, 13.0, 1...
TestOps
python
urllib3__urllib3
test/test_response.py
{ "start": 56368, "end": 56591 }
class ____(MockChunkedEncodingResponse): BAD_LENGTH_LINE = "ZZZ\r\n" def _encode_chunk(self, chunk: bytes) -> bytes: return f"{self.BAD_LENGTH_LINE}{chunk.decode()}\r\n".encode()
MockChunkedInvalidChunkLength
python
sympy__sympy
sympy/polys/polyoptions.py
{ "start": 18133, "end": 18337 }
class ____(BooleanOption, Flag, metaclass=OptionType): """``auto`` option to polynomial manipulation functions. """ option = 'frac' @classmethod def default(cls): return False
Frac
python
facelessuser__pymdown-extensions
tests/test_extensions/test_slugs.py
{ "start": 2808, "end": 3443 }
class ____(util.MdCase): """Test encoded GitHub Flavored Markdown style slugs.""" extension = ['markdown.extensions.toc'] extension_configs = { 'markdown.extensions.toc': { "slugify": slugs.slugify(case="lower-ascii", percent_encode=True) } } def test_slug(self): ...
TestGFMEncoded
python
RaRe-Technologies__gensim
gensim/test/test_similarities.py
{ "start": 22952, "end": 26835 }
class ____(unittest.TestCase): def setUp(self): try: import annoy # noqa:F401 except ImportError as e: raise unittest.SkipTest("Annoy library is not available: %s" % e) from gensim.similarities.annoy import AnnoyIndexer self.indexer = AnnoyIndexer def ...
TestWord2VecAnnoyIndexer
python
google__python-fire
fire/core.py
{ "start": 7053, "end": 36731 }
class ____(SystemExit): # pylint: disable=g-bad-exception-name """An exception raised by Fire to the client in the case of a FireError. The trace of the Fire program is available on the `trace` property. This exception inherits from SystemExit, so clients may explicitly catch it with `except SystemExit` or `...
FireExit
python
jina-ai__jina
jina/proto/docarray_v1/pb/jina_pb2_grpc.py
{ "start": 1726, "end": 2574 }
class ____(object): """* jina gRPC service for DataRequests. """ @staticmethod def process_data( request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, ...
JinaDataRequestRPC
python
keras-team__keras
keras/src/ops/numpy.py
{ "start": 241993, "end": 243568 }
class ____(Operation): def __init__(self, kth, axis=-1, *, name=None): super().__init__(name=name) if not isinstance(kth, int): raise ValueError(f"kth must be an integer. Received:kth = {kth}") self.kth = kth self.axis = axis def call(self, x): return backend...
Argpartition
python
getsentry__sentry
tests/sentry/uptime/autodetect/test_tasks.py
{ "start": 14882, "end": 16777 }
class ____(UptimeTestCase): def test(self) -> None: url = make_unique_test_url() assert not is_url_auto_monitored_for_project(self.project, url) detector = monitor_url_for_project(self.project, url) assert is_url_auto_monitored_for_project(self.project, url) assert detector.n...
TestMonitorUrlForProject
python
astropy__astropy
astropy/table/index.py
{ "start": 37865, "end": 44535 }
class ____: """ Pseudo-list of Table rows allowing for retrieval of rows by indexed column values. Parameters ---------- table : Table Indexed table to use index_id : tuple or None If not None, the index id as a tuple to use for all retrievals. If None (default), the pri...
TableLoc
python
huggingface__transformers
src/transformers/models/esm/modeling_esm.py
{ "start": 32118, "end": 33003 }
class ____(nn.Module): """ESM Head for masked language modeling.""" def __init__(self, config): super().__init__() self.dense = nn.Linear(config.hidden_size, config.hidden_size) self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.decoder = nn.Line...
EsmLMHead
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/suite/test_reflection.py
{ "start": 9593, "end": 12510 }
class ____(fixtures.TestBase): __sparse_driver_backend__ = True def column_names(): return testing.combinations( ("plainname",), ("(3)",), ("col%p",), ("[brack]",), argnames="columnname", ) def table_names(): return testi...
BizarroCharacterTest
python
getsentry__sentry
src/sentry/api/serializers/models/role.py
{ "start": 2251, "end": 2791 }
class ____(Serializer): def __init__(self, **kwargs): """ Remove this when deleting "organizations:team-roles" flag """ self.organization = kwargs["organization"] def serialize(self, obj: TeamRole, attrs, user, **kwargs) -> TeamRoleSerializerResponse: base = _serialize_b...
TeamRoleSerializer
python
astropy__astropy
astropy/io/votable/tests/test_vo.py
{ "start": 7086, "end": 13166 }
class ____: def setup_class(self): with np.errstate(over="ignore"): # https://github.com/astropy/astropy/issues/13341 self.votable = parse(get_pkg_data_filename("data/regression.xml")) self.table = self.votable.get_first_table() self.array = self.table.array s...
TestReferences
python
pytorch__pytorch
test/dynamo/test_misc.py
{ "start": 432800, "end": 433563 }
class ____(JitTestCase): def test_jit_save(self): def fn(): class Foo(torch.nn.Module): def __init__(self) -> None: super().__init__() self.a = 3 @torch.jit.export def __getstate__(self): ...
TestTracer
python
pallets__flask
src/flask/json/tag.py
{ "start": 4770, "end": 5308 }
class ____(JSONTag): """Serialize anything matching the :class:`~markupsafe.Markup` API by having a ``__html__`` method to the result of that method. Always deserializes to an instance of :class:`~markupsafe.Markup`.""" __slots__ = () key = " m" def check(self, value: t.Any) -> bool: r...
TagMarkup
python
pandas-dev__pandas
pandas/tests/frame/methods/test_dtypes.py
{ "start": 238, "end": 4672 }
class ____: def test_empty_frame_dtypes(self): empty_df = DataFrame() tm.assert_series_equal(empty_df.dtypes, Series(dtype=object)) nocols_df = DataFrame(index=[1, 2, 3]) tm.assert_series_equal(nocols_df.dtypes, Series(dtype=object)) norows_df = DataFrame(columns=list("abc"...
TestDataFrameDataTypes
python
wandb__wandb
wandb/vendor/pygments/lexers/ezhil.py
{ "start": 455, "end": 2520 }
class ____(RegexLexer): """ Lexer for `Ezhil, a Tamil script-based programming language <http://ezhillang.org>`_ .. versionadded:: 2.1 """ name = 'Ezhil' aliases = ['ezhil'] filenames = ['*.n'] mimetypes = ['text/x-ezhil'] flags = re.MULTILINE | re.UNICODE # Refer to tamil.utf8....
EzhilLexer
python
dagster-io__dagster
python_modules/dagster/dagster/_core/executor/child_process_executor.py
{ "start": 1643, "end": 5897 }
class ____(Exception): """Thrown when the child process crashes.""" def __init__(self, pid, exit_code=None): self.pid = pid self.exit_code = exit_code super().__init__() def _execute_command_in_child_process(event_queue: Queue, command: ChildProcessCommand): """Wraps the execution...
ChildProcessCrashException
python
python__mypy
mypy/state.py
{ "start": 234, "end": 850 }
class ____: # Wrap this in a class since it's faster that using a module-level attribute. def __init__(self, strict_optional: bool) -> None: # Value varies by file being processed self.strict_optional = strict_optional @contextmanager def strict_optional_set(self, value: bool) -> Itera...
StrictOptionalState
python
huggingface__transformers
src/transformers/models/got_ocr2/modeling_got_ocr2.py
{ "start": 17734, "end": 19738 }
class ____(GotOcr2PreTrainedModel): _can_record_outputs = {"hidden_states": GotOcr2VisionLayer, "attentions": GotOcr2VisionAttention} input_modalities = ("image",) def __init__(self, config: GotOcr2VisionConfig): super().__init__(config) self.config = config self.image_size = config...
GotOcr2VisionEncoder
python
anthropics__anthropic-sdk-python
src/anthropic/_exceptions.py
{ "start": 3751, "end": 3883 }
class ____(APIStatusError): status_code: Literal[529] = 529 # pyright: ignore[reportIncompatibleVariableOverride]
OverloadedError
python
ipython__ipython
IPython/core/formatters.py
{ "start": 9522, "end": 10887 }
class ____(metaclass=abc.ABCMeta): """ Abstract base class for Formatters. A formatter is a callable class that is responsible for computing the raw format data for a particular format type (MIME type). For example, an HTML formatter would have a format type of `text/html` and would return the HTML...
FormatterABC
python
ray-project__ray
release/long_running_tests/workloads/many_drivers.py
{ "start": 795, "end": 3037 }
class ____(object): def method(self): return 1 for _ in range(5): for node in nodes: assert ray.get( f.options(scheduling_strategy=NodeAffinitySchedulingStrategy( node, soft=False)).remote()) == 1 actor = Actor.options(scheduling_strategy=NodeAffinityScheduli...
Actor
python
PrefectHQ__prefect
src/prefect/settings/models/server/events.py
{ "start": 241, "end": 5828 }
class ____(PrefectBaseSettings): """ Settings for controlling behavior of the events subsystem """ model_config: ClassVar[SettingsConfigDict] = build_settings_config( ("server", "events") ) ########################################################################### # Events setting...
ServerEventsSettings
python
huggingface__transformers
src/transformers/models/poolformer/configuration_poolformer.py
{ "start": 803, "end": 5076 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of [`PoolFormerModel`]. It is used to instantiate a PoolFormer model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar c...
PoolFormerConfig
python
tensorflow__tensorflow
tensorflow/python/distribute/experimental/mirrored_strategy_test.py
{ "start": 19762, "end": 20430 }
class ____(test_util.DTensorBaseTest): def setUp(self): super().setUp() global_ids = test_util.create_device_ids_array((2, 1)) local_ids = np.ravel(global_ids).tolist() mesh_dict = { device: layout.Mesh(['batch', 'model'], global_ids, local_ids, test_util.create_de...
InvalidMeshTest
python
getsentry__sentry
src/sentry/models/dashboard_widget.py
{ "start": 7238, "end": 10788 }
class ____(Model): """ Tracks on_demand state and values for dashboard widget queries. Only a subset of dashboard widget queries have conditions or columns that would require on-demand extraction, and others are simply not applicable (eg. different dataset). """ __relocation_scope__ = Relocatio...
DashboardWidgetQueryOnDemand
python
pypa__warehouse
tests/unit/admin/views/test_organization_applications.py
{ "start": 9874, "end": 16357 }
class ____: @pytest.mark.usefixtures("_enable_organizations") def test_detail(self, db_request): organization_application = OrganizationApplicationFactory.create() db_request.matchdict["organization_application_id"] = ( organization_application.id ) result = views.org...
TestOrganizationApplicationDetail
python
numba__numba
numba/cuda/cudadrv/driver.py
{ "start": 39326, "end": 56018 }
class ____(object): """ This object wraps a CUDA Context resource. Contexts should not be constructed directly by user code. """ def __init__(self, device, handle): self.device = device self.handle = handle self.allocations = utils.UniqueDict() self.deallocations = ...
Context
python
huggingface__transformers
examples/modular-transformers/modeling_roberta.py
{ "start": 16417, "end": 19175 }
class ____(GradientCheckpointingLayer): def __init__(self, config, layer_idx=None): super().__init__() self.chunk_size_feed_forward = config.chunk_size_feed_forward self.seq_len_dim = 1 self.attention = RobertaAttention(config, is_causal=config.is_decoder, layer_idx=layer_idx) ...
RobertaLayer
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/cloud_run.py
{ "start": 19523, "end": 22313 }
class ____(GoogleCloudBaseOperator): """ Deletes a Service without executing it. Pushes the deleted service to xcom. :param project_id: Required. The ID of the Google Cloud project that the service belongs to. :param region: Required. The ID of the Google Cloud region that the service belongs to. :...
CloudRunDeleteServiceOperator
python
run-llama__llama_index
llama-index-core/llama_index/core/query_engine/pandas/output_parser.py
{ "start": 126, "end": 773 }
class ____: """ Pandas instruction parser. DEPRECATED: This class has been moved to `llama-index-experimental`. """ def __init__(self, *args: Any, **kwargs: Any) -> None: raise DeprecationWarning( "PandasInstructionParser has been moved to `llama-index-experimental`.\n" ...
PandasInstructionParser
python
crytic__slither
slither/slithir/operations/init_array.py
{ "start": 302, "end": 1476 }
class ____(OperationWithLValue): def __init__( self, init_values: List[RVALUE], lvalue: Union[TemporaryVariableSSA, TemporaryVariable] ) -> None: # init_values can be an array of n dimension # reduce was removed in py3 super().__init__() def reduce(xs): resul...
InitArray
python
django-extensions__django-extensions
tests/test_runscript.py
{ "start": 6771, "end": 10981 }
class ____(RunScriptTests): def setUp(self): super().setUp() self.curwd = os.getcwd() os.chdir(project_path) def tearDown(self): super().setUp() os.chdir(self.curwd) def _execute_script_with_chdir( self, dir_policy, start_path, expected_path, chdir=None ...
ChangingDirectoryTests
python
sphinx-doc__sphinx
tests/test_builders/test_build_linkcheck.py
{ "start": 45747, "end": 47662 }
class ____(BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' def do_HEAD(self) -> None: self.close_connection = True def do_GET(self) -> None: self.send_response(200, 'OK') self.send_header('Content-Length', '0') self.end_headers() @pytest.mark.sphinx( 'linkcheck...
ConnectionResetHandler
python
tensorflow__tensorflow
tensorflow/python/ops/image_grad_test_base.py
{ "start": 13487, "end": 16185 }
class ____(test.TestCase): """Tests scale and translate op.""" def testGrads(self): in_shape = [1, 2, 3, 1] out_shape = [1, 4, 6, 1] x = np.arange(0, 6).reshape(in_shape).astype(np.float32) kernel_types = [ 'lanczos1', 'lanczos3', 'lanczos5', 'gaussian', 'box', 'triangle', 'keyscu...
ScaleAndTranslateOpTestBase
python
getsentry__sentry
src/sentry/integrations/api/serializers/rest_framework/data_forwarder.py
{ "start": 810, "end": 876 }
class ____(TypedDict, total=False): write_key: str
SegmentConfig
python
kamyu104__LeetCode-Solutions
Python/count-pairs-of-connectable-servers-in-a-weighted-tree-network.py
{ "start": 1999, "end": 3081 }
class ____(object): def countPairsOfConnectableServers(self, edges, signalSpeed): """ :type edges: List[List[int]] :type signalSpeed: int :rtype: List[int] """ def bfs(u, p, dist): result = 0 q = [(u, p, dist)] while q: ...
Solution3
python
keras-team__keras
keras/src/layers/convolutional/separable_conv_test.py
{ "start": 6551, "end": 11866 }
class ____(testing.TestCase): @parameterized.parameters( { "depth_multiplier": 5, "filters": 5, "kernel_size": 2, "strides": 1, "padding": "valid", "data_format": "channels_last", "dilation_rate": 1, }, { ...
SeparableConvCorrectnessTest
python
joke2k__faker
faker/providers/company/fr_FR/__init__.py
{ "start": 131, "end": 22924 }
class ____(CompanyProvider): formats = ( "{{last_name}} {{company_suffix}}", "{{last_name}} {{last_name}} {{company_suffix}}", "{{last_name}}", "{{last_name}}", ) catch_phrase_formats = ("{{catch_phrase_noun}} {{catch_phrase_verb}} {{catch_phrase_attribute}}",) nouns = ...
Provider
python
mlflow__mlflow
mlflow/server/fastapi_security.py
{ "start": 678, "end": 1928 }
class ____: """Middleware to validate Host headers using fnmatch patterns.""" def __init__(self, app: ASGIApp, allowed_hosts: list[str]): self.app = app self.allowed_hosts = allowed_hosts async def __call__(self, scope, receive, send): if scope["type"] != "http": return...
HostValidationMiddleware
python
django__django
tests/gis_tests/geoapp/models.py
{ "start": 2120, "end": 2262 }
class ____(NamedModel): point1 = models.PointField() point2 = models.PointField() point3 = models.PointField(srid=3857)
ManyPointModel
python
geekcomputers__Python
venv/Lib/site-packages/pip/_internal/resolution/resolvelib/resolver.py
{ "start": 1295, "end": 12592 }
class ____(BaseResolver): _allowed_strategies = {"eager", "only-if-needed", "to-satisfy-only"} def __init__( self, preparer: RequirementPreparer, finder: PackageFinder, wheel_cache: Optional[WheelCache], make_install_req: InstallRequirementProvider, use_user_site...
Resolver
python
doocs__leetcode
solution/2900-2999/2997.Minimum Number of Operations to Make Array XOR Equal to K/Solution.py
{ "start": 0, "end": 125 }
class ____: def minOperations(self, nums: List[int], k: int) -> int: return reduce(xor, nums, k).bit_count()
Solution
python
pola-rs__polars
py-polars/tests/unit/constructors/test_constructors.py
{ "start": 1855, "end": 1924 }
class ____(pydantic.BaseModel): x: int y: _TestBarPD
_TestFooPD
python
realpython__materials
arcade-platformer/arcade_platformer/arcade_platformer.py
{ "start": 4159, "end": 5607 }
class ____(arcade.View): """Show instructions to the player""" def __init__(self) -> None: """Create instructions screen""" super().__init__() # Find the instructions image in the image folder instructions_image_path = ( ASSETS_PATH / "images" / "instructions_image....
InstructionsView
python
mahmoud__glom
glom/matching.py
{ "start": 1228, "end": 2086 }
class ____(MatchError, TypeError): """:exc:`MatchError` subtype raised when a :class:`Match` fails a type check. >>> glom({'id': 'a'}, Match({'id': int})) Traceback (most recent call last): ... TypeMatchError: error raised while processing. Target-spec trace, with error detail (most recent...
TypeMatchError
python
keras-team__keras
keras/src/trainers/data_adapters/array_slicing.py
{ "start": 3444, "end": 3488 }
class ____(Sliceable): pass
NumpySliceable
python
networkx__networkx
networkx/generators/tests/test_degree_seq.py
{ "start": 39, "end": 7284 }
class ____: """Unit tests for the :func:`~networkx.configuration_model` function. """ def test_empty_degree_sequence(self): """Tests that an empty degree sequence yields the null graph.""" G = nx.configuration_model([]) assert len(G) == 0 def test_degree_zero(self): ...
TestConfigurationModel
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 88159, "end": 88802 }
class ____(_PrintableStructure): _fields_ = [("version", c_uint), ("revision", c_uint), ("guestInfoState", _nvmlVgpuGuestInfoState_t), ("guestDriverVersion", c_char * NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE), ("hostDriverVersion", c_char * NVML_SYSTEM_D...
c_nvmlVgpuMetadata_t
python
pypa__setuptools
setuptools/tests/config/test_pyprojecttoml.py
{ "start": 6468, "end": 12438 }
class ____: def test_dynamic(self, tmp_path): # Let's create a project example that has dynamic classifiers # coming from a txt file. create_example(tmp_path, "src") classifiers = cleandoc( """ Framework :: Flask Programming Language :: Haskell ...
TestClassifiers
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/triggers/mwaa.py
{ "start": 1198, "end": 4753 }
class ____(AwsBaseWaiterTrigger): """ Trigger when an MWAA Dag Run is complete. :param external_env_name: The external MWAA environment name that contains the DAG Run you want to wait for (templated) :param external_dag_id: The DAG ID in the external MWAA environment that contains the DAG Run y...
MwaaDagRunCompletedTrigger
python
ray-project__ray
python/ray/tests/spark/test_multicores_per_task.py
{ "start": 437, "end": 1704 }
class ____(RayOnSparkGPUClusterTestBase): @classmethod def setup_class(cls): cls.num_total_cpus = 4 cls.num_total_gpus = 4 cls.num_cpus_per_spark_task = 2 cls.num_gpus_per_spark_task = 2 cls.max_spark_tasks = 2 gpu_discovery_script_path = os.path.join( ...
TestMultiCoresPerTaskCluster
python
doocs__leetcode
solution/2400-2499/2419.Longest Subarray With Maximum Bitwise AND/Solution.py
{ "start": 0, "end": 285 }
class ____: def longestSubarray(self, nums: List[int]) -> int: mx = max(nums) ans = cnt = 0 for x in nums: if x == mx: cnt += 1 ans = max(ans, cnt) else: cnt = 0 return ans
Solution
python
huggingface__transformers
src/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py
{ "start": 24268, "end": 26622 }
class ____(ModelOutput): r""" intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`): Stacked intermediate hidden states (output of each layer of the decoder). intermediate_logits (`torch.FloatTensor` of shape `(batch_size, config.de...
RTDetrV2DecoderOutput
python
run-llama__llama_index
llama-index-core/tests/postprocessor/test_structured_llm_rerank.py
{ "start": 1606, "end": 4428 }
class ____(MockLLM): @property def metadata(self) -> LLMMetadata: return super().metadata.model_copy(update={"is_function_calling_model": True}) @patch.object( MockFunctionCallingLLM, "structured_predict", mock_llmpredictor_structured_predict, ) def test_llm_rerank() -> None: """Test L...
MockFunctionCallingLLM
python
encode__django-rest-framework
tests/test_validation.py
{ "start": 406, "end": 616 }
class ____(serializers.ModelSerializer): class Meta: model = ValidationModel fields = ('blank_validated_field',) read_only_fields = ('blank_validated_field',)
ValidationModelSerializer
python
pandas-dev__pandas
pandas/tests/arrays/categorical/test_sorting.py
{ "start": 116, "end": 5052 }
class ____: def test_argsort(self): c = Categorical([5, 3, 1, 4, 2], ordered=True) expected = np.array([2, 4, 1, 3, 0]) tm.assert_numpy_array_equal( c.argsort(ascending=True), expected, check_dtype=False ) expected = expected[::-1] tm.assert_numpy_array_...
TestCategoricalSort