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 | has2k1__plotnine | plotnine/exceptions.py | {
"start": 888,
"end": 1616
} | class ____(UserWarning):
"""
Warnings for ggplot inconsistencies
"""
def deprecated_themeable_name(cls):
"""
Decorator to deprecate the name of a themeable
"""
old_init = cls.__init__
@functools.wraps(cls.__init__)
def new_init(self, *args, **kwargs):
old_name = cls.__name... | PlotnineWarning |
python | mlflow__mlflow | mlflow/genai/optimize/types.py | {
"start": 1353,
"end": 3468
} | class ____:
"""
Configuration for prompt optimization.
Args:
num_instruction_candidates: Number of candidate instructions to generate
during each optimization iteration. Higher values may lead to better
results but increase optimization time. Default: 6
max_few_shot_... | OptimizerConfig |
python | openai__openai-python | src/openai/types/webhooks/batch_cancelled_webhook_event.py | {
"start": 239,
"end": 326
} | class ____(BaseModel):
id: str
"""The unique ID of the batch API request."""
| Data |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/execution_api/app.py | {
"start": 5644,
"end": 11199
} | class ____(Cadwyn):
# Workaround lack of customzation https://github.com/zmievsa/cadwyn/issues/255
async def openapi_jsons(self, req: Request) -> JSONResponse:
resp = await super().openapi_jsons(req)
open_apischema = json.loads(resp.body)
open_apischema = self.customize_openapi(open_apis... | CadwynWithOpenAPICustomization |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/decorators/op_decorator.py | {
"start": 1289,
"end": 10770
} | class ____:
def __init__(
self,
name: Optional[str] = None,
description: Optional[str] = None,
required_resource_keys: Optional[AbstractSet[str]] = None,
config_schema: Optional[Union[Any, Mapping[str, Any]]] = None,
tags: Optional[Mapping[str, Any]] = None,
c... | _Op |
python | ray-project__ray | python/ray/data/tests/preprocessors/test_encoder.py | {
"start": 24762,
"end": 35769
} | class ____:
"""Test basic serialization/deserialization functionality for all encoder preprocessors."""
def setup_method(self):
"""Set up test data for encoders."""
# Data for categorical encoders
self.categorical_df = pd.DataFrame(
{
"category": ["A", "B", "... | TestEncoderSerialization |
python | ray-project__ray | release/ray_release/cluster_manager/minimal.py | {
"start": 481,
"end": 9598
} | class ____(ClusterManager):
"""Minimal manager.
Builds app config and compute template but does not start or stop session.
"""
@retry(
init_delay_sec=10,
jitter_sec=5,
max_retry_count=2,
exceptions=(ClusterEnvCreateError,),
)
def create_cluster_env(self):
... | MinimalClusterManager |
python | huggingface__transformers | src/transformers/models/glm4v/modeling_glm4v.py | {
"start": 23546,
"end": 26871
} | class ____(nn.Module):
"""
Multi-headed attention from 'Attention Is All You Need' paper.
and "Generating Long Sequences with Sparse Transformers".
"""
def __init__(self, config: Glm4vTextConfig, layer_idx: Optional[int] = None):
super().__init__()
self.config = config
self.... | Glm4vTextAttention |
python | pytorch__pytorch | test/distributed/test_store.py | {
"start": 21722,
"end": 22103
} | class ____(TCPStoreTest):
_use_libuv = True
def _create_store(self):
store = create_tcp_store(use_libuv=True)
store.set_timeout(timedelta(seconds=300))
return store
def _create_store_with_ws(self, addr, world_size):
return create_tcp_store(
addr, world_size, wai... | LibUvTCPStoreTest |
python | dagster-io__dagster | python_modules/automation/automation/scaffold_logs_viewer/server.py | {
"start": 164,
"end": 5350
} | class ____(BaseHTTPRequestHandler):
def __init__(self, *args, logs_directory: Path, **kwargs):
self.logs_directory = logs_directory
super().__init__(*args, **kwargs)
def do_GET(self):
parsed_path = urlparse(self.path)
path = parsed_path.path
if path == "/" or path == "/... | ScaffoldBranchLogsHandler |
python | ray-project__ray | python/ray/dag/py_obj_scanner.py | {
"start": 711,
"end": 3676
} | class ____(ray.cloudpickle.CloudPickler, Generic[SourceType, TransformedType]):
"""Utility to find and replace the `source_type` in Python objects.
`source_type` can either be a single type or a tuple of multiple types.
The caller must first call `find_nodes()`, then compute a replacement table and
pa... | _PyObjScanner |
python | huggingface__transformers | src/transformers/models/metaclip_2/modeling_metaclip_2.py | {
"start": 2975,
"end": 7573
} | class ____(nn.Module):
def __init__(self, config: MetaClip2VisionConfig):
super().__init__()
self.config = config
self.embed_dim = config.hidden_size
self.image_size = config.image_size
self.patch_size = config.patch_size
self.class_embedding = nn.Parameter(torch.ran... | MetaClip2VisionEmbeddings |
python | mahmoud__boltons | boltons/tableutils.py | {
"start": 5702,
"end": 6000
} | class ____(InputType):
def check_type(self, obj):
return isinstance(obj, MutableSequence)
def guess_headers(self, obj):
return None
def get_entry(self, obj, headers):
return obj
def get_entry_seq(self, obj_seq, headers):
return obj_seq
| ListInputType |
python | optuna__optuna | optuna/storages/_rdb/alembic/versions/v3.0.0.b.py | {
"start": 1115,
"end": 2956
} | class ____(BaseModel):
__tablename__ = "trial_values"
trial_value_id = Column(Integer, primary_key=True)
trial_id = Column(Integer, ForeignKey("trials.trial_id"), nullable=False)
value = Column(Float, nullable=False)
def upgrade():
bind = op.get_bind()
session = Session(bind=bind)
if (
... | TrialValueModel |
python | mlflow__mlflow | mlflow/llama_index/pyfunc_wrapper.py | {
"start": 5642,
"end": 6098
} | class ____(_LlamaIndexModelWrapperBase):
@property
def engine_type(self):
return RETRIEVER_ENGINE_NAME
def _predict_single(self, *args, **kwargs) -> list[dict[str, Any]]:
response = self._llama_model.retrieve(*args, **kwargs)
return [node.dict() for node in response]
def _forma... | RetrieverEngineWrapper |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/rich/pretty.py | {
"start": 16720,
"end": 35848
} | class ____:
"""A line in repr output."""
parent: Optional["_Line"] = None
is_root: bool = False
node: Optional[Node] = None
text: str = ""
suffix: str = ""
whitespace: str = ""
expanded: bool = False
last: bool = False
@property
def expandable(self) -> bool:
"""Chec... | _Line |
python | RaRe-Technologies__gensim | gensim/test/test_ensemblelda.py | {
"start": 583,
"end": 20009
} | class ____(unittest.TestCase):
def get_elda(self):
return EnsembleLda(
corpus=common_corpus, id2word=common_dictionary, num_topics=NUM_TOPICS,
passes=PASSES, num_models=NUM_MODELS, random_state=RANDOM_STATE,
topic_model_class=LdaModel,
)
def get_elda_mem_unfr... | TestEnsembleLda |
python | pytorch__pytorch | torch/ao/nn/qat/dynamic/modules/linear.py | {
"start": 156,
"end": 1215
} | class ____(torch.ao.nn.qat.Linear):
r"""
A linear module attached with FakeQuantize modules for weight,
used for dynamic quantization aware training.
We adopt the same interface as `torch.nn.Linear`, please see
https://pytorch.org/docs/stable/nn.html#torch.nn.Linear
for documentation.
Simi... | Linear |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/test/steps/manifest_only_connectors.py | {
"start": 2804,
"end": 8358
} | class ____(PytestStep):
"""A step to run unit tests for a manifest-only connector"""
title = "Manifest-only unit tests"
test_directory_name = "unit_tests"
common_test_dependencies = ["freezegun", "pytest", "pytest-mock", "requests-mock"]
async def install_testing_environment(
self,
... | ManifestOnlyConnectorUnitTests |
python | sympy__sympy | sympy/physics/continuum_mechanics/truss.py | {
"start": 765,
"end": 44962
} | class ____:
"""
A Truss is an assembly of members such as beams,
connected by nodes, that create a rigid structure.
In engineering, a truss is a structure that
consists of two-force members only.
Trusses are extremely important in engineering applications
and can be seen in numerous real-wo... | Truss |
python | davidhalter__jedi | jedi/inference/value/function.py | {
"start": 1493,
"end": 1968
} | class ____(TreeValue):
def get_qualified_names(self):
if self.parent_context.is_class():
n = self.parent_context.get_qualified_names()
if n is None:
# This means that the parent class lives within a function.
return None
return n + (self.py... | FunctionAndClassBase |
python | keras-team__keras | keras/src/layers/preprocessing/mel_spectrogram_test.py | {
"start": 173,
"end": 3388
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_mel_spectrogram_basics(self):
self.run_layer_test(
layers.MelSpectrogram,
init_kwargs={
"num_mel_bins": 80,
"sampling_rate": 8000,
"sequence_stride": 128... | MelSpectrogramTest |
python | mlflow__mlflow | tests/genai/judges/test_judge_tool_registry.py | {
"start": 908,
"end": 6602
} | class ____(JudgeTool):
@property
def name(self) -> str:
return "mock_tool"
def get_definition(self) -> ToolDefinition:
return ToolDefinition(
function={
"name": "mock_tool",
"description": "A mock tool for testing",
"parameters": {... | MockTool |
python | doocs__leetcode | solution/2300-2399/2347.Best Poker Hand/Solution.py | {
"start": 0,
"end": 408
} | class ____:
def bestHand(self, ranks: List[int], suits: List[str]) -> str:
# if len(set(suits)) == 1:
if all(a == b for a, b in pairwise(suits)):
return 'Flush'
cnt = Counter(ranks)
if any(v >= 3 for v in cnt.values()):
return 'Three of a Kind'
if any(... | Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF008_attrs.py | {
"start": 462,
"end": 751
} | class ____:
mutable_default: list[int] = []
immutable_annotation: Sequence[int] = []
without_annotation = []
correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT
perfectly_fine: list[int] = field(default_factory=list)
class_variable: ClassVar[list[int]] = []
@attr.s
| B |
python | pytorch__pytorch | torch/fx/experimental/optimization.py | {
"start": 7110,
"end": 9409
} | class ____:
def __init__(self, fx_graph: fx.Graph):
self.fx_graph = fx_graph
self.nodes: list[fx.Node] = []
self.start_nodes: list[fx.Node] = []
self.end_nodes: list[fx.Node] = []
def gen_mkl_autotuner(example_inputs, iters=10, warmup=1):
"""
This generates a heuristic that... | MklSubgraph |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/variables/variables_test.py | {
"start": 28278,
"end": 29438
} | class ____(test.TestCase):
def testNoVars(self):
with ops.Graph().as_default():
self.assertEqual(None, variables.assert_variables_initialized())
def testVariables(self):
with ops.Graph().as_default(), self.cached_session() as sess:
v = variable_v1.VariableV1([1, 2])
w = variable_v1.Varia... | ObsoleteIsInitializedTest |
python | scikit-learn__scikit-learn | sklearn/model_selection/_plot.py | {
"start": 339,
"end": 4163
} | class ____:
def _plot_curve(
self,
x_data,
*,
ax=None,
negate_score=False,
score_name=None,
score_type="test",
std_display_style="fill_between",
line_kw=None,
fill_between_kw=None,
errorbar_kw=None,
):
check_matplotl... | _BaseCurveDisplay |
python | pytorch__pytorch | torch/distributed/elastic/timer/local_timer.py | {
"start": 2141,
"end": 4282
} | class ____(TimerServer):
"""
Server that works with ``LocalTimerClient``. Clients are expected to be
subprocesses to the parent process that is running this server. Each host
in the job is expected to start its own timer server locally and each
server instance manages timers for local workers (runni... | LocalTimerServer |
python | pola-rs__polars | py-polars/src/polars/interchange/protocol.py | {
"start": 5024,
"end": 6679
} | class ____(Protocol):
"""Interchange dataframe object."""
version: ClassVar[int] # Version of the protocol
def __dataframe__(
self,
nan_as_null: bool = False, # noqa: FBT001
allow_copy: bool = True, # noqa: FBT001
) -> DataFrame:
"""Convert to a dataframe object impl... | DataFrame |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF033.py | {
"start": 345,
"end": 435
} | class ____:
def __post_init__(self, bar = 11, baz = 11) -> None: ...
# OK
@dataclass
| Foo |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/inputs.py | {
"start": 3975,
"end": 4364
} | class ____(graphene.InputObjectType):
groupName = graphene.NonNull(graphene.String)
repositoryName = graphene.NonNull(graphene.String)
repositoryLocationName = graphene.NonNull(graphene.String)
class Meta:
description = """This type represents the fields necessary to identify
an asset g... | GrapheneAssetGroupSelector |
python | huggingface__transformers | src/transformers/models/rt_detr_v2/modeling_rt_detr_v2.py | {
"start": 48083,
"end": 48722
} | class ____(nn.Module):
def __init__(self, config: RTDetrV2Config):
super().__init__()
self.layers = nn.ModuleList([RTDetrV2EncoderLayer(config) for _ in range(config.encoder_layers)])
def forward(self, src, src_mask=None, pos_embed=None, output_attentions: bool = False) -> torch.Tensor:
... | RTDetrV2Encoder |
python | pypa__warehouse | warehouse/accounts/models.py | {
"start": 12329,
"end": 13598
} | class ____(db.ModelBase):
__tablename__ = "user_emails"
__table_args__ = (
UniqueConstraint("email", name="user_emails_email_key"),
Index("user_emails_user_id", "user_id"),
)
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[UUID] = mapped_column(
PG_UUID(as_... | Email |
python | matplotlib__matplotlib | lib/matplotlib/image.py | {
"start": 51701,
"end": 53836
} | class ____(_ImageBase):
"""An image attached to a figure."""
zorder = 0
_interpolation = 'nearest'
def __init__(self, fig,
*,
cmap=None,
norm=None,
colorizer=None,
offsetx=0,
offsety=0,
... | FigureImage |
python | protocolbuffers__protobuf | python/google/protobuf/internal/numpy/numpy_test.py | {
"start": 1821,
"end": 4312
} | class ____(unittest.TestCase):
# Assigning dim 1 ndarray of ints to repeated field should pass
def testNumpyDim1IntArrayToRepeated_IsValid(self):
message.repeated_int64[:] = np_1_int_array
message.repeated_int64[:] = np_2_int_array
message.repeated_uint64[:] = np_1_uint_array
message.repeated_uint... | NumpyIntProtoTest |
python | fluentpython__example-code-2e | 15-more-types/cafeteria/invariant.py | {
"start": 61,
"end": 109
} | class ____: # <1>
"""Any beverage."""
| Beverage |
python | django__django | tests/composite_pk/test_values.py | {
"start": 142,
"end": 9754
} | class ____(TestCase):
USER_1_EMAIL = "user0001@example.com"
USER_2_EMAIL = "user0002@example.com"
USER_3_EMAIL = "user0003@example.com"
POST_1_ID = "77777777-7777-7777-7777-777777777777"
POST_2_ID = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
POST_3_ID = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
@c... | CompositePKValuesTests |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_R.py | {
"start": 6386,
"end": 7584
} | class ____(Benchmark):
r"""
Ripple 25 objective function.
This class defines the Ripple 25 [1]_ global optimization problem. This is a
multimodal minimization problem defined as follows:
.. math::
f_{\text{Ripple25}}(x) = \sum_{i=1}^2 -e^{-2
\log 2 (\frac{x_i-0.1}{0.8})^2}
... | Ripple25 |
python | getsentry__sentry | src/sentry/api/exceptions.py | {
"start": 641,
"end": 1319
} | class ____(APIException):
code = ""
message = ""
def __init__(self, code=None, message=None, detail=None, **kwargs):
# Note that we no longer call the base `__init__` here. This is because
# DRF now forces all detail messages that subclass `APIException` to a
# string, which breaks ... | SentryAPIException |
python | scrapy__scrapy | tests/test_downloader_handlers_http_base.py | {
"start": 27161,
"end": 28699
} | class ____(ABC):
@property
@abstractmethod
def settings_dict(self) -> dict[str, Any] | None:
raise NotImplementedError
is_secure = False
@deferred_f_from_coro_f
async def test_download_with_content_length(self, mockserver: MockServer) -> None:
crawler = get_crawler(SingleReques... | TestHttpWithCrawlerBase |
python | getsentry__sentry | tests/sentry/api/endpoints/test_source_map_debug_blue_thunder_edition.py | {
"start": 1911,
"end": 64760
} | class ____(APITestCase):
endpoint = "sentry-api-0-event-source-map-debug-blue-thunder-edition"
def setUp(self) -> None:
self.login_as(self.user)
return super().setUp()
def test_missing_event(self) -> None:
resp = self.get_error_response(
self.organization.slug,
... | SourceMapDebugBlueThunderEditionEndpointTestCase |
python | sqlalchemy__sqlalchemy | test/orm/test_unitofworkv2.py | {
"start": 124297,
"end": 125237
} | class ____(UOWTest):
def test_ensure_cache(self):
users, User = self.tables.users, self.classes.User
self.mapper_registry.map_imperatively(User, users)
cache = {}
eq_(len(inspect(User)._compiled_cache), 0)
with testing.db.connect().execution_options(
compiled_c... | EnsureCacheTest |
python | django__django | tests/admin_views/models.py | {
"start": 13633,
"end": 14005
} | class ____(models.Model):
"Because we all know there's only one real use case for GFKs."
name = models.CharField(max_length=25)
content_type = models.ForeignKey(ContentType, models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey("content_type", "object_id")
... | FunkyTag |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 575031,
"end": 575427
} | class ____(sgqlc.types.Type):
"""An edge in a connection."""
__schema__ = github_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
"""A cursor for use in pagination."""
node = sgqlc.types.Field("DeploymentStatus", graphq... | DeploymentStatusEdge |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/src/connectors_qa/checks/documentation/documentation.py | {
"start": 835,
"end": 4763
} | class ____(DocumentationCheck):
name = "Breaking changes must be accompanied by a migration guide"
description = "When a breaking change is introduced, we check that a migration guide is available. It should be stored under `./docs/integrations/<connector-type>s/<connector-name>-migrations.md`.\nThis document s... | CheckMigrationGuide |
python | readthedocs__readthedocs.org | readthedocs/core/unresolver.py | {
"start": 1041,
"end": 1140
} | class ____(UnresolverError):
def __init__(self, domain):
self.domain = domain
| DomainError |
python | chroma-core__chroma | chromadb/test/conftest.py | {
"start": 28126,
"end": 33488
} | class ____:
"""This allows consuming tests to be parameterized by async/sync versions of the client and papers over the async implementation.
If you don't need to manually construct clients, use the `client` fixture instead.
"""
_system: System
# Need to track created clients so we can call .clear_... | ClientFactories |
python | numba__numba | numba/tests/test_listobject.py | {
"start": 3120,
"end": 3883
} | class ____(MemoryLeakMixin, TestCase):
def test_list_to_from_meminfo(self):
"""
Exercise listobject.{_as_meminfo, _from_meminfo}
"""
@njit
def boxer():
l = listobject.new_list(int32)
for i in range(10, 20):
l.append(i)
ret... | TestToFromMeminfo |
python | pytorch__pytorch | torch/masked/maskedtensor/core.py | {
"start": 4328,
"end": 13059
} | class ____(torch.Tensor):
@staticmethod
def __new__(cls, data, mask, requires_grad=False):
if is_masked_tensor(data) or not torch.is_tensor(data):
raise TypeError("data must be a Tensor")
if is_masked_tensor(mask) or not torch.is_tensor(mask):
raise TypeError("mask must b... | MaskedTensor |
python | ray-project__ray | python/ray/llm/_internal/common/models.py | {
"start": 381,
"end": 1303
} | class ____:
"""Thread-safe global ID manager for assigning unique IDs."""
def __init__(self):
self._counter = 0
self._lock = threading.Lock()
def next(self) -> int:
"""Get the next unique ID."""
with self._lock:
self._counter += 1
return self._counte... | GlobalIdManager |
python | cython__cython | Cython/Debugger/libcython.py | {
"start": 32167,
"end": 33420
} | class ____(CythonBase, libpython.PythonInfo):
"""
Implementation of the interface dictated by libpython.LanguageInfo.
"""
def lineno(self, frame):
# Take care of the Python and Cython levels. We need to care for both
# as we can't simply dispatch to 'py-step', since that would work for
... | CythonInfo |
python | pypa__pip | src/pip/_vendor/truststore/_api.py | {
"start": 2369,
"end": 11413
} | class ____(_truststore_SSLContext_super_class): # type: ignore[misc]
"""SSLContext API that uses system certificates on all platforms"""
@property # type: ignore[misc]
def __class__(self) -> type:
# Dirty hack to get around isinstance() checks
# for ssl.SSLContext instances in aiohttp/tru... | SSLContext |
python | pypa__setuptools | setuptools/command/install.py | {
"start": 1004,
"end": 5066
} | class ____(orig.install):
"""Use easy_install to install the package, w/dependencies"""
distribution: Distribution # override distutils.dist.Distribution with setuptools.dist.Distribution
user_options = orig.install.user_options + [
('old-and-unmanageable', None, "Try not to use this!"),
... | install |
python | openai__gym | gym/spaces/graph.py | {
"start": 999,
"end": 9771
} | class ____(Space):
r"""A space representing graph information as a series of `nodes` connected with `edges` according to an adjacency matrix represented as a series of `edge_links`.
Example usage::
self.observation_space = spaces.Graph(node_space=space.Box(low=-100, high=100, shape=(3,)), edge_space=s... | Graph |
python | pypa__setuptools | setuptools/build_meta.py | {
"start": 2346,
"end": 5125
} | class ____(setuptools.dist.Distribution):
def fetch_build_eggs(self, specifiers) -> NoReturn:
specifier_list = list(parse_strings(specifiers))
raise SetupRequirementsError(specifier_list)
@classmethod
@contextlib.contextmanager
def patch(cls) -> Iterator[None]:
"""
Repl... | Distribution |
python | PyCQA__pylint | tests/functional/u/unhashable_member.py | {
"start": 105,
"end": 598
} | class ____:
__hash__ = list.__hash__
# Subscripts
{}[[1, 2, 3]] # [unhashable-member]
{}[{}] # [unhashable-member]
{}[Unhashable()] # [unhashable-member]
{'foo': 'bar'}['foo']
{'foo': 'bar'}[42]
# Keys
{[1, 2, 3]: "tomato"} # [unhashable-member]
{
[1, 2, 3]: "tomato", # [unhashable-member]
[4, 5, 6]: "c... | Unhashable |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 18455,
"end": 19819
} | class ____(CDeclaratorNode):
# name string The Cython name being declared
# cname string or None C name, if specified
# default ExprNode or None the value assigned on declaration
child_attrs = ['default']
default = None
def declared_name(self):
return self.na... | CNameDeclaratorNode |
python | pytorch__pytorch | torch/nn/modules/container.py | {
"start": 1214,
"end": 1397
} | class ____(Module):
def __init__(self, **kwargs: Any) -> None:
super().__init__()
for key, value in kwargs.items():
self.add_module(key, value)
| Container |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/coercions.py | {
"start": 29858,
"end": 30354
} | class ____(_Deannotate, _CoerceLiterals, RoleImpl):
__slots__ = ()
_coerce_consts = True
def _text_coercion(self, element, argname=None):
# see #5754 for why we can't easily deprecate this coercion.
# essentially expressions like postgresql_where would have to be
# text() as they c... | DDLExpressionImpl |
python | numba__numba | numba/tests/test_ir_inlining.py | {
"start": 14230,
"end": 31000
} | class ____(MemoryLeakMixin, InliningBase):
def test_basic_inline_never(self):
def foo():
pass
@overload(foo, inline='never')
def foo_overload():
def foo_impl():
pass
return foo_impl
def impl():
return foo()
s... | TestOverloadInlining |
python | falconry__falcon | falcon/app.py | {
"start": 56387,
"end": 57019
} | class ____(App):
"""Compatibility alias of :class:`falcon.App`.
``API`` was renamed to :class:`App <falcon.App>` in Falcon 3.0 in order to
reflect the breadth of applications that :class:`App <falcon.App>`, and its
ASGI counterpart in particular, can now be used for.
.. deprecated:: 3.0
Th... | API |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP008.py | {
"start": 1825,
"end": 1868
} | class ____:
def foo(self):
pass
| A |
python | spack__spack | lib/spack/spack/test/util/unparse/unparse.py | {
"start": 3163,
"end": 14405
} | class ____:
x: int
y: int
def location(point):
match point:
case Point(x=0, y=0):
print("Origin is the point's location.")
case Point(x=0, y=y):
print(f"Y={y} and the point is on the y-axis.")
case Point(x=x, y=0):
print(f"X={x} and the point is o... | Point |
python | doocs__leetcode | solution/2300-2399/2350.Shortest Impossible Sequence of Rolls/Solution.py | {
"start": 0,
"end": 258
} | class ____:
def shortestSequence(self, rolls: List[int], k: int) -> int:
ans = 1
s = set()
for v in rolls:
s.add(v)
if len(s) == k:
ans += 1
s.clear()
return ans
| Solution |
python | apache__airflow | providers/apache/cassandra/tests/unit/apache/cassandra/sensors/test_table.py | {
"start": 1075,
"end": 3103
} | class ____:
@patch("airflow.providers.apache.cassandra.sensors.table.CassandraHook")
def test_poke(self, mock_hook):
sensor = CassandraTableSensor(
task_id="test_task",
cassandra_conn_id=TEST_CASSANDRA_CONN_ID,
table=TEST_CASSANDRA_TABLE,
)
exists = se... | TestCassandraTableSensor |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py | {
"start": 3708,
"end": 3874
} | class ____:
def __str__(self, weird_extra_arg) -> str:
...
def __repr__(self, weird_extra_arg_with_default=...) -> str:
...
@final
| FineAndDandy |
python | pytorch__pytorch | torch/distributed/tensor/experimental/_context_parallel/_load_balancer.py | {
"start": 3428,
"end": 7778
} | class ____(_LoadBalancer):
def __init__(self, seq_length: int, world_size: int, device: str | torch.device):
self.seq_length = seq_length
self.world_size = world_size
self.device = device
def _generate_indices(self, restore: bool = False) -> Tensor:
"""
Generate head-and... | _HeadTailLoadBalancer |
python | doocs__leetcode | solution/1500-1599/1553.Minimum Number of Days to Eat N Oranges/Solution.py | {
"start": 0,
"end": 240
} | class ____:
def minDays(self, n: int) -> int:
@cache
def dfs(n: int) -> int:
if n < 2:
return n
return 1 + min(n % 2 + dfs(n // 2), n % 3 + dfs(n // 3))
return dfs(n)
| Solution |
python | huggingface__transformers | src/transformers/models/kyutai_speech_to_text/modular_kyutai_speech_to_text.py | {
"start": 10281,
"end": 10360
} | class ____(MimiConv1dPaddingCache):
pass
| KyutaiSpeechToTextConv1dPaddingCache |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 868570,
"end": 874506
} | class ____(sgqlc.types.Type, Closable, Updatable, Node):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"created_at",
"creator",
"database_id",
"field",
"fields",
"items",
"number",
"owner",
... | ProjectV2 |
python | astropy__astropy | astropy/modeling/fitting.py | {
"start": 44588,
"end": 56881
} | class ____(Fitter):
"""
Base class for Non-Linear least-squares fitters.
Parameters
----------
calc_uncertainties : bool
If the covariance matrix should be computed and set in the fit_info.
Default: False
use_min_max_bounds : bool
If set, the parameter bounds for a model... | _NonLinearLSQFitter |
python | sphinx-doc__sphinx | sphinx/util/cfamily.py | {
"start": 6624,
"end": 7296
} | class ____(ASTAttribute):
"""For paren attributes defined by the user."""
def __init__(self, id: str, arg: str) -> None:
self.id = id
self.arg = arg
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTParenAttribute):
return NotImplemented
retur... | ASTParenAttribute |
python | tensorflow__tensorflow | tensorflow/python/ops/parallel_for/test_util.py | {
"start": 949,
"end": 3112
} | class ____(test.TestCase):
"""Base class for test cases."""
def _run_targets(self, targets1, targets2=None, run_init=True):
targets1 = nest.flatten(targets1)
targets2 = ([] if targets2 is None else nest.flatten(targets2))
assert len(targets1) == len(targets2) or not targets2
if run_init:
init... | PForTestCase |
python | etianen__django-reversion | tests/test_app/tests/test_views.py | {
"start": 1311,
"end": 1597
} | class ____(LoginMixin, TestModelMixin, TestBase):
def testCreateRevisionUser(self):
response = self.client.post("/test-app/revision-mixin/")
obj = TestModel.objects.get(pk=response.content)
self.assertSingleRevision((obj,), user=self.user)
| RevisionMixinUserTest |
python | ipython__ipython | IPython/core/magic_arguments.py | {
"start": 8710,
"end": 8907
} | class ____(ArgMethodWrapper):
""" Store arguments and keywords to pass to add_argument().
Instances also serve to decorate command methods.
"""
_method_name = 'add_argument'
| argument |
python | kamyu104__LeetCode-Solutions | Python/zuma-game.py | {
"start": 1714,
"end": 3503
} | class ____(object):
def findMinStep(self, board, hand):
"""
:type board: str
:type hand: str
:rtype: int
"""
def shrink(s): # Time: O(n), Space: O(n)
stack = []
start = 0
for i in xrange(len(s)+1):
if i == len(s) or... | Solution_TLE |
python | automl__auto-sklearn | autosklearn/metalearning/metafeatures/metafeature.py | {
"start": 1412,
"end": 2367
} | class ____(object):
def __init__(self, name, type_, fold, repeat, value, time, comment=""):
self.name = name
self.type_ = type_
self.fold = fold
self.repeat = repeat
self.value = value
self.time = time
self.comment = comment
def to_arff_row(self):
... | MetaFeatureValue |
python | scikit-learn__scikit-learn | sklearn/_loss/loss.py | {
"start": 26589,
"end": 27603
} | class ____(BaseLoss):
"""Half Gamma deviance loss with log-link, for regression.
Domain:
y_true and y_pred in positive real numbers
Link:
y_pred = exp(raw_prediction)
For a given sample x_i, half Gamma deviance loss is defined as::
loss(x_i) = log(exp(raw_prediction_i)/y_true_i)
... | HalfGammaLoss |
python | Netflix__metaflow | metaflow/plugins/datatools/s3/s3.py | {
"start": 3203,
"end": 3288
} | class ____(MetaflowException):
headline = "S3 invalid range"
| MetaflowS3InvalidRange |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/actions.py | {
"start": 1935,
"end": 2223
} | class ____(CompositeAction):
"""Composite action parser for a sanity target."""
def create_parser(self) -> NamespaceParser:
"""Return a namespace parser to parse the argument associated with this action."""
return SanityPythonTargetParser()
| SanityPythonTargetAction |
python | bokeh__bokeh | src/bokeh/client/websocket.py | {
"start": 1630,
"end": 3239
} | class ____:
''' Used for compatibility across Tornado versions and to add write_lock'''
def __init__(self, socket: WebSocketClientConnection) -> None:
self._socket = socket
# write_lock allows us to lock the connection to send multiple
# messages atomically.
self.write_lock = lo... | WebSocketClientConnectionWrapper |
python | apache__thrift | lib/py/src/protocol/TBase.py | {
"start": 2829,
"end": 2895
} | class ____(TFrozenBase, TExceptionBase):
pass
| TFrozenExceptionBase |
python | wandb__wandb | wandb/sdk/data_types/table.py | {
"start": 50156,
"end": 54445
} | class ____(_dtypes.Type):
name = "partitioned-table"
types = [PartitionedTable]
_dtypes.TypeRegistry.add(_TableType)
_dtypes.TypeRegistry.add(_JoinedTableType)
_dtypes.TypeRegistry.add(_PartitionedTableType)
_dtypes.TypeRegistry.add(_ForeignKeyType)
_dtypes.TypeRegistry.add(_PrimaryKeyType)
_dtypes.TypeRegist... | _PartitionedTableType |
python | plotly__plotly.py | plotly/graph_objs/densitymap/colorbar/_tickformatstop.py | {
"start": 233,
"end": 8529
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "densitymap.colorbar"
_path_str = "densitymap.colorbar.tickformatstop"
_valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"}
@property
def dtickrange(self):
"""
range [*min*, *max*], where "min", "ma... | Tickformatstop |
python | openai__openai-python | src/openai/types/realtime/realtime_audio_config_input_param.py | {
"start": 533,
"end": 813
} | class ____(TypedDict, total=False):
type: NoiseReductionType
"""Type of noise reduction.
`near_field` is for close-talking microphones such as headphones, `far_field` is
for far-field microphones such as laptop or conference room microphones.
"""
| NoiseReduction |
python | getsentry__sentry | src/sentry/search/eap/columns.py | {
"start": 8797,
"end": 9617
} | class ____(ResolvedFunction):
# The internal rpc alias for this column
internal_name: Function.ValueType
extrapolation_mode: ExtrapolationMode.ValueType
# The condition to filter on
filter: TraceItemFilter
# The attribute to conditionally aggregate on
key: AttributeKey
is_aggregate: boo... | ResolvedConditionalAggregate |
python | TheAlgorithms__Python | data_structures/linked_list/__init__.py | {
"start": 431,
"end": 3760
} | class ____:
def __init__(self) -> None:
self.head: Node | None = None
self.size = 0
def add(self, item: Any, position: int = 0) -> None:
"""
Add an item to the LinkedList at the specified position.
Default position is 0 (the head).
Args:
item (Any): ... | LinkedList |
python | pennersr__django-allauth | allauth/socialaccount/providers/twitter/views.py | {
"start": 245,
"end": 562
} | class ____(OAuth):
"""
Verifying twitter credentials
"""
_base_url = "https://api.x.com/1.1/account/verify_credentials.json"
url = _base_url + "?include_email=true" if QUERY_EMAIL else _base_url
def get_user_info(self):
user = self.query(self.url).json()
return user
| TwitterAPI |
python | astropy__astropy | astropy/io/votable/converters.py | {
"start": 15272,
"end": 16494
} | class ____(Array):
"""
Handles variable lengths arrays (i.e. where *arraysize* is '*').
"""
format = "O"
def __init__(self, field, base, arraysize, config=None, pos=None):
Array.__init__(self, field, config)
self._base = base
self.default = np.array([], dtype=self._base.fo... | VarArray |
python | pytorch__pytorch | torch/utils/weak.py | {
"start": 5484,
"end": 11545
} | class ____(MutableMapping):
def __init__(self, dict=None, ref_type=WeakIdRef) -> None: # CHANGED
self.data = {}
self.ref_type = ref_type # CHANGED
def remove(k, selfref=ref(self)) -> None:
self = selfref()
if self is not None:
if self._iterating:
... | WeakIdKeyDictionary |
python | ray-project__ray | rllib/core/columns.py | {
"start": 62,
"end": 2560
} | class ____:
"""Definitions of common column names for RL data, e.g. 'obs', 'rewards', etc..
Note that this replaces the `SampleBatch` and `Postprocessing` columns (of the same
name).
"""
# Observation received from an environment after `reset()` or `step()`.
OBS = "obs"
# Infos received fr... | Columns |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 14536,
"end": 16473
} | class ____(nodes.Inline, nodes.TextElement):
"""Node representing a potential way to create a cross-reference and the
condition in which this way should be used.
This node is only allowed to be placed under a :py:class:`pending_xref`
node. A **pending_xref** node must contain either no **pending_xref_... | pending_xref_condition |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/emr.py | {
"start": 64274,
"end": 71266
} | class ____(AwsBaseOperator[EmrServerlessHook]):
"""
Operator to stop an EMR Serverless application.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:EmrServerlessStopApplicationOperator`
:param application_id: ID of the EMR S... | EmrServerlessStopApplicationOperator |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 9232,
"end": 9377
} | class ____(_TestDCTIIIBase):
def setup_method(self):
self.rdt = np.float64
self.dec = 14
self.type = 3
| TestDCTIIIDouble |
python | pytorch__pytorch | torch/distributed/checkpoint/metadata.py | {
"start": 3576,
"end": 3785
} | class ____:
checkpoint_id: Union[str, os.PathLike, None] = None
save_id: Optional[str] = None
load_id: Optional[str] = None
modules: list[str] = field(default_factory=list)
@dataclass
| StorageMeta |
python | kamyu104__LeetCode-Solutions | Python/maximum-number-of-integers-to-choose-from-a-range-i.py | {
"start": 794,
"end": 1592
} | class ____(object):
def maxCount(self, banned, n, maxSum):
"""
:type banned: List[int]
:type n: int
:type maxSum: int
:rtype: int
"""
def check(x):
return (x+1)*x//2-prefix[bisect.bisect_right(sorted_banned, x)] <= maxSum
sorted_banned... | Solution2 |
python | geekcomputers__Python | BlackJack_game/blackjack_simulate.py | {
"start": 9273,
"end": 11646
} | class ____:
def __init__(self):
self.data = []
self.winner = None
self.remain_chips = 0
self.rounds = 0
self.player_win_count = 0
self.dealer_win_count = 0
self.player_point = 0
self.dealer_point = 0
def update(self, winner, chips, player_point, d... | Recorder |
python | conda__conda | conda/exceptions.py | {
"start": 13388,
"end": 13824
} | class ____(CondaError):
def __init__(self, target_directory: PathType):
message = dals(
"""
The target directory exists, but it is not a conda environment.
Use 'conda create' to convert the directory to a conda environment.
target directory: %(target_directory)s
... | DirectoryNotACondaEnvironmentError |
python | getsentry__sentry | tests/sentry/integrations/discord/test_issue_alert.py | {
"start": 1547,
"end": 11885
} | class ____(RuleTestCase):
rule_cls = DiscordNotifyServiceAction
def setUp(self) -> None:
self.guild_id = "guild-id"
self.channel_id = "12345678910"
self.discord_user_id = "user1234"
self.discord_integration = self.create_integration(
provider="discord",
n... | DiscordIssueAlertTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.