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 | scikit-learn__scikit-learn | sklearn/base.py | {
"start": 40992,
"end": 42057
} | class ____:
"""Mixin class for all meta estimators in scikit-learn.
This mixin is empty, and only exists to indicate that the estimator is a
meta-estimator.
.. versionchanged:: 1.6
The `_required_parameters` is now removed and is unnecessary since tests are
refactored and don't use thi... | MetaEstimatorMixin |
python | dask__dask | dask/dataframe/dask_expr/_expr.py | {
"start": 51896,
"end": 52057
} | class ____(Elemwise):
_projection_passthrough = True
_parameters = ["frame", "cond", "other"]
_defaults = {"other": np.nan}
operation = M.mask
| Mask |
python | pydantic__pydantic | pydantic-core/tests/benchmarks/test_micro_benchmarks.py | {
"start": 18159,
"end": 20499
} | class ____:
@pytest.fixture(scope='class')
def core_validator(self):
class CoreModel:
__slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__'
return SchemaValidator(
schema=core_schema.model_schema(
cls=CoreModel,
... | TestBenchmarkDateTime |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/descriptors.py | {
"start": 26398,
"end": 26535
} | class ____(AOTOutput):
idx: int
def expr(self) -> str:
return f"__saved_for_backwards_{self.idx}"
| SavedForBackwardsAOTOutput |
python | great-expectations__great_expectations | contrib/experimental/great_expectations_experimental/expectations/expect_column_kurtosis_to_be_between.py | {
"start": 560,
"end": 3242
} | class ____(ColumnAggregateMetricProvider):
"""MetricProvider Class for Aggregate Mean MetricProvider"""
metric_name = "column.custom.kurtosis"
@column_aggregate_value(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return stats.kurtosis(column)
# @metric_value(engine=Sql... | ColumnKurtosis |
python | getsentry__sentry | src/sentry/api/authentication.py | {
"start": 15465,
"end": 21603
} | class ____(StandardAuthentication):
token_name = b"bearer"
def _find_or_update_token_by_hash(self, token_str: str) -> ApiToken | ApiTokenReplica:
"""
Find token by hash or update token's hash value if only found via plaintext.
1. Hash provided plaintext token.
2. Perform lookup... | UserAuthTokenAuthentication |
python | huggingface__transformers | src/transformers/models/auto/modeling_auto.py | {
"start": 90523,
"end": 90773
} | class ____(_BaseAutoModelClass):
_model_mapping = MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING
AutoModelForSpeechSeq2Seq = auto_class_update(
AutoModelForSpeechSeq2Seq, head_doc="sequence-to-sequence speech-to-text modeling"
)
| AutoModelForSpeechSeq2Seq |
python | openai__openai-python | src/openai/resources/realtime/realtime.py | {
"start": 8062,
"end": 8525
} | class ____:
def __init__(self, realtime: AsyncRealtime) -> None:
self._realtime = realtime
@cached_property
def client_secrets(self) -> AsyncClientSecretsWithStreamingResponse:
return AsyncClientSecretsWithStreamingResponse(self._realtime.client_secrets)
@cached_property
def calls(... | AsyncRealtimeWithStreamingResponse |
python | doocs__leetcode | solution/3700-3799/3708.Longest Fibonacci Subarray/Solution.py | {
"start": 0,
"end": 315
} | class ____:
def longestSubarray(self, nums: List[int]) -> int:
n = len(nums)
ans = f = 2
for i in range(2, n):
if nums[i] == nums[i - 1] + nums[i - 2]:
f = f + 1
ans = max(ans, f)
else:
f = 2
return ans
| Solution |
python | euske__pdfminer | pdfminer/layout.py | {
"start": 5107,
"end": 5276
} | class ____(LTItem, LTText):
def __init__(self, text):
self._text = text
return
def get_text(self):
return self._text
## LTChar
##
| LTAnno |
python | ray-project__ray | python/ray/dag/tests/experimental/test_torch_tensor_dag.py | {
"start": 1088,
"end": 3948
} | class ____:
def __init__(self):
self.device = AcceleratorContext.get().get_accelerator_devices()[0]
def init_distributed(self, world_size, rank):
torch.distributed.init_process_group(
backend="nccl", world_size=world_size, rank=rank
)
def send(self, shape, dtype, value:... | TorchTensorWorker |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeNarrowingLiteralMember1.py | {
"start": 3688,
"end": 3963
} | class ____:
event: None | Literal["e"]
def func2(e: XD | XE) -> None:
if e.event == None:
reveal_type(e, expected_text="XE")
if e.event == "e":
reveal_type(e, expected_text="XE")
if e.event == "d":
reveal_type(e, expected_text="XD")
| XE |
python | huggingface__transformers | src/transformers/quantizers/quantizer_spqr.py | {
"start": 1039,
"end": 3090
} | class ____(HfQuantizer):
"""
Quantizer of the SpQR method. Enables the loading of prequantized models.
"""
requires_calibration = True
def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
super().__init__(quantization_config, **kwargs)
self.quantization_confi... | SpQRHfQuantizer |
python | pydata__xarray | xarray/core/groupby.py | {
"start": 54188,
"end": 62540
} | class ____(GroupBy["DataArray"], DataArrayGroupbyArithmetic):
"""GroupBy object specialized to grouping DataArray objects"""
__slots__ = ()
_dims: tuple[Hashable, ...] | None
@property
def dims(self) -> tuple[Hashable, ...]:
self._raise_if_by_is_chunked()
if self._dims is None:
... | DataArrayGroupByBase |
python | yaml__pyyaml | lib/yaml/cyaml.py | {
"start": 1096,
"end": 1283
} | class ____(CParser, Constructor, Resolver):
def __init__(self, stream):
CParser.__init__(self, stream)
Constructor.__init__(self)
Resolver.__init__(self)
| CLoader |
python | huggingface__transformers | src/transformers/models/sam2/configuration_sam2.py | {
"start": 13323,
"end": 16618
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Sam2MaskDecoder`]. It is used to instantiate a SAM2
memory encoder according to the specified arguments, defining the model architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can ... | Sam2MaskDecoderConfig |
python | pypa__hatch | tests/cli/status/test_status.py | {
"start": 3047,
"end": 5517
} | class ____:
def test_no_project(self, hatch, isolation, config_file, helpers):
config_file.model.mode = "project"
config_file.save()
result = hatch("status")
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
f"""
Mod... | TestModeProject |
python | getsentry__sentry | tests/sentry/replays/consumers/test_recording.py | {
"start": 1040,
"end": 10406
} | class ____(TransactionTestCase):
replay_id = uuid.uuid4().hex
replay_recording_id = uuid.uuid4().hex
force_synchronous = True
def get_recording_data(self, segment_id: int) -> memoryview:
result = storage_kv.get(
_make_recording_filename(
project_id=self.project.id,
... | RecordingTestCase |
python | django__django | django/views/generic/dates.py | {
"start": 9613,
"end": 12852
} | class ____(MultipleObjectMixin, DateMixin, View):
"""
Base class for date-based views displaying a list of objects.
This requires subclassing to provide a response mixin.
"""
allow_empty = False
date_list_period = "year"
def get(self, request, *args, **kwargs):
self.date_list, sel... | BaseDateListView |
python | Textualize__rich | examples/log.py | {
"start": 198,
"end": 1943
} | class ____(RegexHighlighter):
base_style = "req."
highlights = [
r"^(?P<protocol>\w+) (?P<method>\w+) (?P<path>\S+) (?P<result>\w+) (?P<stats>\[.+\])$",
r"\/(?P<filename>\w+\..{3,4})",
]
theme = Theme(
{
"req.protocol": Style.parse("dim bold green"),
"req.method": Style... | RequestHighlighter |
python | django__django | django/core/management/base.py | {
"start": 569,
"end": 1222
} | class ____(Exception):
"""
Exception class indicating a problem while executing a management
command.
If this exception is raised during the execution of a management
command, it will be caught and turned into a nicely-printed error
message to the appropriate output stream (i.e., stderr); as a
... | CommandError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictClosed5.py | {
"start": 127,
"end": 192
} | class ____(TypedDict, extra_items=str):
name: str
| MovieExtraStr |
python | PrefectHQ__prefect | tests/server/models/test_block_documents.py | {
"start": 25820,
"end": 34385
} | class ____:
@pytest.fixture(autouse=True)
async def block_documents(self, session, block_schemas):
block_documents = []
block_documents.append(
await models.block_documents.create_block_document(
session=session,
block_document=schemas.actions.BlockDoc... | TestReadBlockDocuments |
python | pytorch__pytorch | test/lazy/test_functionalization.py | {
"start": 278,
"end": 2936
} | class ____(TestCase):
def test_lazy_init_with_view(self):
def f(device, reset_storage=False):
torch.manual_seed(2023)
if device == "lazy":
metrics.reset()
class Model(torch.nn.Module):
def __init__(self) -> None:
super... | LazyFuncionalizationTest |
python | django__django | tests/backends/tests.py | {
"start": 10030,
"end": 10806
} | class ____(TransactionTestCase):
available_apps = []
# Unfortunately with sqlite3 the in-memory test database cannot be closed,
# and so it cannot be re-opened during testing.
@skipUnlessDBFeature("test_db_allows_multiple_connections")
def test_signal(self):
data = {}
def receiver(... | ConnectionCreatedSignalTest |
python | networkx__networkx | networkx/algorithms/isomorphism/tests/test_vf2pp_helpers.py | {
"start": 27201,
"end": 46638
} | class ____:
def test_const_covered_neighbors(self):
G1 = nx.Graph([(0, 1), (1, 2), (3, 0), (3, 2)])
G2 = nx.Graph([("a", "b"), ("b", "c"), ("k", "a"), ("k", "c")])
gparams = _GraphParameters(G1, G2, None, None, None, None, None)
sparams = _StateParameters(
{0: "a", 1: "b"... | TestGraphISOFeasibility |
python | apache__airflow | task-sdk/tests/task_sdk/definitions/test_dag.py | {
"start": 19899,
"end": 24145
} | class ____:
DEFAULT_ARGS = {
"owner": "test",
"depends_on_past": True,
"start_date": datetime.now(tz=timezone.utc),
"retries": 1,
"retry_delay": timedelta(minutes=1),
}
VALUE = 42
def test_dag_decorator_without_args(self):
"""Test that @dag can be used wi... | TestDagDecorator |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1476406,
"end": 1477232
} | class ____(sgqlc.types.Type, Node):
"""Represents an 'review_requested' event on a given pull request."""
__schema__ = github_schema
__field_names__ = ("actor", "created_at", "pull_request", "requested_reviewer")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
"""Identifies the actor who per... | ReviewRequestedEvent |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1119492,
"end": 1120131
} | class ____(sgqlc.types.Type, Node):
"""Represents a 'converted_to_discussion' event on a given issue."""
__schema__ = github_schema
__field_names__ = ("actor", "created_at", "discussion")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
"""Identifies the actor who performed the event."""
... | ConvertedToDiscussionEvent |
python | scipy__scipy | scipy/special/tests/test_basic.py | {
"start": 178888,
"end": 179521
} | class ____:
def test_round(self):
rnd = list(map(int, (special.round(10.1),
special.round(10.4),
special.round(10.5),
special.round(10.6))))
# Note: According to the documentation, scipy.special.round is
... | TestRound |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_snippets.py | {
"start": 30864,
"end": 31841
} | class ____(util.MdCase):
"""Test snippet URL cases with missing URL and 'check paths'."""
extension = [
'pymdownx.snippets',
]
extension_configs = {
'pymdownx.snippets': {
'base_path': [os.path.join(BASE, '_snippets')],
'url_download': True,
'url_max... | TestURLSnippetsMissing |
python | ray-project__ray | python/ray/data/_internal/execution/interfaces/op_runtime_metrics.py | {
"start": 7175,
"end": 37561
} | class ____(metaclass=OpRuntimesMetricsMeta):
"""Runtime metrics for a 'PhysicalOperator'.
Metrics are updated dynamically during the execution of the Dataset.
This class can be used for either observablity or scheduling purposes.
DO NOT modify the fields of this class directly. Instead, use the provid... | OpRuntimeMetrics |
python | sphinx-doc__sphinx | sphinx/util/cfamily.py | {
"start": 8647,
"end": 16786
} | class ____:
def __init__(
self,
definition: str,
*,
location: nodes.Node | tuple[str, int] | str,
config: Config,
) -> None:
self.definition = definition.strip()
self.location = location # for warnings
self.config = config
self.pos = 0
... | BaseParser |
python | Textualize__textual | docs/examples/guide/compound/byte02.py | {
"start": 1688,
"end": 2421
} | class ____(Widget):
DEFAULT_CSS = """
ByteEditor > Container {
height: 1fr;
align: center middle;
}
ByteEditor > Container.top {
background: $boost;
}
ByteEditor Input {
width: 16;
}
"""
def compose(self) -> ComposeResult:
with Container(class... | ByteEditor |
python | pypa__pipenv | pipenv/vendor/pipdeptree/_models/package.py | {
"start": 542,
"end": 737
} | class ____(ValueError):
"""
An invalid requirement string was found.
When raising an exception, this should provide just the problem requirement string.
"""
| InvalidRequirementError |
python | getsentry__sentry | tests/sentry/core/endpoints/test_team_details.py | {
"start": 2606,
"end": 7939
} | class ____(TeamDetailsTestBase):
method = "put"
def test_simple(self) -> None:
team = self.team # force creation
self.get_success_response(
team.organization.slug, team.slug, name="hello world", slug="foobar"
)
team = Team.objects.get(id=team.id)
assert te... | TeamUpdateTest |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_multicolumn_sum_to_equal.py | {
"start": 2299,
"end": 14594
} | class ____(MulticolumnMapExpectation):
__doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION}
ExpectMulticolumnSumToEqual is a \
Multicolumn Map Expectation.
Multicolumn Map Expectations are evaluated for a set of columns and ask a yes/no question about the row-wise relationship between those columns.
Base... | ExpectMulticolumnSumToEqual |
python | kamyu104__LeetCode-Solutions | Python/maximum-tastiness-of-candy-basket.py | {
"start": 84,
"end": 865
} | class ____(object):
def maximumTastiness(self, price, k):
"""
:type price: List[int]
:type k: int
:rtype: int
"""
def check(x): # max cnt if smallest absolute difference >= x
cnt = prev = 0
for i in xrange(len(price)):
if prev ... | Solution |
python | pytorch__pytorch | torch/_utils.py | {
"start": 37790,
"end": 40858
} | class ____(Generic[P]):
def __init__(self, name: str):
self.name = name
self.callback_list: list[Callable[P, None]] = []
def add_callback(self, cb: Callable[P, None]) -> None:
self.callback_list.append(cb)
def fire_callbacks(self, *args: P.args, **kwargs: P.kwargs) -> None:
... | CallbackRegistry |
python | PyCQA__pylint | tests/functional/r/regression/regression_3091.py | {
"start": 102,
"end": 239
} | class ____():
fun = lambda self, x: x * 2
def __init__(self):
x = self.fun(1) # Crashes pylint 2.3.1
print(x)
| MyClass |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/kubernetes_engine.py | {
"start": 2388,
"end": 2603
} | class ____(BaseGoogleLink):
"""Helper class for constructing Kubernetes Engine Pod Link."""
name = "Kubernetes Pod"
key = "kubernetes_pod_conf"
format_str = KUBERNETES_POD_LINK
| KubernetesEnginePodLink |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-monday/unit_tests/integrations/monday_requests/items_request_builder.py | {
"start": 209,
"end": 1288
} | class ____(MondayBaseRequestBuilder):
@classmethod
def items_endpoint(cls, authenticator: Authenticator, board_ids: List[int] = None) -> "ItemsRequestBuilder":
return cls().with_authenticator(authenticator).with_board_ids(board_ids)
@property
def request_body(self):
params = super().que... | ItemsRequestBuilder |
python | kamyu104__LeetCode-Solutions | Python/move-sub-tree-of-n-ary-tree.py | {
"start": 251,
"end": 1880
} | class ____(object):
def moveSubTree(self, root, p, q):
"""
:type root: Node
:type p: Node
:type q: Node
:rtype: Node
"""
def iter_find_parents(node, parent, p, q, is_ancestor, lookup):
stk = [(1, [node, None, False])]
while stk:
... | Solution |
python | PrefectHQ__prefect | src/prefect/server/schemas/core.py | {
"start": 12328,
"end": 12597
} | class ____(PrefectBaseModel):
"""
Base class for classes that represent inputs to runs, which
could include, constants, parameters, task runs or flow runs.
"""
model_config: ClassVar[ConfigDict] = ConfigDict(frozen=True)
input_type: str
| RunInput |
python | ray-project__ray | python/ray/serve/_private/benchmarks/streaming/streaming_http_throughput.py | {
"start": 756,
"end": 3701
} | class ____:
def __init__(self, downstream: DeploymentHandle):
logging.getLogger("ray.serve").setLevel(logging.WARNING)
self._h = downstream.options(stream=True)
async def stream(self):
async for token in self._h.stream.remote():
yield token
def __call__(self, *args):
... | Intermediate |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 62810,
"end": 63346
} | class ____(_VectorIndexConfig):
cleanup_interval_seconds: int
distance_metric: VectorDistances
dynamic_ef_min: int
dynamic_ef_max: int
dynamic_ef_factor: int
ef: int
ef_construction: int
filter_strategy: VectorFilterStrategy
flat_search_cutoff: int
max_connections: int
skip: ... | _VectorIndexConfigHNSW |
python | django__django | tests/migrations/test_state.py | {
"start": 60511,
"end": 70904
} | class ____(SimpleTestCase):
def test_custom_model_base(self):
state = ModelState.from_model(ModelWithCustomBase)
self.assertEqual(state.bases, (models.Model,))
def test_bound_field_sanity_check(self):
field = models.CharField(max_length=1)
field.model = models.Model
with... | ModelStateTests |
python | pandas-dev__pandas | asv_bench/benchmarks/sparse.py | {
"start": 484,
"end": 921
} | class ____:
def setup(self):
K = 50
N = 50001
rng = date_range("1/1/2000", periods=N, freq="min")
self.series = {}
for i in range(1, K):
data = np.random.randn(N)[:-i]
idx = rng[:-i]
data[100:] = np.nan
self.series[i] = Series(S... | SparseSeriesToFrame |
python | viewflow__viewflow | viewflow/workflow/flow/views/detail.py | {
"start": 1387,
"end": 1803
} | class ____(mixins.TaskViewTemplateNames, generic.TemplateView):
"""
Default detail view for the flow task.
Get confirmation from user, assigns task and redirects to task pages.
"""
template_filename = "task_detail.html"
def get_actions(self):
activation = self.request.activation
... | DetailTaskView |
python | doocs__leetcode | solution/3100-3199/3122.Minimum Number of Operations to Satisfy Conditions/Solution.py | {
"start": 0,
"end": 615
} | class ____:
def minimumOperations(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
f = [[inf] * 10 for _ in range(n)]
for i in range(n):
cnt = [0] * 10
for j in range(m):
cnt[grid[j][i]] += 1
if i == 0:
fo... | Solution |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/quantization/stablehlo/python/integration_test/quantize_model_test.py | {
"start": 2180,
"end": 36945
} | class ____(quantize_model_test_base.QuantizedModelTest):
@parameterized.parameters(
testing.parameter_combinations([{
'bias_fn': (
None,
nn_ops.bias_add,
),
'activation_fn': (
None,
nn_ops.relu,
nn_ops.relu6,
... | StaticRangeQuantizationTest |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_us_zipcode_within_mile_radius_of_given_zipcode.py | {
"start": 1153,
"end": 3253
} | class ____(ColumnMapMetricProvider):
"""
Determines whether a US zip code is within a the given radius in miles of another given zip code.
requirements: uszipcode
"""
# This is the id string that will be used to reference your metric.
# Please see {some doc} for information on how to choose an ... | ColumnValuesAreUSZipcodeWithinMileRadiusOfGivenZipcode |
python | redis__redis-py | tests/test_connection_pool.py | {
"start": 15172,
"end": 16083
} | class ____:
def test_extra_typed_querystring_options(self):
pool = redis.BlockingConnectionPool.from_url(
"redis://localhost/2?socket_timeout=20&socket_connect_timeout=10"
"&socket_keepalive=&retry_on_timeout=Yes&max_connections=10&timeout=42"
)
assert pool.connectio... | TestBlockingConnectionPoolURLParsing |
python | pytorch__pytorch | torch/_dynamo/source.py | {
"start": 20551,
"end": 20963
} | class ____(ChainedSource):
def __post_init__(self) -> None:
assert self.base is not None
def reconstruct(self, codegen: "PyCodegen") -> None:
codegen(self.base)
def guard_source(self) -> GuardSource:
return self.base.guard_source()
def name(self) -> str:
return f"{self... | FlattenScriptObjectSource |
python | tox-dev__tox | src/tox/tox_env/python/virtual_env/package/pyproject.py | {
"start": 17506,
"end": 21532
} | class ____(Frontend):
def __init__(self, root: Path, env: Pep517VenvPackager) -> None:
super().__init__(*Frontend.create_args_from_folder(root))
self._tox_env = env
self._backend_executor_: LocalSubProcessPep517Executor | None = None
into: dict[str, Any] = {}
for hook in cha... | Pep517VirtualEnvFrontend |
python | openai__openai-python | src/openai/types/fine_tuning/checkpoints/permission_create_params.py | {
"start": 252,
"end": 407
} | class ____(TypedDict, total=False):
project_ids: Required[SequenceNotStr[str]]
"""The project identifiers to grant access to."""
| PermissionCreateParams |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/properties.py | {
"start": 3723,
"end": 4071
} | class ____:
def __init__(self, z: str) -> None:
self.z = z
@property
def attribute(self) -> PropertyCallableReturn:
_test_sink(self.z)
return PropertyCallableReturn(_test_source())
def test_property_callable():
obj = PropertyCallable(_test_source())
return obj.attribute(_t... | PropertyCallable |
python | django__django | django/db/models/functions/math.py | {
"start": 2875,
"end": 2950
} | class ____(Transform):
function = "FLOOR"
lookup_name = "floor"
| Floor |
python | h5py__h5py | h5py/tests/test_attrs.py | {
"start": 856,
"end": 1204
} | class ____(TestCase):
""" Feature: AttributeManager provide a helpful
__repr__ string
"""
def test_repr(self):
grp = self.f.create_group(make_name())
grp.attrs.create('att', 1)
self.assertIsInstance(repr(grp.attrs), str)
grp.id.close()
self.assertIsInstance(... | TestRepr |
python | huggingface__transformers | src/transformers/models/dia/modeling_dia.py | {
"start": 2641,
"end": 3937
} | class ____(nn.Module):
"""In order to efficiently compute the audio embedding from the 9 different channels,
we vectorize the embedding process by using a single embedding layer and an offset.
Example:
- num_embeds = 4
- vocab_size = 8
- num_channels = 3
We would have offsets = [0, 8, 16]
... | DiaMultiChannelEmbedding |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/eveonline/tests.py | {
"start": 246,
"end": 799
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = EveOnlineProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""
{
"CharacterID": 273042051,
"CharacterName": "CCP illurkall",
"ExpiresOn": "2014-05-23T... | EveOnlineTests |
python | huggingface__transformers | src/transformers/models/sew_d/modeling_sew_d.py | {
"start": 20594,
"end": 22194
} | class ____(torch.autograd.Function):
"""Optimized dropout function to save computation and memory by using mask operation instead of multiplication."""
@staticmethod
def forward(ctx, input, local_ctx):
mask, dropout = get_mask(input, local_ctx)
ctx.scale = 1.0 / (1 - dropout)
if dro... | XDropout |
python | google__pytype | pytype/rewrite/load_abstract.py | {
"start": 188,
"end": 1434
} | class ____:
"""Store of constants and singletons.
Constants should be accessed via self[<raw value>], which creates the constant
if it does not exist. Under the hood, constants are stored in self._consts.
Singletons are stored in self.singles and should be accessed via
self.singles[<name>]. For convenience,... | Constants |
python | joke2k__faker | faker/providers/color/es_CL/__init__.py | {
"start": 63,
"end": 103
} | class ____(ColorProvider):
pass
| Provider |
python | sympy__sympy | sympy/logic/algorithms/lra_theory.py | {
"start": 27955,
"end": 30115
} | class ____:
"""
Represents an upper or lower bound or an equality between a symbol
and some constant.
"""
def __init__(self, var, const, upper, equality, strict=None):
if not equality in [True, False]:
assert equality in [True, False]
self.var = var
if isinstanc... | Boundary |
python | pytorch__pytorch | test/higher_order_ops/test_invoke_subgraph.py | {
"start": 64254,
"end": 70641
} | class ____(torch.nn.Module):
def forward(self, getitem_6: "f32[8, 8]", getitem_5: "f32[8, 8]", getitem_4: "f32[8, 8]", cos: "f32[8, 8]", tangents_1: "f32[8, 8]"):
mul: "f32[8, 8]" = torch.ops.aten.mul.Tensor(tangents_1, cos); tangents_1 = cos = None
partitioned_bw_subgraph_0_0 = self.partitioned_b... | GraphModule |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_vertex_ai.py | {
"start": 37088,
"end": 48943
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("custom_job.Dataset"))
@mock.patch(VERTEX_AI_PATH.format("custom_job.CustomJobHook"))
def test_execute(self, mock_hook, mock_dataset):
mock_hook.return_value.create_custom_training_job.return_value = (
None,
"training_id",
... | TestVertexAICreateCustomTrainingJobOperator |
python | sphinx-doc__sphinx | sphinx/builders/latex/transforms.py | {
"start": 15455,
"end": 16475
} | class ____(SphinxPostTransform):
"""Gather bibliography entries to tail of document.
Before::
<document>
<paragraph>
blah blah blah
<citation>
...
<paragraph>
blah blah blah
<citation>
...
... | BibliographyTransform |
python | facebookresearch__faiss | tests/test_contrib.py | {
"start": 2898,
"end": 5635
} | class ____(unittest.TestCase):
def test_knn_cpu(self):
xb = np.random.rand(200, 32).astype('float32')
xq = np.random.rand(100, 32).astype('float32')
index = faiss.IndexFlatL2(32)
index.add(xb)
Dref, Iref = index.search(xq, 10)
Dnew, Inew = knn(xq, xb, 10)
... | TestExhaustiveSearch |
python | huggingface__transformers | src/transformers/models/qwen3_next/modular_qwen3_next.py | {
"start": 38135,
"end": 38424
} | class ____(LlamaForQuestionAnswering):
pass
__all__ = [
"Qwen3NextForCausalLM",
"Qwen3NextForQuestionAnswering",
"Qwen3NextModel",
"Qwen3NextPreTrainedModel",
"Qwen3NextForSequenceClassification",
"Qwen3NextForTokenClassification",
]
| Qwen3NextForQuestionAnswering |
python | python-markdown__markdown | markdown/extensions/md_in_html.py | {
"start": 19056,
"end": 19785
} | class ____(Extension):
"""Add Markdown parsing in HTML to Markdown class."""
def extendMarkdown(self, md):
""" Register extension instances. """
# Replace raw HTML preprocessor
md.preprocessors.register(HtmlBlockPreprocessor(md), 'html_block', 20)
# Add `blockprocessor` which h... | MarkdownInHtmlExtension |
python | astropy__astropy | astropy/cosmology/_src/tests/io/test_json.py | {
"start": 2755,
"end": 5607
} | class ____(ReadWriteTestMixinBase):
"""
Tests for a Cosmology[Read/Write] with ``format="json"``.
This class will not be directly called by :mod:`pytest` since its name does
not begin with ``Test``. To activate the contained tests this class must
be inherited in a subclass. Subclasses must define a ... | ReadWriteJSONTestMixin |
python | pypa__hatch | src/hatch/template/__init__.py | {
"start": 158,
"end": 780
} | class ____:
def __init__(self, path: Path | None, contents: str = ""):
self.path = path
self.contents = contents
self.feature = None
def write(self, root):
if self.path is None: # no cov
return
path = root / self.path
path.ensure_parent_dir_exists()... | File |
python | facebook__pyre-check | stubs/integration_test/fixture_source/integration_test/cache.py | {
"start": 1276,
"end": 1359
} | class ____(YetAnotherBase):
def method(self, x):
pass
| YetAnotherOverride2 |
python | hyperopt__hyperopt | hyperopt/tests/test_base.py | {
"start": 1677,
"end": 4153
} | class ____:
"""
Run some generic sanity-checks of a suggest algorithm to make sure that
it respects the semantics expected by e.g. fmin.
Use it like this:
TestRand = Suggest_API.make_test_class(rand.suggest, 'TestRand')
"""
@classmethod
def make_tst_class(cls, suggest, domain, na... | Suggest_API |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 143293,
"end": 143349
} | class ____(Enum):
SYMM_MEM = "symm_mem"
| CommBufferType |
python | realpython__materials | tic-tac-toe-ai-python/source_code_bonus/tic-tac-toe/frontends/window/renderers.py | {
"start": 167,
"end": 797
} | class ____(tk.Tk):
def __init__(self, events: Queue) -> None:
super().__init__()
self.title("Tic-Tac-Toe")
self.events = events
self.buttons = []
for row in range(3):
for col in range(3):
button = ttk.Button(master=self, text="", width=5)
... | Window |
python | PyCQA__pylint | tests/functional/a/assigning/assigning_non_slot.py | {
"start": 3483,
"end": 3735
} | class ____(Unknown):
__slots__ = ['yo']
def test(self):
self.not_yo = 42
# pylint: disable=wrong-import-order, wrong-import-position
from typing import (
Generic,
TypeVar,
)
TypeT = TypeVar('TypeT')
| ClassHavingUnknownAncestors |
python | huggingface__transformers | src/transformers/models/biogpt/modular_biogpt.py | {
"start": 1969,
"end": 2038
} | class ____(BartScaledWordEmbedding):
pass
| BioGptScaledWordEmbedding |
python | huggingface__transformers | src/transformers/models/csm/modeling_csm.py | {
"start": 19386,
"end": 24379
} | class ____(CsmPreTrainedModel):
config: CsmDepthDecoderConfig
def __init__(self, config):
super().__init__(config)
self.padding_idx = config.pad_token_id
self.vocab_size = config.vocab_size
self.embed_tokens = nn.Embedding((config.num_codebooks * config.vocab_size), config.backb... | CsmDepthDecoderModel |
python | PrefectHQ__prefect | src/prefect/blocks/notifications.py | {
"start": 7089,
"end": 12336
} | class ____(AbstractAppriseNotificationBlock):
"""
Enables sending notifications via a provided PagerDuty webhook.
See [Apprise notify_pagerduty docs](https://github.com/caronc/apprise/wiki/Notify_pagerduty)
for more info on formatting the URL.
Examples:
Load a saved PagerDuty webhook and se... | PagerDutyWebHook |
python | tensorflow__tensorflow | tensorflow/python/trackable/resource.py | {
"start": 10112,
"end": 10820
} | class ____(TrackableResource):
"""Restored SavedResource."""
def __init__(self, device=""):
super().__init__(device=device)
@classmethod
def _deserialize_from_proto(cls, object_proto, dependencies, **unused_kwargs):
obj = cls(device=object_proto.resource.device)
resource_creator = dependencies.get... | RestoredResource |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_core/test_worker.py | {
"start": 40149,
"end": 43726
} | class ____:
"""Tests worker keda auto scaler."""
def test_should_add_component_specific_labels(self):
docs = render_chart(
values={
"executor": "CeleryExecutor",
"workers": {
"keda": {"enabled": True},
"labels": {"test_... | TestWorkerKedaAutoScaler |
python | python-poetry__poetry | tests/inspection/test_lazy_wheel.py | {
"start": 1706,
"end": 17146
} | class ____(IntEnum):
# numbers must be negative to avoid conflicts with HTTP status codes
as_positive = -1 # JFrog Artifactory bug (RTDEV-38572)
one_more = -2 # JFrog Artifactory bug (one more byte than requested)
def build_head_response(
accept_ranges: str | None, content_length: int, response_head... | NegativeOffsetFailure |
python | dagster-io__dagster | python_modules/libraries/dagster-databricks/dagster_databricks/components/databricks_asset_bundle/configs.py | {
"start": 14532,
"end": 15687
} | class ____(DatabricksBaseTask):
@property
def task_type(self) -> str:
return DATABRICKS_UNKNOWN_TASK_TYPE
@property
def task_config_metadata(self) -> Mapping[str, Any]:
return {}
@classmethod
def from_job_task_config(cls, job_task_config: Mapping[str, Any]) -> "DatabricksUnknow... | DatabricksUnknownTask |
python | sqlalchemy__sqlalchemy | test/orm/test_relationships.py | {
"start": 62900,
"end": 65037
} | class ____(fixtures.MappedTest):
"""test a relationship with a non-column entity in the primary join,
is not viewonly, and also has the non-column's clause mentioned in the
foreign keys list.
"""
@classmethod
def define_tables(cls, metadata):
Table(
"tags",
meta... | FKEquatedToConstantTest |
python | getsentry__sentry | src/sentry/snuba/entity_subscription.py | {
"start": 16696,
"end": 17606
} | class ____(BaseMetricsEntitySubscription):
query_type = SnubaQuery.Type.PERFORMANCE
dataset = Dataset.PerformanceMetrics
def get_snql_aggregations(self) -> list[str]:
return [self.aggregate]
def get_snql_extra_conditions(self) -> list[Condition]:
return []
def aggregate_query_resu... | PerformanceMetricsEntitySubscription |
python | scipy__scipy | scipy/integrate/tests/test_integrate.py | {
"start": 7693,
"end": 10217
} | class ____:
# Check integrate.ode correctly handles solout for dopri5 and dop853
def _run_solout_test(self, integrator):
# Check correct usage of solout
ts = []
ys = []
t0 = 0.0
tend = 10.0
y0 = [1.0, 2.0]
def solout(t, y):
ts.append(t)
... | TestSolout |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_type_checking/module/direct.py | {
"start": 105,
"end": 147
} | class ____(MyBaseClass):
foo: Sequence
| Foo |
python | getsentry__sentry | tests/sentry/models/test_grouprelease.py | {
"start": 257,
"end": 1816
} | class ____(TestCase):
def test_simple(self) -> None:
project = self.create_project()
group = self.create_group(project=project)
release = Release.objects.create(version="abc", organization_id=project.organization_id)
release.add_project(project)
env = Environment.objects.crea... | GetOrCreateTest |
python | networkx__networkx | networkx/algorithms/flow/tests/test_maxflow.py | {
"start": 17526,
"end": 18940
} | class ____:
def test_cutoff(self):
k = 5
p = 1000
G = nx.DiGraph()
for i in range(k):
G.add_edge("s", (i, 0), capacity=2)
nx.add_path(G, ((i, j) for j in range(p)), capacity=2)
G.add_edge((i, p - 1), "t", capacity=2)
R = shortest_augmenting... | TestCutoff |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/execution/context/logger.py | {
"start": 2170,
"end": 3150
} | class ____(InitLoggerContext):
"""Logger initialization context outputted by ``build_init_logger_context``.
Represents a context whose config has not yet been validated against a logger definition, hence
the inability to access the `logger_def` attribute. When an instance of
``UnboundInitLoggerContext`... | UnboundInitLoggerContext |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/typing/__init__.py | {
"start": 6050,
"end": 6345
} | class ____(TypedDict):
"""DataFrame serialization header."""
columns_kwargs: list[ColumnOptions]
frame_count: int
# Not public in polars yet
RankMethod = Literal["ordinal", "dense", "min", "max", "average"]
RoundMethod = Literal["half_away_from_zero", "half_to_even"]
| DataFrameHeader |
python | getsentry__sentry | src/sentry/apidocs/parameters.py | {
"start": 30690,
"end": 31300
} | class ____:
QUERY = OpenApiParameter(
name="query",
location="query",
required=False,
type=str,
description="""The name of the Discover query you'd like to filter by.""",
)
SORT = OpenApiParameter(
name="sortBy",
location="query",
required=Fal... | DiscoverSavedQueriesParams |
python | django__django | tests/migrations/migrations_test_apps/with_generic_model/models.py | {
"start": 176,
"end": 499
} | class ____[T](models.Model):
"""A model inheriting from typing.Generic via the PEP 695 syntax."""
# Example from Python docs:
# https://typing.python.org/en/latest/spec/generics.html#arbitrary-generic-types-as-base-classes
T1 = typing.TypeVar("T1")
T2 = typing.TypeVar("T2")
T3 = typing.TypeVar("T3")
| GenericModelPEP695 |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/migration/ndb/redis_cache/main.py | {
"start": 1037,
"end": 3037
} | class ____(ndb.Model):
"""Models an individual Guestbook entry with content and date."""
content = ndb.StringProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
# [END gae_ndb_redis_cache_greeting]
# [START gae_ndb_redis_cache_query]
with client.context(global_cache=global_cache):
... | Greeting |
python | kamyu104__LeetCode-Solutions | Python/make-a-positive-array.py | {
"start": 50,
"end": 597
} | class ____(object):
def makeArrayPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
MAX_VAL = 10**18
result = 0
prev1 = nums[0]+nums[1]
prev2 = nums[0]
max_prev3 = 0
for i in xrange(2, len(nums)):
prefix = prev1... | Solution |
python | keras-team__keras | keras/src/trainers/data_adapters/grain_dataset_adapter_test.py | {
"start": 606,
"end": 8260
} | class ____(testing.TestCase):
def _get_dataset(self, dataset_type, worker_count=0, num_threads=0):
x = np.random.normal(size=(34, 4)).astype("float32")
y = np.random.normal(size=(34, 2)).astype("float32")
class MySource(grain.sources.RandomAccessDataSource):
def __init__(self, x... | GrainDatasetAdapterTest |
python | great-expectations__great_expectations | tests/integration/data_sources_and_expectations/test_misconfigured_expectations.py | {
"start": 1071,
"end": 3609
} | class ____:
# Currently bugs with the following (not raising misconfiguration errors at all):
# - sqlite
# - databricks
# - mysql
# - spark-filesystem-csv
_DATA = pd.DataFrame({"a": ["b", "c"]})
_EXPECTATION = gxe.ExpectColumnStdevToBeBetween(
column="a",
min_value=0,
... | TestNumericExpectationAgainstStrDataMisconfiguration |
python | networkx__networkx | networkx/readwrite/tests/test_graphml.py | {
"start": 155,
"end": 12969
} | class ____:
@classmethod
def setup_class(cls):
cls.simple_directed_data = """<?xml version="1.0" encoding="UTF-8"?>
<!-- This file was written by the JAVA GraphML Library.-->
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xs... | BaseGraphML |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.