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 | cherrypy__cherrypy | cherrypy/process/wspbus.py | {
"start": 5241,
"end": 21676
} | class ____(object):
"""Process state-machine and messenger for HTTP site deployment.
All listeners for a given channel are guaranteed to be called even
if others at the same channel fail. Each failure is logged, but
execution proceeds on to the next listener. The only way to stop all
processing fro... | Bus |
python | python-poetry__poetry | src/poetry/installation/chef.py | {
"start": 587,
"end": 3665
} | class ____:
def __init__(
self, artifact_cache: ArtifactCache, env: Env, pool: RepositoryPool
) -> None:
self._env = env
self._pool = pool
self._artifact_cache = artifact_cache
def prepare(
self,
archive: Path,
output_dir: Path | None = None,
... | Chef |
python | kubernetes-client__python | kubernetes/client/exceptions.py | {
"start": 2099,
"end": 2623
} | class ____(OpenApiException, KeyError):
def __init__(self, msg, path_to_item=None):
"""
Args:
msg (str): the exception message
Keyword Args:
path_to_item (None/list) the path to the exception in the
received_data dict
"""
self.path_to_... | ApiKeyError |
python | pandas-dev__pandas | pandas/core/indexes/multi.py | {
"start": 4886,
"end": 156898
} | class ____(Index):
"""
A multi-level, or hierarchical, index object for pandas objects.
Parameters
----------
levels : sequence of arrays
The unique labels for each level.
codes : sequence of arrays
Integers for each level designating which label at each location.
sortorder ... | MultiIndex |
python | huggingface__transformers | src/transformers/models/vits/modeling_vits.py | {
"start": 37303,
"end": 44530
} | class ____(nn.Module):
"""Multi-headed attention with relative positional representation."""
def __init__(self, config: VitsConfig):
super().__init__()
self.embed_dim = config.hidden_size
self.num_heads = config.num_attention_heads
self.dropout = config.attention_dropout
... | VitsAttention |
python | lepture__authlib | authlib/jose/errors.py | {
"start": 709,
"end": 958
} | class ____(JoseError):
error = "invalid_crit_header_parameter_name"
def __init__(self, name):
description = f"Invalid Header Parameter Name: {name}"
super().__init__(description=description)
| InvalidCritHeaderParameterNameError |
python | astropy__astropy | astropy/visualization/interval.py | {
"start": 6051,
"end": 6813
} | class ____(AsymmetricPercentileInterval):
"""
Interval based on a keeping a specified fraction of pixels.
Parameters
----------
percentile : float
The fraction of pixels to keep. The same fraction of pixels is
eliminated from both ends.
n_samples : int, optional
Maximum ... | PercentileInterval |
python | modin-project__modin | modin/pandas/base.py | {
"start": 6281,
"end": 161151
} | class ____(QueryCompilerCaster, ClassLogger):
"""
Implement most of the common code that exists in DataFrame/Series.
Since both objects share the same underlying representation, and the algorithms
are the same, we use this object to define the general behavior of those objects
and then use those ob... | BasePandasDataset |
python | huggingface__transformers | src/transformers/models/imagegpt/modeling_imagegpt.py | {
"start": 17358,
"end": 26929
} | class ____(ImageGPTPreTrainedModel):
def __init__(self, config: ImageGPTConfig):
super().__init__(config)
self.embed_dim = config.hidden_size
self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
... | ImageGPTModel |
python | ray-project__ray | python/ray/__init__.py | {
"start": 4236,
"end": 7661
} | class ____:
def __init__(self, name, real_worker):
self._name = name
self._real_worker = real_worker
self._warned = set()
def __getattr__(self, attr):
value = getattr(self._real_worker, attr)
if attr not in self._warned:
self._warned.add(attr)
log... | _DeprecationWrapper |
python | ansible__ansible | lib/ansible/errors/__init__.py | {
"start": 10870,
"end": 11971
} | class ____(AnsibleRuntimeError):
"""A file missing failure."""
def __init__(self, message="", obj=None, show_content=True, suppress_extended_error=..., orig_exc=None, paths=None, file_name=None):
self.file_name = file_name
self.paths = paths
if message:
message += "\n"
... | AnsibleFileNotFound |
python | ray-project__ray | rllib/utils/exploration/gaussian_noise.py | {
"start": 804,
"end": 9197
} | class ____(Exploration):
"""An exploration that adds white noise to continuous actions.
If explore=True, returns actions plus scale (annealed over time) x
Gaussian noise. Also, some completely random period is possible at the
beginning.
If explore=False, returns the deterministic action.
"""
... | GaussianNoise |
python | eth-brownie__brownie | brownie/project/main.py | {
"start": 2440,
"end": 6453
} | class ____:
_path: Optional[pathlib.Path]
_build_path: Optional[pathlib.Path]
_sources: Sources
_build: Build
_containers: Dict[ContractName, ContractContainer]
def _compile(
self, contract_sources: Dict, compiler_config: CompilerConfig, silent: bool
) -> None:
compiler_con... | _ProjectBase |
python | apache__airflow | providers/influxdb/src/airflow/providers/influxdb/hooks/influxdb.py | {
"start": 1324,
"end": 5933
} | class ____(BaseHook):
"""
Interact with InfluxDB.
Performs a connection to InfluxDB and retrieves client.
:param influxdb_conn_id: Reference to :ref:`Influxdb connection id <howto/connection:influxdb>`.
"""
conn_name_attr = "influxdb_conn_id"
default_conn_name = "influxdb_default"
con... | InfluxDBHook |
python | python-openxml__python-docx | tests/opc/unitdata/types.py | {
"start": 404,
"end": 765
} | class ____(BaseBuilder):
__tag__ = "Types"
__nspfxs__ = ("ct",)
__attrs__ = ()
def with_nsdecls(self, *nspfxs):
self._nsdecls = ' xmlns="%s"' % nsmap["ct"]
return self
def a_Default():
return CT_DefaultBuilder()
def a_Types():
return CT_TypesBuilder()
def an_Override():
... | CT_TypesBuilder |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 34342,
"end": 34576
} | class ____(Response):
"""
Response of events.add endpoint.
"""
_service = "events"
_action = "add"
_version = "2.13"
_schema = {"additionalProperties": True, "definitions": {}, "type": "object"}
| AddResponse |
python | huggingface__transformers | src/transformers/models/yolos/modeling_yolos.py | {
"start": 5271,
"end": 6652
} | class ____(nn.Module):
def __init__(self, config) -> None:
super().__init__()
self.config = config
def forward(self, pos_embed, img_size=(800, 1344)) -> torch.Tensor:
cls_pos_embed = pos_embed[:, 0, :]
cls_pos_embed = cls_pos_embed[:, None]
det_pos_embed = pos_embed[:, -... | InterpolateInitialPositionEmbeddings |
python | tensorflow__tensorflow | tensorflow/python/training/input_test.py | {
"start": 17391,
"end": 41462
} | class ____(test_lib.TestCase):
def _testOneThreadHelper(self, use_dict):
with ops.Graph().as_default(), self.cached_session():
batch_size = 10
num_batches = 3
zero64 = constant_op.constant(0, dtype=dtypes.int64)
examples = variables.Variable(zero64)
counter = examples.count_up_to(nu... | BatchTest |
python | pola-rs__polars | py-polars/src/polars/interchange/buffer.py | {
"start": 331,
"end": 2301
} | class ____(Buffer):
"""
A buffer object backed by a Polars Series consisting of a single chunk.
Parameters
----------
data
The Polars Series backing the buffer object.
allow_copy
Allow data to be copied during operations on this column. If set to `False`,
a RuntimeError ... | PolarsBuffer |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_column_distinct_values_to_be_continuous.py | {
"start": 781,
"end": 10228
} | class ____(ColumnAggregateExpectation):
"""Expect the set of distinct column values to be continuous."""
examples = [
{
"data": {
"a": [
"2021-01-01",
"2021-01-31",
"2021-02-28",
"2021-03-20",
... | ExpectColumnDistinctValuesToBeContinuous |
python | huggingface__transformers | src/transformers/models/granite_speech/configuration_granite_speech.py | {
"start": 4513,
"end": 8565
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`GraniteSpeechForConditionalGeneration`]. It is used to instantiate an
Granite Speech model according to the specified arguments, defining the model architecture.
Configuration objects inherit from [`Pre... | GraniteSpeechConfig |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/circular_import/c.py | {
"start": 52,
"end": 97
} | class ____:
X = circular_import.a.X
| SomeClass |
python | aimacode__aima-python | nlp4e.py | {
"start": 10798,
"end": 13594
} | class ____:
"""Class for parsing sentences using a chart data structure.
>>> chart = Chart(E0)
>>> len(chart.parses('the stench is in 2 2'))
1
"""
def __init__(self, grammar, trace=False):
"""A datastructure for parsing a string; and methods to do the parse.
self.chart[i] holds ... | Chart |
python | PrefectHQ__prefect | src/prefect/server/schemas/filters.py | {
"start": 75482,
"end": 76006
} | class ____(PrefectFilterBaseModel):
"""Filter by `Artifact.task_run_id`."""
any_: Optional[list[UUID]] = Field(
default=None, description="A list of task run IDs to include"
)
def _get_filter_list(
self, db: "PrefectDBInterface"
) -> Iterable[sa.ColumnExpressionArgument[bool]]:
... | ArtifactFilterTaskRunId |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 395261,
"end": 401589
} | class ____(ExprNode):
"""
Merge a sequence of iterables into a set/list/tuple.
The target collection is determined by self.type, which must be set externally.
args [ExprNode]
"""
subexprs = ['args']
is_temp = True
gil_message = "Constructing Python collection"
def __init__(self... | MergedSequenceNode |
python | davidhalter__jedi | test/refactor/extract_variable.py | {
"start": 3150,
"end": 8641
} | class ____(x):
pass
# -------------------------------------------------- keyword-pass
#? 12 error {'new_name': 'x'}
def x(): pass
# ++++++++++++++++++++++++++++++++++++++++++++++++++
Cannot extract a "simple_stmt"
# -------------------------------------------------- keyword-continue
#? 5 error {'new_name': 'x'}
con... | Foo |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/internal/observability.py | {
"start": 11839,
"end": 19487
} | class ____:
def __bool__(self):
self._note_deprecation()
return bool(_callbacks)
def _note_deprecation(self):
from hypothesis._settings import note_deprecation
note_deprecation(
"hypothesis.internal.observability.TESTCASE_CALLBACKS is deprecated. "
"Repl... | _TestcaseCallbacks |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_storage_transfer_service.py | {
"start": 17515,
"end": 21761
} | class ____(GoogleCloudBaseOperator):
"""
Runs a transfer job.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:CloudDataTransferServiceRunJobOperator`
:param job_name: (Required) Name of the job to be run
:param project_i... | CloudDataTransferServiceRunJobOperator |
python | PrefectHQ__prefect | src/prefect/flows.py | {
"start": 4232,
"end": 74016
} | class ____(Generic[P, R]):
"""
A Prefect workflow definition.
Wraps a function with an entrypoint to the Prefect engine. To preserve the input
and output types, we use the generic type variables `P` and `R` for "Parameters" and
"Returns" respectively.
Args:
fn: The function defining th... | Flow |
python | getsentry__sentry | src/sentry/api/event_search.py | {
"start": 23449,
"end": 26128
} | class ____[TAllowBoolean: (Literal[True], Literal[False]) = Literal[True]]: # noqa: E251
"""
Configures how the search parser interprets a search query
"""
# <target_name>: [<list of source names>]
key_mappings: Mapping[str, list[str]] = field(default_factory=dict)
# Text keys we allow operat... | SearchConfig |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_composer.py | {
"start": 2273,
"end": 2512
} | class ____(BaseGoogleLink):
"""Helper class for constructing Cloud Composer Environment Link."""
name = "Cloud Composer Environment"
key = "composer_conf"
format_str = CLOUD_COMPOSER_DETAILS_LINK
| CloudComposerEnvironmentLink |
python | apache__airflow | providers/google/src/airflow/providers/google/ads/transfers/ads_to_gcs.py | {
"start": 1247,
"end": 5122
} | class ____(BaseOperator):
"""
Fetch daily results from the Google Ads API for 1-n clients.
Converts and saves the data as a temporary CSV file Uploads the CSV to
Google Cloud Storage.
.. seealso::
For more information on the Google Ads API, take a look at the API docs:
https://deve... | GoogleAdsToGcsOperator |
python | pypa__hatch | tests/env/plugin/test_interface.py | {
"start": 24857,
"end": 30079
} | class ____:
def test_default(self, isolation, isolated_data_dir, platform, global_application):
config = {"project": {"name": "my_app", "version": "0.0.1"}}
project = Project(isolation, config=config)
environment = MockEnvironment(
isolation,
project.metadata,
... | TestDependencyGroups |
python | django__django | tests/model_inheritance_regress/models.py | {
"start": 2949,
"end": 3110
} | class ____(CertificationAudit):
auditing_dept = models.CharField(max_length=20)
# Abstract classes don't get m2m tables autocreated.
| InternalCertificationAudit |
python | langchain-ai__langchain | libs/core/langchain_core/runnables/base.py | {
"start": 206258,
"end": 213944
} | class ____(RunnableBindingBase[Input, Output]): # type: ignore[no-redef]
"""Wrap a `Runnable` with additional functionality.
A `RunnableBinding` can be thought of as a "runnable decorator" that
preserves the essential features of `Runnable`; i.e., batching, streaming,
and async support, while adding a... | RunnableBinding |
python | redis__redis-py | tests/test_http/test_http_client.py | {
"start": 854,
"end": 13343
} | class ____:
def test_get_returns_parsed_json_and_uses_timeout(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
# Arrange
base_url = "https://api.example.com/"
path = "v1/items"
params = {"limit": 5, "q": "hello world"}
expected_url = f"{base_url}{path}?limit=5&q=... | TestHttpClient |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/autotools_config_replacement/package.py | {
"start": 239,
"end": 3202
} | class ____(AutotoolsPackage):
"""
This package features broken and working config.sub and config.guess files,
that should be replaced by the ones provided by gnuconfig. It allows testing
with / without patches and with / without substitutes available.
"""
has_code = False
version("1.0.0")
... | AutotoolsConfigReplacement |
python | fastapi__sqlmodel | docs_src/tutorial/delete/tutorial001_py310.py | {
"start": 71,
"end": 2761
} | class ____(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, ec... | Hero |
python | tiangolo__fastapi | docs_src/path_operation_configuration/tutorial005_py39.py | {
"start": 104,
"end": 736
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
price: float
tax: Union[float, None] = None
tags: set[str] = set()
@app.post(
"/items/",
response_model=Item,
summary="Create an item",
response_description="The created item",
)
async def create_item(item: Item)... | Item |
python | keras-team__keras | guides/making_new_layers_and_models_via_subclassing.py | {
"start": 15775,
"end": 17460
} | class ____(keras.Model):
def __init__(self, num_classes=1000):
super().__init__()
self.block_1 = ResNetBlock()
self.block_2 = ResNetBlock()
self.global_pool = layers.GlobalAveragePooling2D()
self.classifier = Dense(num_classes)
def call(self, inputs):
x = self.b... | ResNet |
python | openai__gym | gym/error.py | {
"start": 1607,
"end": 1727
} | class ____(Error):
"""When the order enforcing is violated, i.e. step or render is called before reset."""
| ResetNeeded |
python | openai__openai-python | src/openai/_utils/_transform.py | {
"start": 887,
"end": 15999
} | class ____:
"""Metadata class to be used in Annotated types to provide information about a given type.
For example:
class MyParams(TypedDict):
account_holder_name: Annotated[str, PropertyInfo(alias='accountHolderName')]
This means that {'account_holder_name': 'Robert'} will be transformed to ... | PropertyInfo |
python | huggingface__transformers | src/transformers/models/xlm/modeling_xlm.py | {
"start": 26987,
"end": 29247
} | class ____(PreTrainedModel):
config: XLMConfig
base_model_prefix = "transformer"
def __init__(self, *inputs, **kwargs):
super().__init__(*inputs, **kwargs)
@property
def dummy_inputs(self):
inputs_list = torch.tensor([[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]])
attn... | XLMPreTrainedModel |
python | run-llama__llama_index | llama-index-integrations/graph_stores/llama-index-graph-stores-nebula/llama_index/graph_stores/nebula/nebula_property_graph.py | {
"start": 3347,
"end": 30315
} | class ____(PropertyGraphStore):
"""
NebulaGraph Property Graph Store.
This class implements a NebulaGraph property graph store.
You could go with NebulaGraph-lite freely on Google Colab.
- https://github.com/nebula-contrib/nebulagraph-lite
Or Install with Docker Extension(search in the Docker ... | NebulaPropertyGraphStore |
python | django__django | tests/postgres_tests/__init__.py | {
"start": 442,
"end": 719
} | class ____(SimpleTestCase):
pass
@unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests")
# To register type handlers and locate the widget's template.
@modify_settings(INSTALLED_APPS={"append": "django.contrib.postgres"})
| PostgreSQLSimpleTestCase |
python | catalyst-team__catalyst | catalyst/extras/frozen_class.py | {
"start": 0,
"end": 588
} | class ____:
"""Class which prohibit ``__setattr__`` on existing attributes.
Examples:
>>> class IRunner(FrozenClass):
"""
__is_frozen = False
def __setattr__(self, key, value):
"""@TODO: Docs. Contribution is welcome."""
if self.__is_frozen and not hasattr(self, key):
... | FrozenClass |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/runtime_wrappers.py | {
"start": 108328,
"end": 111529
} | class ____(CompilerWrapper):
flat_requires_grad: list[Optional[bool]] = field(default_factory=list)
def post_compile(
self,
compiled_fn,
aot_config: AOTConfig,
*,
runtime_metadata: ViewAndMutationMeta,
):
@wraps(compiled_fn)
def debug_compiled_functio... | DebugAssertWrapper |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vector_index.py | {
"start": 8285,
"end": 8466
} | class ____(_QuantizerConfigUpdate):
enabled: Optional[bool]
rescoreLimit: Optional[int]
@staticmethod
def quantizer_name() -> str:
return "bq"
| _BQConfigUpdate |
python | pytorch__pytorch | torch/ao/nn/qat/modules/conv.py | {
"start": 317,
"end": 3939
} | class ____(nn.modules.conv._ConvNd):
_FLOAT_MODULE: ClassVar[type[nn.modules.conv._ConvNd]]
def __init__(
self,
in_channels: int,
out_channels: int,
kernel_size: tuple[int, ...],
stride: tuple[int, ...],
padding: str | tuple[int, ...],
dilation: tuple[int... | _ConvNd |
python | pytorch__pytorch | torch/distributions/transforms.py | {
"start": 22767,
"end": 23091
} | class ____(Transform):
r"""Transform via the mapping :math:`y = |x|`."""
domain = constraints.real
codomain = constraints.positive
def __eq__(self, other):
return isinstance(other, AbsTransform)
def _call(self, x):
return x.abs()
def _inverse(self, y):
return y
| AbsTransform |
python | wandb__wandb | wandb/sdk/artifacts/_generated/input_types.py | {
"start": 234,
"end": 1429
} | class ____(GQLInput):
name: Optional[str] = Field(default=None, max_length=128)
description: Optional[str] = None
id: Optional[str] = None
framework: Optional[str] = None
entity_name: Optional[str] = Field(alias="entityName", default=None)
docker_image: Optional[str] = Field(
alias="dock... | UpsertModelInput |
python | huggingface__transformers | src/transformers/models/florence2/modeling_florence2.py | {
"start": 5677,
"end": 6381
} | class ____(nn.Module):
def __init__(self, config: Florence2VisionConfig, stage_idx: int):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[config.activation_function]
self.fc1 = nn.Linear(config.embed_dim[stage_idx], int(config.embed_dim[stage_idx] * config.mlp_rat... | Florence2VisionMLP |
python | kamyu104__LeetCode-Solutions | Python/maximum-sum-of-subsequence-with-non-adjacent-elements.py | {
"start": 52,
"end": 2681
} | class ____(object):
def maximumSumSubsequence(self, nums, queries):
"""
:type nums: List[int]
:type queries: List[List[int]]
:rtype: int
"""
MOD = 10**9+7
L0R0, L1R0, L0R1, L1R1 = range(4)
# Template:
# https://github.com/kamyu104/LeetCode-Solu... | Solution |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 633289,
"end": 634359
} | class ____(sgqlc.types.relay.Connection):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"edges",
"nodes",
"page_info",
"total_count",
"total_recurring_monthly_price_in_cents",
"total_recurring_monthly_price_in_... | SponsorshipConnection |
python | sympy__sympy | sympy/functions/special/error_functions.py | {
"start": 29959,
"end": 35564
} | class ____(DefinedFunction):
r"""
The classical exponential integral.
Explanation
===========
For use in SymPy, this function is defined as
.. math:: \operatorname{Ei}(x) = \sum_{n=1}^\infty \frac{x^n}{n\, n!}
+ \log(x) + \gamma,
where $\gamma$ is the... | Ei |
python | django-extensions__django-extensions | django_extensions/management/commands/merge_model_instances.py | {
"start": 2963,
"end": 9753
} | class ____(BaseCommand):
help = """
Removes duplicate model instances based on a specified
model and field name(s).
Makes sure that any OneToOne, ForeignKey, or ManyToMany relationships
attached to a deleted model(s) get reattached to the remaining model.
Based on the follo... | Command |
python | apache__airflow | airflow-core/src/airflow/jobs/triggerer_job_runner.py | {
"start": 6350,
"end": 7480
} | class ____:
class StartTriggerer(BaseModel):
"""Tell the async trigger runner process to start, and where to send status update messages."""
type: Literal["StartTriggerer"] = "StartTriggerer"
class TriggerStateChanges(BaseModel):
"""
Report state change about triggers back to t... | messages |
python | lazyprogrammer__machine_learning_examples | rl2/cartpole/dqn_tf.py | {
"start": 808,
"end": 1277
} | class ____:
def __init__(self, M1, M2, f=tf.nn.tanh, use_bias=True):
self.W = tf.Variable(tf.random_normal(shape=(M1, M2)))
self.params = [self.W]
self.use_bias = use_bias
if use_bias:
self.b = tf.Variable(np.zeros(M2).astype(np.float32))
self.params.append(self.b)
self.f = f
def fo... | HiddenLayer |
python | langchain-ai__langchain | libs/text-splitters/langchain_text_splitters/html.py | {
"start": 11753,
"end": 18658
} | class ____:
"""Splitting HTML files based on specified tag and font sizes.
Requires `lxml` package.
"""
def __init__(
self,
headers_to_split_on: list[tuple[str, str]],
**kwargs: Any,
) -> None:
"""Create a new `HTMLSectionSplitter`.
Args:
header... | HTMLSectionSplitter |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-aws-bedrock-agentcore/tests/test_browser.py | {
"start": 296,
"end": 828
} | class ____:
@patch.dict(os.environ, {"AWS_REGION": "us-east-1"})
def test_get_aws_region_from_aws_region(self):
assert get_aws_region() == "us-east-1"
@patch.dict(
os.environ, {"AWS_DEFAULT_REGION": "us-west-1", "AWS_REGION": ""}, clear=True
)
def test_get_aws_region_from_aws_defaul... | TestGetAwsRegion |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mssql/base.py | {
"start": 41424,
"end": 41518
} | class ____(_DateTimeBase, sqltypes.DateTime):
__visit_name__ = "SMALLDATETIME"
| SMALLDATETIME |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/reduce_test.py | {
"start": 1547,
"end": 9117
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(test_base.default_test_combinations())
def testSum(self):
for i in range(10):
ds = dataset_ops.Dataset.range(1, i + 1)
result = ds.reduce(np.int64(0), lambda x, y: x + y)
self.assertEqual(((i + 1) * i) // 2,... | ReduceTest |
python | ZoranPandovski__al-go-rithms | data_structures/Graphs/graph/Python/Disjoint_Set.py | {
"start": 0,
"end": 129
} | class ____:
def __init__(self):
self.parent=None
self.rank=0
self.element=None
self.e=[]
| Disjoint |
python | keras-team__keras | integration_tests/model_visualization_test.py | {
"start": 136,
"end": 2395
} | class ____(keras.models.Model):
def __init__(self, name):
super().__init__(name=name)
def call(self, x):
return x
def parse_text_from_html(html):
pattern = r"<font[^>]*>(.*?)</font>"
matches = re.findall(pattern, html)
for match in matches:
clean_text = re.sub(r"<[^>]*>",... | SubclassModel |
python | getsentry__sentry | tests/sentry/models/test_release.py | {
"start": 45756,
"end": 47874
} | class ____(TestCase):
def run_test(self, operator, build, expected_releases, organization_id=None, projects=None):
organization_id = organization_id if organization_id else self.organization.id
project_ids = [p.id for p in projects] if projects else None
assert set(
Release.objec... | ReleaseFilterBySemverBuildTest |
python | weaviate__weaviate-python-client | weaviate/exceptions.py | {
"start": 12952,
"end": 13226
} | class ____(UnexpectedStatusCodeError):
"""Is raised when a request to Weaviate fails due to insufficient permissions."""
def __init__(self, res: Union[httpx.Response, AioRpcError, Call]) -> None:
super().__init__("forbidden", res)
| InsufficientPermissionsError |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/axes_size.py | {
"start": 5045,
"end": 5253
} | class ____(MaxExtent):
"""
Size whose absolute part is the largest width of the given *artist_list*.
"""
def __init__(self, artist_list):
super().__init__(artist_list, "width")
| MaxWidth |
python | pypa__pipenv | pipenv/vendor/click/types.py | {
"start": 13735,
"end": 14251
} | class ____(ParamType):
_number_class: t.ClassVar[t.Type[t.Any]]
def convert(
self, value: t.Any, param: t.Optional["Parameter"], ctx: t.Optional["Context"]
) -> t.Any:
try:
return self._number_class(value)
except ValueError:
self.fail(
_("{val... | _NumberParamTypeBase |
python | scrapy__scrapy | scrapy/core/engine.py | {
"start": 1721,
"end": 2935
} | class ____:
def __init__(
self,
close_if_idle: bool,
nextcall: CallLaterOnce[None],
scheduler: BaseScheduler,
) -> None:
self.closing: Deferred[None] | None = None
self.inprogress: set[Request] = set()
self.close_if_idle: bool = close_if_idle
self.... | _Slot |
python | ray-project__ray | python/ray/serve/tests/unit/test_constants_utils.py | {
"start": 7849,
"end": 8723
} | class ____:
@pytest.mark.parametrize(
"name",
[
"RAY_SERVE_FOO",
"RAY_SERVE__DOUBLE_UNDERSCORE",
"RAY_SERVE_123",
"RAY_SERVE_VAR_NAME",
],
)
def test_validate_name_accepts_valid_prefix(self, name):
# Should not raise
ass... | TestValidation |
python | PyCQA__pylint | doc/data/messages/s/super-init-not-called/bad.py | {
"start": 0,
"end": 118
} | class ____:
def __init__(self, name="fruit"):
self.name = name
print("Creating a {self.name}")
| Fruit |
python | django__django | tests/gis_tests/tests.py | {
"start": 1564,
"end": 3160
} | class ____(unittest.TestCase):
"""
The PostGIS version check parses correctly the version numbers
"""
def test_get_version(self):
expect = "1.0.0"
ops = FakePostGISOperations(expect)
actual = ops.postgis_lib_version()
self.assertEqual(expect, actual)
def test_versio... | TestPostGISVersionCheck |
python | facebook__pyre-check | client/commands/launch_and_subscribe_handler.py | {
"start": 1332,
"end": 17432
} | class ____(background_tasks.Task):
server_options_reader: PyreServerOptionsReader
remote_logging: Optional[backend_arguments.RemoteLogging]
server_state: ServerState
client_status_message_handler: status_message_handler.ClientStatusMessageHandler
client_type_error_handler: type_error_handler.ClientT... | PyreDaemonLaunchAndSubscribeHandler |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 64418,
"end": 65173
} | class ____(str, Enum):
ARABIC = "arabic"
AZERBAIJANI = "azerbaijani"
BASQUE = "basque"
BENGALI = "bengali"
CATALAN = "catalan"
CHINESE = "chinese"
DANISH = "danish"
DUTCH = "dutch"
ENGLISH = "english"
FINNISH = "finnish"
FRENCH = "french"
GERMAN = "german"
GREEK = "gr... | Language |
python | ansible__ansible | test/units/module_utils/facts/test_collectors.py | {
"start": 12490,
"end": 12718
} | class ____(BaseFactsTest):
__test__ = True
gather_subset = ['!all', 'platform']
valid_subsets = ['platform']
fact_namespace = 'ansible_platform'
collector_class = PlatformFactCollector
| TestPlatformFactCollector |
python | spyder-ide__spyder | spyder/utils/stylesheet.py | {
"start": 18641,
"end": 19755
} | class ____(BaseTabBarStyleSheet):
"""Base style for dockwidget tabbars."""
SCROLL_BUTTONS_BORDER_WIDTH = '2px'
SCROLL_BUTTONS_PADDING = 7 if WIN else 9
def set_stylesheet(self):
super().set_stylesheet()
# Main constants
css = self.get_stylesheet()
# Center tabs to dif... | BaseDockTabBarStyleSheet |
python | vyperlang__vyper | vyper/venom/basicblock.py | {
"start": 6675,
"end": 15299
} | class ____:
"""
IRInstruction represents an instruction in IR. Each instruction has an opcode,
operands, and return value. For example, the following IR instruction:
%1 = add %0, 1
has opcode "add", operands ["%0", "1"], and return value "%1".
Convention: the rightmost value is the top of t... | IRInstruction |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_webagg.py | {
"start": 1807,
"end": 1904
} | class ____(core.FigureCanvasWebAggCore):
manager_class = FigureManagerWebAgg
| FigureCanvasWebAgg |
python | apache__thrift | lib/py/src/protocol/TCompactProtocol.py | {
"start": 13217,
"end": 13690
} | class ____(TProtocolFactory):
def __init__(self,
string_length_limit=None,
container_length_limit=None):
self.string_length_limit = string_length_limit
self.container_length_limit = container_length_limit
def getProtocol(self, trans):
return TCompactPro... | TCompactProtocolFactory |
python | pydata__xarray | xarray/computation/arithmetic.py | {
"start": 3781,
"end": 4043
} | class ____(
ImplementsArrayReduce,
IncludeNumpySameMethods,
SupportsArithmetic,
DataArrayOpsMixin,
):
__slots__ = ()
# priority must be higher than Variable to properly work with binary ufuncs
__array_priority__ = 60
| DataArrayArithmetic |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/definition/time_window_subclasses.py | {
"start": 540,
"end": 4533
} | class ____(TimeWindowPartitionsDefinition):
"""A set of hourly partitions.
The first partition in the set will start on the start_date at midnight. The last partition
in the set will end before the current time, unless the end_offset argument is set to a
positive number. If minute_offset is provided, t... | HourlyPartitionsDefinition |
python | tiangolo__fastapi | scripts/label_approved.py | {
"start": 386,
"end": 2245
} | class ____(BaseSettings):
github_repository: str
token: SecretStr
debug: bool | None = False
config: dict[str, LabelSettings] | Literal[""] = default_config
settings = Settings()
if settings.debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
logging.d... | Settings |
python | spack__spack | lib/spack/spack/vendor/altgraph/Dot.py | {
"start": 3727,
"end": 9966
} | class ____(object):
"""
A class providing a **graphviz** (dot language) representation
allowing a fine grained control over how the graph is being
displayed.
If the :command:`dot` and :command:`dotty` programs are not in the current
system path their location needs to be specified in the contr... | Dot |
python | neetcode-gh__leetcode | python/0416-partition-equal-subset-sum.py | {
"start": 0,
"end": 481
} | class ____:
def canPartition(self, nums: List[int]) -> bool:
if sum(nums) % 2:
return False
dp = set()
dp.add(0)
target = sum(nums) // 2
for i in range(len(nums) - 1, -1, -1):
nextDP = set()
for t in dp:
if (t + nums[i]) =... | Solution |
python | getsentry__sentry | tests/sentry/api/endpoints/test_frontend_version.py | {
"start": 115,
"end": 1100
} | class ____(APITestCase):
def test_returns_frontend_commit_sha(self) -> None:
url = reverse("sentry-api-0-internal-frontend-version")
with patch("sentry.api.endpoints.frontend_version.get_frontend_commit_sha") as mock_get_sha:
mock_get_sha.return_value = "abc123def456"
respo... | FrontendVersionTest |
python | pytorch__pytorch | test/inductor/test_flex_attention.py | {
"start": 11337,
"end": 150808
} | class ____(InductorTestCase):
def setUp(self):
super().setUp()
skipCPUIf(
LONG_COMPILATION_ON_CPU,
"skip UT for CPU due to long compilation time found in CI",
)
def _check_equal(
self,
golden_out: torch.Tensor,
ref_out: torch.Tensor,
... | TestFlexAttention |
python | huggingface__transformers | src/transformers/models/whisper/modeling_whisper.py | {
"start": 56803,
"end": 62321
} | class ____(WhisperPreTrainedModel, GenerationMixin):
_tied_weights_keys = {"proj_out.weight": "model.decoder.embed_tokens.weight"}
main_input_name = "input_ids"
def __init__(self, config):
super().__init__(config)
config.is_encoder_decoder = False
self.model = WhisperDecoderWrapper(... | WhisperForCausalLM |
python | google__jax | tests/lax_numpy_test.py | {
"start": 243038,
"end": 251505
} | class ____(jtu.JaxTestCase):
def testWrappedSignaturesMatch(self):
"""Test that jax.numpy function signatures match numpy."""
# NumPy functions explicitly not implemented in JAX:
skip = {'array2string',
'asanyarray',
'asarray_chkfinite',
'ascontiguousarray',
... | NumpySignaturesTest |
python | Textualize__textual | src/textual/widgets/_data_table.py | {
"start": 8111,
"end": 107851
} | class ____(ScrollView, Generic[CellType], can_focus=True):
"""A tabular widget that contains data."""
BINDINGS: ClassVar[list[BindingType]] = [
Binding("enter", "select_cursor", "Select", show=False),
Binding("up", "cursor_up", "Cursor up", show=False),
Binding("down", "cursor_down", "C... | DataTable |
python | explosion__spaCy | spacy/lang/hi/__init__.py | {
"start": 117,
"end": 215
} | class ____(BaseDefaults):
stop_words = STOP_WORDS
lex_attr_getters = LEX_ATTRS
| HindiDefaults |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/executors/ecs/boto_schema.py | {
"start": 2955,
"end": 3353
} | class ____(Schema):
"""Botocore Serialization Object for ECS ``RunTask`` Operation output."""
tasks = fields.List(fields.Nested(BotoTaskSchema), required=True)
failures = fields.List(fields.Nested(BotoFailureSchema), required=True)
class Meta:
"""Options object for a Schema. See Schema.Meta fo... | BotoRunTaskSchema |
python | pyca__cryptography | tests/x509/test_x509_ext.py | {
"start": 206280,
"end": 207973
} | class ____:
def test_load(self, backend):
cert = _load_cert(
os.path.join("x509", "cryptography.io.precert.pem"),
x509.load_pem_x509_certificate,
)
poison = cert.extensions.get_extension_for_oid(
ExtensionOID.PRECERT_POISON
).value
assert i... | TestPrecertPoisonExtension |
python | apache__airflow | airflow-core/docs/empty_plugin/empty_plugin.py | {
"start": 1605,
"end": 1834
} | class ____(AirflowPlugin):
"""Defining the plugin class"""
name = "Empty Plugin"
flask_blueprints = [bp]
appbuilder_views = [{"name": "Empty Plugin", "category": "Extra Views", "view": EmptyPluginView()}]
| EmptyPlugin |
python | apache__airflow | task-sdk/src/airflow/sdk/execution_time/supervisor.py | {
"start": 14498,
"end": 34945
} | class ____:
"""
Base class for managing subprocesses in Airflow's TaskSDK.
This class handles common functionalities required for subprocess management, such as
socket handling, process monitoring, and request handling.
"""
id: UUID
pid: int
"""The process ID of the child process"""
... | WatchedSubprocess |
python | docker__docker-py | docker/types/containers.py | {
"start": 23806,
"end": 27412
} | class ____(dict):
def __init__(
self, version, image, command, hostname=None, user=None, detach=False,
stdin_open=False, tty=False, ports=None, environment=None,
volumes=None, network_disabled=False, entrypoint=None,
working_dir=None, domainname=None, host_config=None, mac_address=No... | ContainerConfig |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/hwloc/package.py | {
"start": 217,
"end": 260
} | class ____(Package):
version("2.0.3")
| Hwloc |
python | pytest-dev__pytest | src/_pytest/warning_types.py | {
"start": 3345,
"end": 4398
} | class ____(PytestWarning):
"""When the lsof plugin finds leaked fds."""
__module__ = "pytest"
def warn_explicit_for(method: FunctionType, message: PytestWarning) -> None:
"""
Issue the warning :param:`message` for the definition of the given :param:`method`
this helps to log warnings for functio... | PytestFDWarning |
python | bokeh__bokeh | src/bokeh/core/serialization.py | {
"start": 3196,
"end": 3314
} | class ____(TypedDict):
type: Literal["object"]
name: str
attributes: NotRequired[dict[str, AnyRep]]
| ObjectRep |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-kyriba/source_kyriba/source.py | {
"start": 8616,
"end": 8696
} | class ____(BankBalancesStream):
balance_type = "INTRADAY"
| BankBalancesIntraday |
python | python__mypy | mypy/nodes.py | {
"start": 1465,
"end": 1514
} | class ____(Enum):
VALUE = "NotParsed"
| NotParsed |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.