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 | ray-project__ray | rllib/algorithms/impala/impala_learner.py | {
"start": 12425,
"end": 16346
} | class ____(threading.Thread):
def __init__(
self,
*,
in_queue: queue.Queue,
out_queue: deque,
device: torch.device,
metrics_logger: MetricsLogger,
):
super().__init__(name="_GPULoaderThread")
self.daemon = True
self._in_queue = in_queue
... | _GPULoaderThread |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 152341,
"end": 153316
} | class ____(ASTBase):
def __init__(self, expr: ASTExpression) -> None:
self.expr = expr
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTRequiresClause):
return NotImplemented
return self.expr == other.expr
def __hash__(self) -> int:
return ha... | ASTRequiresClause |
python | run-llama__llama_index | llama-index-experimental/llama_index/experimental/param_tuner/base.py | {
"start": 289,
"end": 470
} | class ____(BaseModel):
"""Run result."""
score: float
params: Dict[str, Any]
metadata: Dict[str, Any] = Field(default_factory=dict, description="Metadata.")
| RunResult |
python | wandb__wandb | wandb/integration/tensorflow/estimator_hook.py | {
"start": 727,
"end": 1756
} | class ____(SessionRunHook):
def __init__(self, summary_op=None, steps_per_log=1000, history=None):
self._summary_op = summary_op
self._steps_per_log = steps_per_log
self._history = history
with telemetry.context() as tel:
tel.feature.estimator_hook = True
def begin(... | WandbHook |
python | getsentry__sentry | tests/sentry/workflow_engine/endpoints/validators/actions/test_msteams.py | {
"start": 254,
"end": 2155
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.integration, self.org_integration = self.create_provider_integration_for(
provider="msteams", organization=self.organization, user=self.user, name="msteams"
)
self.valid_data = {
"type": Acti... | TestMSTeamsActionValidator |
python | mlflow__mlflow | tests/gateway/tools.py | {
"start": 4068,
"end": 4514
} | class ____(mock.Mock):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
async def __aenter__(self):
return self
async def __aexit__(self, *args):
return
def mock_http_client(mock_response: MockAsyncResponse | MockAsyncStreamingResponse):
mock_http_client... | MockHttpClient |
python | mlflow__mlflow | mlflow/pyfunc/scoring_server/client.py | {
"start": 485,
"end": 1124
} | class ____(ABC):
@abstractmethod
def wait_server_ready(self, timeout=30, scoring_server_proc=None):
"""
Wait until the scoring server is ready to accept requests.
"""
@abstractmethod
def invoke(self, data, params: dict[str, Any] | None = None):
"""
Invoke inferen... | BaseScoringServerClient |
python | kubernetes-client__python | kubernetes/client/models/v1_ingress_service_backend.py | {
"start": 383,
"end": 4426
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1IngressServiceBackend |
python | pypa__pip | src/pip/_vendor/distlib/util.py | {
"start": 33749,
"end": 36067
} | class ____(object):
"""
A very simple publish/subscribe system.
"""
def __init__(self):
self._subscribers = {}
def add(self, event, subscriber, append=True):
"""
Add a subscriber for an event.
:param event: The name of an event.
:param subscriber: The subsc... | EventMixin |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess1.py | {
"start": 2448,
"end": 2823
} | class ____:
@Decorator
async def method1(self, a: int, *, b: str) -> str: ...
def method2(self):
reveal_type(self.method1, expected_text="(a: int, *, b: str) -> Awaitable[str]")
@classmethod
def method3(cls):
reveal_type(
cls.method1,
expected_text="Decorato... | ClassF |
python | pyca__cryptography | src/cryptography/x509/ocsp.py | {
"start": 3587,
"end": 6568
} | class ____:
def __init__(
self,
request: tuple[
x509.Certificate, x509.Certificate, hashes.HashAlgorithm
]
| None = None,
request_hash: tuple[bytes, bytes, int, hashes.HashAlgorithm]
| None = None,
extensions: list[x509.Extension[x509.ExtensionType... | OCSPRequestBuilder |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/vertex_ai/experiment_service.py | {
"start": 3870,
"end": 9012
} | class ____(GoogleBaseHook):
"""Use the Vertex AI SDK for Python to create and manage your experiment runs."""
@GoogleBaseHook.fallback_to_default_project_id
def create_experiment_run(
self,
experiment_run_name: str,
experiment_name: str,
location: str,
project_id: st... | ExperimentRunHook |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc8628/endpoints/device_authorization.py | {
"start": 448,
"end": 9721
} | class ____(BaseEndpoint):
"""DeviceAuthorization endpoint - used by the client to initiate
the authorization flow by requesting a set of verification codes
from the authorization server by making an HTTP "POST" request to
the device authorization endpoint.
The client authentication requirements of ... | DeviceAuthorizationEndpoint |
python | pytest-dev__pytest-cov | src/pytest_cov/__init__.py | {
"start": 436,
"end": 547
} | class ____(PytestCovWarning):
"""
Indicates that we failed to generate a report.
"""
| CovReportWarning |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 409098,
"end": 409978
} | class ____:
@pytest.mark.parametrize("case", [ # a, b, loc, scale, m1, m2, g1, g2
(-0.01, 1.1, 0.02, 0.0001, 0.02000137427557091,
2.1112742956578063e-08, 0.05989781342460999, 20.36324408592951-3),
(2.554395574161155, 2.2482281679651965, 0, 1, -1.54215386737391,
0.7... | TestJohnsonSU |
python | getsentry__sentry | src/sentry/snuba/entity_subscription.py | {
"start": 13194,
"end": 16696
} | class ____(BaseEntitySubscription, ABC):
def __init__(
self,
aggregate: str,
time_window: int,
extra_fields: _EntitySpecificParams | None = None,
):
super().__init__(aggregate, time_window, extra_fields)
self.aggregate = aggregate
if not extra_fields or "o... | BaseMetricsEntitySubscription |
python | matplotlib__matplotlib | lib/matplotlib/backends/_backend_pdf_ps.py | {
"start": 3476,
"end": 5968
} | class ____(RendererBase):
# The following attributes must be defined by the subclasses:
# - _afm_font_dir
# - _use_afm_rc_name
def __init__(self, width, height):
super().__init__()
self.width = width
self.height = height
def flipy(self):
# docstring inherited
... | RendererPDFPSBase |
python | getsentry__sentry | src/sentry/seer/models.py | {
"start": 2490,
"end": 2703
} | class ____(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return f"Seer API response validation error: {self.message}"
| SeerApiResponseValidationError |
python | conda__conda | conda/exceptions.py | {
"start": 12687,
"end": 13050
} | class ____(CondaError):
def __init__(self, environment_name: str):
message = dals(
"""
Could not find conda environment: %(environment_name)s
You can list all discoverable environments with `conda info --envs`.
"""
)
super().__init__(message, environment_n... | EnvironmentNameNotFound |
python | apache__airflow | providers/cncf/kubernetes/tests/unit/cncf/kubernetes/operators/test_job.py | {
"start": 3803,
"end": 36307
} | class ____:
@pytest.fixture(autouse=True)
def setup_tests(self):
self._default_client_patch = patch(f"{HOOK_CLASS}._get_default_client")
self._default_client_mock = self._default_client_patch.start()
yield
patch.stopall()
def test_templates(self, create_task_instance_of_op... | TestKubernetesJobOperator |
python | matplotlib__matplotlib | lib/matplotlib/sankey.py | {
"start": 514,
"end": 36150
} | class ____:
"""
Sankey diagram.
Sankey diagrams are a specific type of flow diagram, in which
the width of the arrows is shown proportionally to the flow
quantity. They are typically used to visualize energy or
material or cost transfers between processes.
`Wikipedia (6/1/2011) <... | Sankey |
python | realpython__materials | flask-google-login/user.py | {
"start": 58,
"end": 855
} | class ____(UserMixin):
def __init__(self, id_, name, email, profile_pic):
self.id = id_
self.name = name
self.email = email
self.profile_pic = profile_pic
@staticmethod
def get(user_id):
db = get_db()
user = db.execute(
"SELECT * FROM user WHERE i... | User |
python | doocs__leetcode | solution/1600-1699/1688.Count of Matches in Tournament/Solution.py | {
"start": 0,
"end": 83
} | class ____:
def numberOfMatches(self, n: int) -> int:
return n - 1
| Solution |
python | pandas-dev__pandas | pandas/io/json/_json.py | {
"start": 43337,
"end": 45985
} | class ____(Parser):
_default_orient = "columns"
_split_keys = ("columns", "index", "data")
def _parse(self) -> DataFrame:
json = self.json
orient = self.orient
if orient == "split":
decoded = {
str(k): v
for k, v in ujson_loads(json, prec... | FrameParser |
python | kamyu104__LeetCode-Solutions | Python/shortest-path-in-a-weighted-tree.py | {
"start": 33,
"end": 535
} | class ____(object): # 0-indexed.
def __init__(self, n):
self.__bit = [0]*(n+1) # Extra one for dummy node.
def add(self, i, val):
i += 1 # Extra one for dummy node.
while i < len(self.__bit):
self.__bit[i] += val
i += (i & -i)
def query(self, i):
... | BIT |
python | fluentpython__example-code | 14-it-generator/sentence_iter.py | {
"start": 244,
"end": 525
} | class ____:
def __init__(self, text):
self.text = text
self.words = RE_WORD.findall(text)
def __repr__(self):
return 'Sentence(%s)' % reprlib.repr(self.text)
def __iter__(self): # <1>
return SentenceIterator(self.words) # <2>
| Sentence |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/cover/test_cache_implementation.py | {
"start": 1206,
"end": 1857
} | class ____(GenericCache):
def new_entry(self, key, value):
return 1
def on_access(self, key, value, score):
return score + 1
@st.composite
def write_pattern(draw, min_distinct_keys=0):
keys = draw(
st.lists(st.integers(0, 1000), unique=True, min_size=max(min_distinct_keys, 1))
... | LFUCache |
python | Textualize__textual | tests/test_on.py | {
"start": 9002,
"end": 10866
} | class ____(Widget):
class Parent(Message):
pass
class JustSomeRandomMixin:
pass
class Child(JustSomeRandomMixin, Parent):
pass
def post_parent(self) -> None:
self.post_message(self.Parent())
def post_child(self) -> None:
self.post_message(self.Child())
a... | MixinMessageSender |
python | pytorch__pytorch | test/distributed/_composable/fsdp/test_fully_shard_training.py | {
"start": 32732,
"end": 34621
} | class ____(FSDPTest):
@property
def world_size(self) -> int:
return min(8, torch.get_device_module(device_type).device_count())
@skip_if_lt_x_gpu(2)
def test_train_parity_shard_placement_fn_shard_largest_dim(self):
torch.manual_seed(42)
model_args = ModelArgs(n_layers=3, dropout... | TestFullyShardShardPlacementFnMultiProcess |
python | PyCQA__pycodestyle | testing/data/python313.py | {
"start": 146,
"end": 271
} | class ____[T, U: str = str]:
pass
def f[T: (int, str) = str](t: T) -> T:
pass
def f2[T = str](t: T) -> T:
pass
| C3 |
python | PyCQA__pylint | pylint/testutils/lint_module_test.py | {
"start": 1235,
"end": 13268
} | class ____:
maxDiff = None
def __init__(
self, test_file: FunctionalTestFile, config: Config | None = None
) -> None:
_test_reporter = FunctionalTestReporter()
self._linter = PyLinter()
self._linter.config.persistent = 0
checkers.initialize(self._linter)
# S... | LintModuleTest |
python | django__django | tests/sitemaps_tests/urls/http.py | {
"start": 2094,
"end": 2162
} | class ____(SimpleSitemap):
lastmod = date(2013, 3, 13)
| DateSiteMap |
python | crytic__slither | slither/slithir/variables/temporary.py | {
"start": 161,
"end": 873
} | class ____(Variable):
def __init__(self, node: "Node", index: Optional[int] = None) -> None:
super().__init__()
if index is None:
self._index = node.compilation_unit.counter_slithir_temporary
node.compilation_unit.counter_slithir_temporary += 1
else:
self.... | TemporaryVariable |
python | sympy__sympy | sympy/matrices/sparse.py | {
"start": 570,
"end": 14432
} | class ____(RepMatrix):
"""
A sparse matrix (a matrix with a large number of zero elements).
Examples
========
>>> from sympy import SparseMatrix, ones
>>> SparseMatrix(2, 2, range(4))
Matrix([
[0, 1],
[2, 3]])
>>> SparseMatrix(2, 2, {(1, 1): 2})
Matrix([
[0, 0],
[0,... | SparseRepMatrix |
python | django-guardian__django-guardian | guardian/testapp/tests/test_utils.py | {
"start": 4604,
"end": 5345
} | class ____(TestCase):
def test_for_instance(self):
project = Project(name="Foobar")
self.assertEqual(get_user_obj_perms_model(project), ProjectUserObjectPermission)
def test_for_class(self):
self.assertEqual(get_user_obj_perms_model(Project), ProjectUserObjectPermission)
def test_d... | GetUserObjPermsModelTest |
python | huggingface__transformers | tests/models/groupvit/test_modeling_groupvit.py | {
"start": 12463,
"end": 15733
} | class ____:
def __init__(
self,
parent,
batch_size=12,
seq_length=7,
is_training=True,
use_input_mask=True,
use_labels=True,
vocab_size=99,
hidden_size=32,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=37... | GroupViTTextModelTester |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 39749,
"end": 40512
} | class ____(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
action: Annotated[
Literal["update"], Field(description="The action to be performed on the entities.", title="Action")
]
entities: Annotated[
list[PoolBody], Field(description="A list of entities to be update... | BulkUpdateActionPoolBody |
python | dagster-io__dagster | python_modules/libraries/dagster-airlift/dagster_airlift/in_airflow/dag_proxy_operator.py | {
"start": 2407,
"end": 3771
} | class ____(BaseProxyDAGToDagsterOperator):
"""The default task proxying operator - which opens a blank session and expects the dagster URL to be set in the environment.
The dagster url is expected to be set in the environment as DAGSTER_URL.
This operator should not be instantiated directly - it is instant... | DefaultProxyDAGToDagsterOperator |
python | facelessuser__soupsieve | tests/test_level2/test_next_sibling.py | {
"start": 59,
"end": 1207
} | class ____(util.TestCase):
"""Test next sibling combinators."""
MARKUP = """
<div>
<p id="0">Some text <span id="1"> in a paragraph</span>.</p>
<a id="2" href="http://google.com">Link</a>
<span id="3">Direct child</span>
<pre>
<span id="4">Child 1</span>
<span id="5">Child 2</span>
... | TestNextSibling |
python | numba__numba | numba/cuda/cudadrv/driver.py | {
"start": 2761,
"end": 6008
} | class ____(CudaDriverError):
def __init__(self, code, msg):
self.code = code
self.msg = msg
super(CudaAPIError, self).__init__(code, msg)
def __str__(self):
return "[%s] %s" % (self.code, self.msg)
def locate_driver_and_loader():
envpath = config.CUDA_DRIVER
if envpa... | CudaAPIError |
python | spack__spack | lib/spack/spack/vendor/jinja2/nodes.py | {
"start": 18469,
"end": 18857
} | class ____(Literal):
"""A constant template string."""
fields = ("data",)
data: str
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> str:
eval_ctx = get_eval_context(self, eval_ctx)
if eval_ctx.volatile:
raise Impossible()
if eval_ctx.autoescape:
... | TemplateData |
python | ray-project__ray | python/ray/llm/_internal/serve/core/configs/openai_api_models.py | {
"start": 3947,
"end": 4077
} | class ____(vLLMTranscriptionStreamResponse):
model_config = ConfigDict(arbitrary_types_allowed=True)
| TranscriptionStreamResponse |
python | ansible__ansible | test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/action/bypass_host_loop.py | {
"start": 217,
"end": 487
} | class ____(ActionBase):
BYPASS_HOST_LOOP = True
def run(self, tmp=None, task_vars=None):
result = super(ActionModule, self).run(tmp, task_vars)
result['bypass_inventory_hostname'] = task_vars['inventory_hostname']
return result
| ActionModule |
python | huggingface__transformers | src/transformers/models/mixtral/modeling_mixtral.py | {
"start": 6511,
"end": 7238
} | class ____(nn.Module):
def __init__(self, hidden_size, eps=1e-6):
"""
MixtralRMSNorm is equivalent to T5LayerNorm
"""
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size))
self.variance_epsilon = eps
def forward(self, hidden_states):
inpu... | MixtralRMSNorm |
python | getsentry__sentry | src/sentry/workflow_engine/typings/notification_action.py | {
"start": 523,
"end": 733
} | class ____(Enum):
ALL_MEMBERS = "AllMembers"
ACTIVE_MEMBERS = "ActiveMembers"
NO_ONE = "NoOne"
# Keep existing excluded keys constant
EXCLUDED_ACTION_DATA_KEYS = ["uuid", "id"]
| FallthroughChoiceType |
python | django__django | django/contrib/postgres/indexes.py | {
"start": 4030,
"end": 5001
} | class ____(PostgresIndex):
suffix = "btree"
def __init__(self, *expressions, fillfactor=None, deduplicate_items=None, **kwargs):
self.fillfactor = fillfactor
self.deduplicate_items = deduplicate_items
super().__init__(*expressions, **kwargs)
def deconstruct(self):
path, arg... | BTreeIndex |
python | django__django | tests/filtered_relation/models.py | {
"start": 2679,
"end": 3053
} | class ____(models.Model):
rate_date = models.DateField()
from_currency = models.ForeignKey(
Currency,
models.CASCADE,
related_name="rates_from",
)
to_currency = models.ForeignKey(
Currency,
models.CASCADE,
related_name="rates_to",
)
rate = models.D... | ExchangeRate |
python | openai__openai-python | src/openai/types/shared_params/compound_filter.py | {
"start": 372,
"end": 646
} | class ____(TypedDict, total=False):
filters: Required[Iterable[Filter]]
"""Array of filters to combine.
Items can be `ComparisonFilter` or `CompoundFilter`.
"""
type: Required[Literal["and", "or"]]
"""Type of operation: `and` or `or`."""
| CompoundFilter |
python | pytorch__pytorch | test/test_python_dispatch.py | {
"start": 99178,
"end": 104319
} | class ____(TestCase):
def _test_wrapper_subclass_aliasing(self, op, args, kwargs):
def to_subclass(t: torch.Tensor):
return TwoTensor(t, t.clone())
result_ref = op(*args, **kwargs)
args_subclass = pytree.tree_map_only(torch.Tensor, to_subclass, args)
kwargs_subclass = p... | TestWrapperSubclassAliasing |
python | cython__cython | tests/run/genexpr_arg_order.py | {
"start": 2340,
"end": 4534
} | class ____:
@property
def indexer(self):
print("Getting indexer")
return IndexableClass()
@property
def function(self):
print("Getting function")
def func(a, b, c):
print("In func")
return [a, b, c]
return func
def genexp_index_order():
... | NoisyAttributeLookup |
python | ray-project__ray | python/ray/serve/_private/deployment_state.py | {
"start": 2517,
"end": 2644
} | class ____(Enum):
PENDING_ALLOCATION = 1
PENDING_INITIALIZATION = 2
SUCCEEDED = 3
FAILED = 4
| ReplicaStartupStatus |
python | django__django | tests/servers/tests.py | {
"start": 878,
"end": 1188
} | class ____(LiveServerTestCase):
available_apps = [
"servers",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
]
fixtures = ["testdata.json"]
def urlopen(self, url):
return urlopen(self.live_server_url + url)
| LiveServerBase |
python | astropy__astropy | astropy/cosmology/_src/core.py | {
"start": 2658,
"end": 2944
} | class ____(Exception):
pass
# TODO: replace with `field(converter=lambda x: None if x is None else str(x))` when
# the `converter` argument is available in `field` (py3.13, maybe?).
# See https://peps.python.org/pep-0712/
@dataclass(frozen=True, slots=True)
| CosmologyError |
python | pola-rs__polars | py-polars/src/polars/interchange/protocol.py | {
"start": 6679,
"end": 7076
} | class ____(Protocol):
"""Dataframe that supports conversion into an interchange dataframe object."""
def __dataframe__(
self,
nan_as_null: bool = False, # noqa: FBT001
allow_copy: bool = True, # noqa: FBT001
) -> SupportsInterchange:
"""Convert to a dataframe object implem... | SupportsInterchange |
python | getsentry__sentry | tests/sentry/receivers/test_onboarding.py | {
"start": 2655,
"end": 55177
} | class ____(TestCase):
@assume_test_silo_mode(SiloMode.CONTROL)
def _create_integration(self, provider: str, external_id: int = 9999):
return self.create_provider_integration(
provider=provider,
name="test",
external_id=external_id,
)
def test_existing_com... | OrganizationOnboardingTaskTest |
python | pytorch__pytorch | torch/_inductor/pattern_matcher.py | {
"start": 36500,
"end": 37588
} | class ____:
pattern: PatternExpr
extra_check: Callable[[Match], bool]
def apply(self, match: Match, graph: torch.fx.Graph, node: torch.fx.Node) -> None:
raise NotImplementedError
def register(
self,
pass_dicts: Union[_PassDictsType, Sequence[_PassDictsType]],
target: Un... | PatternEntry |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/validation.py | {
"start": 4661,
"end": 5162
} | class ____(Validator):
"""
Validator that can be switched on/off according to
a filter. (This wraps around another validator.)
"""
def __init__(self, validator: Validator, filter: FilterOrBool) -> None:
self.validator = validator
self.filter = to_filter(filter)
def validate(sel... | ConditionalValidator |
python | pydantic__pydantic | pydantic/_internal/_mock_val_ser.py | {
"start": 626,
"end": 2284
} | class ____(Mapping[str, Any]):
"""Mocker for `pydantic_core.CoreSchema` which optionally attempts to
rebuild the thing it's mocking when one of its methods is accessed and raises an error if that fails.
"""
__slots__ = '_error_message', '_code', '_attempt_rebuild', '_built_memo'
def __init__(
... | MockCoreSchema |
python | walkccc__LeetCode | solutions/3535. Unit Conversion II/3535.py | {
"start": 0,
"end": 1016
} | class ____:
def queryConversions(
self,
conversions: list[list[int]],
queries: list[list[int]]
) -> list[int]:
self.MOD = 1_000_000_007
units = self._baseUnitConversions(conversions)
# By Fermat's little theorem.
return [units[v] * self._modPow(units[u], self.MOD - 2) % self.MOD
... | Solution |
python | python-openxml__python-docx | src/docx/opc/part.py | {
"start": 550,
"end": 5711
} | class ____:
"""Base class for package parts.
Provides common properties and methods, but intended to be subclassed in client code
to implement specific part behaviors.
"""
def __init__(
self,
partname: PackURI,
content_type: str,
blob: bytes | None = None,
p... | Part |
python | bokeh__bokeh | src/bokeh/core/property/wrappers.py | {
"start": 7856,
"end": 8946
} | class ____(PropertyValueContainer, set[T]):
""" A list property value container that supports change notifications on
mutating operations.
"""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
def _saved_copy(self) -> set[T]:
return set(self)
@not... | PropertyValueSet |
python | PyCQA__pylint | doc/data/messages/i/invalid-repr-returned/good.py | {
"start": 0,
"end": 107
} | class ____:
"""__repr__ returns <type 'str'>"""
def __repr__(self):
return "apples"
| CustomRepr |
python | django__django | django/contrib/contenttypes/models.py | {
"start": 183,
"end": 5011
} | class ____(models.Manager):
use_in_migrations = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Cache shared by all the get_for_* methods to speed up
# ContentType retrieval.
self._cache = {}
def get_by_natural_key(self, app_label, model):
... | ContentTypeManager |
python | geekcomputers__Python | Calculator with simple ui.py | {
"start": 37,
"end": 1950
} | class ____:
def __init__(self):
pass
def add(self, num1, num2):
"""
This function adds two numbers.
Examples:
>>> add(2, 3)
5
>>> add(5, 9)
14
>>> add(-1, 2)
1
"""
return num1 + num2
def subtract(self, num1, n... | Calculator |
python | lepture__authlib | authlib/oidc/core/errors.py | {
"start": 1586,
"end": 2015
} | class ____(OAuth2Error):
"""The Authorization Server requires End-User consent. This error MAY be
returned when the prompt parameter value in the Authentication Request is
none, but the Authentication Request cannot be completed without
displaying a user interface for End-User consent.
http://openi... | ConsentRequiredError |
python | walkccc__LeetCode | solutions/424. Longest Repeating Character Replacement/424-2.py | {
"start": 0,
"end": 394
} | class ____:
def characterReplacement(self, s: str, k: int) -> int:
maxCount = 0
count = collections.Counter()
# l and r track the maximum window instead of the valid window.
l = 0
for r, c in enumerate(s):
count[c] += 1
maxCount = max(maxCount, count[c])
while maxCount + k < r -... | Solution |
python | huggingface__transformers | src/transformers/models/eomt/modeling_eomt.py | {
"start": 41094,
"end": 41584
} | class ____(nn.LayerNorm):
def __init__(self, num_channels, eps=1e-6, affine=True):
super().__init__(num_channels, eps=eps, elementwise_affine=affine)
def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
hidden_state = hidden_state.permute(0, 2, 3, 1)
hidden_state = F.layer_nor... | EomtLayerNorm2d |
python | huggingface__transformers | src/transformers/models/paligemma/modeling_paligemma.py | {
"start": 3579,
"end": 9756
} | class ____(nn.Module):
def __init__(self, config: PaliGemmaConfig):
super().__init__()
self.linear = nn.Linear(config.vision_config.hidden_size, config.vision_config.projection_dim, bias=True)
def forward(self, image_features):
hidden_states = self.linear(image_features)
return... | PaliGemmaMultiModalProjector |
python | getsentry__sentry | src/sentry/backup/comparators.py | {
"start": 8319,
"end": 9522
} | class ____(JSONScrubbingComparator):
"""Comparator that ensures that the specified fields' value on the right input is an ISO-8601
date that is greater than (ie, occurs after) or equal to the specified field's left input."""
def compare(self, on: InstanceID, left: Any, right: Any) -> list[ComparatorFinding... | DateUpdatedComparator |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefaultClass2.py | {
"start": 577,
"end": 805
} | class ____(dict[T1, T2]): ...
a1 = ClassA[int]()
reveal_type(a1, expected_text="ClassA[int, int]")
a2 = ClassA()
reveal_type(a2, expected_text="ClassA[str, str]")
# This should generate an error because T2 depends on T1.
| ClassA |
python | doocs__leetcode | solution/3000-3099/3081.Replace Question Marks in String to Minimize Its Value/Solution.py | {
"start": 0,
"end": 495
} | class ____:
def minimizeStringValue(self, s: str) -> str:
cnt = Counter(s)
pq = [(cnt[c], c) for c in ascii_lowercase]
heapify(pq)
t = []
for _ in range(s.count("?")):
v, c = pq[0]
t.append(c)
heapreplace(pq, (v + 1, c))
t.sort()
... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/backoff_strategies.py | {
"start": 230,
"end": 1894
} | class ____(BackoffStrategy):
def __init__(self, stream: HttpStream, **kwargs): # type: ignore # noqa
self.stream = stream
super().__init__(**kwargs)
def backoff_time(
self, response_or_exception: Optional[Union[requests.Response, requests.RequestException]], **kwargs: Any
) -> Opti... | GithubStreamABCBackoffStrategy |
python | getsentry__sentry | src/sentry/deletions/defaults/monitor_environment.py | {
"start": 181,
"end": 826
} | class ____(ModelDeletionTask[MonitorEnvironment]):
def get_child_relations(self, instance: MonitorEnvironment) -> list[BaseRelation]:
from sentry.monitors import models
return [
ModelRelation(
models.MonitorIncident,
{"monitor_environment_id": instance.id... | MonitorEnvironmentDeletionTask |
python | matplotlib__matplotlib | lib/mpl_toolkits/axes_grid1/axes_rgb.py | {
"start": 1707,
"end": 5085
} | class ____:
"""
4-panel `~.Axes.imshow` (RGB, R, G, B).
Layout::
┌───────────────┬─────┐
│ │ R │
│ ├─────┤
│ RGB │ G │
│ ├─────┤
│ │ B │
└───────────────┴─────┘
Subclasses c... | RGBAxes |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/filters/base.py | {
"start": 193,
"end": 2699
} | class ____(metaclass=ABCMeta):
"""
Base class for any filter to activate/deactivate a feature, depending on a
condition.
The return value of ``__call__`` will tell if the feature should be active.
"""
def __init__(self) -> None:
self._and_cache: dict[Filter, Filter] = {}
self._... | Filter |
python | django__django | tests/managers_regress/models.py | {
"start": 809,
"end": 1049
} | class ____(models.Model):
value = models.IntegerField()
class Meta:
abstract = True
# Custom manager
restricted = Value42()
# No custom manager on this class to make sure the default case doesn't break.
| AbstractBase2 |
python | fluentpython__example-code-2e | 05-data-classes/cards_enum.py | {
"start": 203,
"end": 381
} | class ____:
rank: Suit
suit: Rank
def __str__(self):
glyphs = [chr(x) for x in range(0x2660, 0x2664)]
return f'{self.rank} of {glyphs[self.suit-1]}'
| Card |
python | ray-project__ray | rllib/algorithms/dreamerv3/torch/models/actor_network.py | {
"start": 358,
"end": 7435
} | class ____(nn.Module):
"""The `actor` (policy net) of DreamerV3.
Consists of a simple MLP for Discrete actions and two MLPs for cont. actions (mean
and stddev).
Also contains two scalar variables to keep track of the percentile-5 and
percentile-95 values of the computed value targets within a batch... | ActorNetwork |
python | vyperlang__vyper | tests/unit/ast/test_source_annotation.py | {
"start": 1060,
"end": 6342
} | class ____(Exception):
def __init__(self, message='Error Message not found.', item=None):
self.message = message
self.lineno = None
self.col_offset = None
if isinstance(item, tuple): # is a position.
self.lineno, self.col_offset = item
elif item and hasattr(item... | ParserException |
python | pdm-project__pdm | src/pdm/cli/commands/venv/backends.py | {
"start": 469,
"end": 4885
} | class ____(abc.ABC):
"""The base class for virtualenv backends"""
def __init__(self, project: Project, python: str | None) -> None:
self.project = project
self.python = python
@abc.abstractmethod
def pip_args(self, with_pip: bool) -> Iterable[str]:
pass
@cached_property
... | Backend |
python | Pylons__pyramid | tests/test_integration.py | {
"start": 20490,
"end": 21202
} | class ____(IntegrationBase, unittest.TestCase):
package = 'tests.pkgs.securityapp'
def test_public(self):
res = self.testapp.get('/public', status=200)
self.assertEqual(res.body, b'Hello')
def test_private_denied(self):
self.testapp.get('/private', status=403)
def test_private... | TestSecurityApp |
python | getsentry__sentry | tests/sentry/deletions/test_data_source.py | {
"start": 305,
"end": 1081
} | class ____(BaseWorkflowTest, HybridCloudTestMixin):
def setUp(self) -> None:
self.alert_rule = self.create_alert_rule()
self.snuba_query = self.alert_rule.snuba_query
self.subscription = QuerySubscription.objects.get(snuba_query_id=self.snuba_query.id)
self.data_source = self.create_... | DeleteDataSourceTest |
python | tensorflow__tensorflow | tensorflow/python/ops/lookup_ops.py | {
"start": 34148,
"end": 34730
} | class ____(collections.namedtuple("HasherSpec", ["hasher", "key"])):
"""A structure for the spec of the hashing function to use for hash buckets.
`hasher` is the name of the hashing function to use (eg. "fasthash",
"stronghash").
`key` is optional and specify the key to use for the hash function if
supported... | HasherSpec |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 19723,
"end": 20551
} | class ____(ChainedSource):
is_int: bool
def __post_init__(self) -> None:
assert self.base is not None
def reconstruct(self, codegen: "PyCodegen") -> None:
# Integer casting at reconstruction helps reduce the amount of DynamicInts returned
# to the user, in favor of plain ints.
... | DynamicScalarSource |
python | Netflix__metaflow | metaflow/packaging_sys/tar_backend.py | {
"start": 130,
"end": 3010
} | class ____(PackagingBackend):
type = "tgz"
@classmethod
def get_extract_commands(cls, archive_name: str, dest_dir: str) -> List[str]:
return [
f"TAR_OPTIONS='--warning=no-timestamp' tar -xzf {archive_name} -C {dest_dir}"
]
def __init__(self):
super().__init__()
... | TarPackagingBackend |
python | catalyst-team__catalyst | catalyst/contrib/datasets/cifar.py | {
"start": 10181,
"end": 12825
} | class ____(QueryGalleryDataset):
"""
CIFAR10 for metric learning with query and gallery split.
CIFAR10QGDataset should be used for test stage.
For this dataset we used only test part of the CIFAR10 and only
those images that are labeled as 'dog', 'frog', 'horse', 'ship', 'truck'.
"""
_split... | CifarQGDataset |
python | spack__spack | lib/spack/spack/test/installer_tui.py | {
"start": 2807,
"end": 6215
} | class ____:
"""Test basic state management operations"""
def test_add_build(self):
"""Test that add_build adds builds correctly"""
status, _, _ = create_build_status(total=2)
spec1 = MockSpec("pkg1", "1.0")
spec2 = MockSpec("pkg2", "2.0")
status.add_build(spec1, explici... | TestBasicStateManagement |
python | getsentry__sentry | src/sentry/notifications/notifications/activity/escalating.py | {
"start": 236,
"end": 1550
} | class ____(GroupActivityNotification):
message_builder = "SlackNotificationsMessageBuilder"
metrics_key = "escalating_activity"
title = "Issue marked as escalating"
def get_notification_title(
self, provider: ExternalProviders, context: Mapping[str, Any] | None = None
) -> str:
ret... | EscalatingActivityNotification |
python | scipy__scipy | scipy/stats/_multivariate.py | {
"start": 181438,
"end": 185168
} | class ____(multi_rv_frozen):
__class_getitem__ = None
def __init__(self, loc=None, shape=1, df=1, allow_singular=False,
seed=None):
"""Create a frozen multivariate t distribution.
Parameters
----------
%(_mvt_doc_default_callparams)s
Examples
-... | multivariate_t_frozen |
python | google__jax | jax/_src/interpreters/mlir.py | {
"start": 22567,
"end": 24066
} | class ____:
# The names of the dimension variables, sorted by name. This is the order in
# which they are passed to the IR functions that need them. This is only
# used for native serialization with polymorphic shapes when
# --jax_dynamic_shapes is off.
# TODO: for multi-platform lowering we prepend to the re... | ShapePolyLoweringState |
python | chroma-core__chroma | chromadb/test/test_api.py | {
"start": 85948,
"end": 89709
} | class ____:
"""Test Search class dict input support."""
def test_search_with_dict_where(self):
"""Test Search accepts dict for where parameter."""
from chromadb.execution.expression.plan import Search
from chromadb.execution.expression.operator import Where
# Simple equality
... | TestSearchDictSupport |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingTypeEquals1.py | {
"start": 1034,
"end": 1178
} | class ____:
pass
E = C[T] | D
def func5(x: E[T]) -> None:
if type(x) == C:
reveal_type(x, expected_text="C[T@func5]")
@final
| D |
python | sqlalchemy__sqlalchemy | test/sql/test_type_expressions.py | {
"start": 16424,
"end": 17036
} | class ____(fixtures.TablesTest, RoundTripTestBase):
@classmethod
def define_tables(cls, metadata):
class MyString(UserDefinedType):
cache_ok = True
def get_col_spec(self, **kw):
return "VARCHAR(50)"
def bind_expression(self, bindvalue):
... | UserDefinedTypeRoundTripTest |
python | python-openxml__python-docx | src/docx/opc/phys_pkg.py | {
"start": 1075,
"end": 2318
} | class ____(PhysPkgReader):
"""Implements |PhysPkgReader| interface for an OPC package extracted into a
directory."""
def __init__(self, path):
"""`path` is the path to a directory containing an expanded package."""
super(_DirPkgReader, self).__init__()
self._path = os.path.abspath(p... | _DirPkgReader |
python | dagster-io__dagster | python_modules/libraries/dagster-omni/dagster_omni/translation.py | {
"start": 2108,
"end": 4344
} | class ____:
"""Container class for data required to translate an object in an
Omni workspace into a Dagster definition.
Properties:
obj (Union[OmniDocument, OmniQuery]): The object to translate.
workspace_data (OmniWorkspaceData): Global workspace data.
"""
obj: Union[OmniDocument,... | OmniTranslatorData |
python | python-attrs__attrs | typing-examples/mypy.py | {
"start": 687,
"end": 736
} | class ____:
z: Any = attr.ib()
@attrs.define
| FF |
python | getsentry__sentry | tests/sentry/users/api/endpoints/test_userroles_index.py | {
"start": 1168,
"end": 1494
} | class ____(UserRolesTest):
def test_simple(self) -> None:
UserRole.objects.create(name="test-role")
resp = self.get_response()
assert resp.status_code == 200
assert len(resp.data) >= 1, resp.data
assert "test-role" in [r["name"] for r in resp.data]
@control_silo_test
| UserRolesGetTest |
python | apache__airflow | providers/common/compat/tests/unit/common/compat/lineage/test_hook.py | {
"start": 22637,
"end": 39563
} | class ____:
"""Test edge cases and error conditions to ensure collector never fails."""
@pytest.mark.parametrize("uri", ["", None])
def test_invalid_uri_none(self, collector, uri):
"""Test handling of None URI - should not raise."""
mock_context = mock.MagicMock()
# Should not rais... | TestEdgeCases |
python | scipy__scipy | scipy/stats/tests/test_distributions.py | {
"start": 362029,
"end": 366743
} | class ____:
# Construct a distribution w/ explicit shapes parameter and test it.
def test_correct_shapes(self):
dummy_distr = _distr_gen(name='dummy', shapes='a')
assert_equal(dummy_distr.pdf(1, a=1), 42)
def test_wrong_shapes_1(self):
dummy_distr = _distr_gen(name='dummy', shapes=... | TestSubclassingExplicitShapes |
python | nedbat__coveragepy | coverage/config.py | {
"start": 803,
"end": 5568
} | class ____(configparser.ConfigParser):
"""Our specialization of ConfigParser."""
def __init__(self, our_file: bool) -> None:
"""Create the HandyConfigParser.
`our_file` is True if this config file is specifically for coverage,
False if we are examining another config file (tox.ini, set... | HandyConfigParser |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.