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 | pymupdf__PyMuPDF | src/__init__.py | {
"start": 646302,
"end": 646392
} | class ____(RuntimeError):
"""Raised if file does not exist."""
pass
| FileNotFoundError |
python | huggingface__transformers | src/transformers/models/qwen3_vl_moe/modeling_qwen3_vl_moe.py | {
"start": 11259,
"end": 14831
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: Qwen3VLMoeTextConfig, layer_idx: int):
super().__init__()
self.layer_type = config.layer_types[layer_idx] if hasattr(config, "layer_types") else None
self.config = confi... | Qwen3VLMoeTextAttention |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_exceptions.py | {
"start": 69827,
"end": 71204
} | class ____(__TestCase):
def test_attributes(self):
# Setting 'attr' should not be a problem.
exc = AttributeError('Ouch!')
self.assertIsNone(exc.name)
self.assertIsNone(exc.obj)
sentinel = object()
exc = AttributeError('Ouch', name='carry', obj=sentinel)
self... | AttributeErrorTests |
python | getsentry__sentry | tests/sentry/sentry_apps/api/bases/test_sentryapps.py | {
"start": 773,
"end": 3870
} | class ____(TestCase):
def setUp(self) -> None:
self.permission = SentryAppPermission()
self.sentry_app = self.create_sentry_app(name="foo", organization=self.organization)
self.request = drf_request_from_request(self.make_request(user=self.user, method="GET"))
self.superuser = self... | SentryAppPermissionTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1586797,
"end": 1587073
} | class ____(sgqlc.types.Union):
"""Represents either a repository the viewer can access or a
restricted contribution.
"""
__schema__ = github_schema
__types__ = (CreatedRepositoryContribution, RestrictedContribution)
| CreatedRepositoryOrRestrictedContribution |
python | kamyu104__LeetCode-Solutions | Python/count-integers-in-intervals.py | {
"start": 155,
"end": 1054
} | class ____(object):
def __init__(self):
self.__sl = SortedList()
self.__cnt = 0
def add(self, left, right):
"""
:type left: int
:type right: int
:rtype: None
"""
i = self.__sl.bisect_right((left,))
if i-1 >= 0 and self.__sl[i-1][1]+1 >= l... | CountIntervals |
python | streamlit__streamlit | lib/streamlit/elements/widgets/multiselect.py | {
"start": 2283,
"end": 5559
} | class ____(Generic[T]):
options: Sequence[T]
formatted_options: list[str]
formatted_option_to_option_index: dict[str, int]
default_options_indices: list[int]
def __init__(
self,
options: Sequence[T],
*,
formatted_options: list[str],
formatted_option_to_option... | MultiSelectSerde |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_mutating_admission_policy_list.py | {
"start": 383,
"end": 7317
} | 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... | V1beta1MutatingAdmissionPolicyList |
python | pypa__warehouse | warehouse/accounts/utils.py | {
"start": 437,
"end": 1581
} | class ____:
"""
This class supports `MacaroonSecurityPolicy` in
`warehouse.macaroons.security_policy`.
It is a wrapper containing both a user associated with an authenticated request
and an optional corresponding Macaroon, if the authentication was via API token.
If the request was authenticate... | UserContext |
python | google__jax | tests/mosaic/gpu_test.py | {
"start": 192973,
"end": 200002
} | class ____(Sm90ATestCase, jtu.JaxTestCase):
@parameterized.product(
swizzle=tuple(mgpu_dialect.SwizzlingMode),
transpose_lhs=(False, True),
transpose_rhs=(False, True),
lhs_in_registers=(False, True),
)
def test_wgmma_kernel_with_tma(
self, swizzle, transpose_lhs, transpose_rhs, lhs... | MosaicGpuDialectSm90ATest |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataflow.py | {
"start": 46647,
"end": 50078
} | class ____(GoogleCloudBaseOperator):
"""
Runs a Dataflow Data Pipeline.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:DataflowRunPipelineOperator`
:param pipeline_name: The display name of the pipeline. In example
... | DataflowRunPipelineOperator |
python | charliermarsh__ruff | crates/ruff_server/resources/test/fixtures/pandas_html.py | {
"start": 16735,
"end": 20405
} | class ____(_HtmlFrameParser):
"""
HTML to DataFrame parser that uses BeautifulSoup under the hood.
See Also
--------
pandas.io.html._HtmlFrameParser
pandas.io.html._LxmlFrameParser
Notes
-----
Documentation strings for this class are in the base class
:class:`pandas.io.html._Ht... | _BeautifulSoupHtml5LibFrameParser |
python | scipy__scipy | scipy/optimize/tests/test_chandrupatla.py | {
"start": 5280,
"end": 20348
} | class ____:
def f(self, x, loc):
xp = array_namespace(x, loc)
res = -xp.exp(-1/2 * (x-loc)**2) / (2*xp.pi)**0.5
return xp.asarray(res, dtype=x.dtype)[()]
@pytest.mark.parametrize('dtype', ('float32', 'float64'))
@pytest.mark.parametrize('loc', [0.6, np.linspace(-1.05, 1.05, 10)])
... | TestChandrupatlaMinimize |
python | openai__openai-python | src/openai/_module_client.py | {
"start": 3072,
"end": 3215
} | class ____(LazyProxy["Containers"]):
@override
def __load__(self) -> Containers:
return _load_client().containers
| ContainersProxy |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 133324,
"end": 133920
} | class ____(nn.Module):
def __init__(self, codec_num_embeds, codec_dim, repeats):
super().__init__()
self.repeats = repeats
self.codec_embed = nn.Embedding(codec_num_embeds + 1, codec_dim)
def forward(self, code, drop_code=False):
if drop_code:
code = torch.zeros_like... | DiTCodecEmbedding |
python | pandas-dev__pandas | asv_bench/benchmarks/io/csv.py | {
"start": 13563,
"end": 14485
} | class ____(StringIORewind):
params = ["c", "python"]
param_names = ["engine"]
def setup(self, engine):
data = """{},19:00:00,18:56:00,0.8100,2.8100,7.2000,0.0000,280.0000\n
{},20:00:00,19:56:00,0.0100,2.2100,7.2000,0.0000,260.0000\n
{},21:00:00,20:56:00,-0.5900,2... | ReadCSVParseDates |
python | doocs__leetcode | solution/1700-1799/1799.Maximize Score After N Operations/Solution.py | {
"start": 0,
"end": 735
} | class ____:
def maxScore(self, nums: List[int]) -> int:
m = len(nums)
f = [0] * (1 << m)
g = [[0] * m for _ in range(m)]
for i in range(m):
for j in range(i + 1, m):
g[i][j] = gcd(nums[i], nums[j])
for k in range(1 << m):
if (cnt := k.b... | Solution |
python | pola-rs__polars | py-polars/src/polars/io/iceberg/_utils.py | {
"start": 17751,
"end": 18680
} | class ____(abc.ABC):
def __init__(self, polars_dtype: pl.DataType) -> None:
self.polars_dtype = polars_dtype
@staticmethod
def init_for_field_type(
current_field_type: IcebergType,
# All types that this field ID has been set to across schema changes.
all_field_types: set[Ice... | LoadFromBytesImpl |
python | numba__numba | numba/core/caching.py | {
"start": 25899,
"end": 26855
} | class ____(Cache):
"""
Implements Cache that saves and loads CompileResult objects.
"""
_impl_class = CompileResultCacheImpl
# Remember used cache filename prefixes.
_lib_cache_prefixes = set([''])
def make_library_cache(prefix):
"""
Create a Cache class for additional compilation features t... | FunctionCache |
python | readthedocs__readthedocs.org | readthedocs/subscriptions/views.py | {
"start": 6812,
"end": 8273
} | class ____(OrganizationMixin, GenericView):
"""Create a stripe billing portal session for the user to manage their subscription."""
http_method_names = ["post"]
def get_success_url(self):
return reverse(
"subscription_detail",
args=[self.get_organization().slug],
)
... | StripeCustomerPortal |
python | getsentry__sentry | src/sentry/notifications/platform/target.py | {
"start": 730,
"end": 865
} | class ____(StrEnum):
GENERIC = "generic"
INTEGRATION = "integration"
@dataclass(kw_only=True, frozen=True)
| NotificationTargetType |
python | getsentry__sentry-python | sentry_sdk/utils.py | {
"start": 7865,
"end": 7927
} | class ____(ValueError):
"""Raised on invalid DSNs."""
| BadDsn |
python | doocs__leetcode | solution/3600-3699/3644.Maximum K to Sort a Permutation/Solution.py | {
"start": 0,
"end": 200
} | class ____:
def sortPermutation(self, nums: List[int]) -> int:
ans = -1
for i, x in enumerate(nums):
if i != x:
ans &= x
return max(ans, 0)
| Solution |
python | huggingface__transformers | src/transformers/models/electra/modeling_electra.py | {
"start": 9395,
"end": 12964
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a mu... | ElectraCrossAttention |
python | has2k1__plotnine | plotnine/themes/theme_gray.py | {
"start": 5226,
"end": 5265
} | class ____(theme_gray):
pass
| theme_grey |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/closure.py | {
"start": 6143,
"end": 7375
} | class ____(Generic[T]):
...
V = List[GenericClass[str]]
P = ParamSpec('P')
def decorator(function: Callable[P, Awaitable[V]]) -> Callable[P, Awaitable[V]]:
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> V:
return await function(*args, **kwargs)
return wrapper
def ignored_decorator(func... | GenericClass |
python | run-llama__llama_index | llama-index-core/tests/tools/test_eval_query_engine_tool.py | {
"start": 1190,
"end": 2995
} | class ____(IsolatedAsyncioTestCase):
def setUp(self) -> None:
self.mock_evaluator = MockEvaluator()
self.mock_evaluator.aevaluate = AsyncMock()
self.mock_evaluator.aevaluate.return_value = EvaluationResult(passing=True)
tool_name = "nice_tool"
self.tool_input = "hello world"... | TestEvalQueryEngineTool |
python | conda__conda | conda/models/environment.py | {
"start": 6996,
"end": 21527
} | class ____:
"""
**Experimental** While experimental, expect both major and minor changes across minor releases.
Data model for a conda environment.
"""
#: The platform this environment may be installed on (required)
platform: str
#: Environment level configuration, eg. channels, solver op... | Environment |
python | django__django | tests/admin_filters/tests.py | {
"start": 9883,
"end": 83510
} | class ____(TestCase):
request_factory = RequestFactory()
@classmethod
def setUpTestData(cls):
cls.today = datetime.date.today()
cls.tomorrow = cls.today + datetime.timedelta(days=1)
cls.one_week_ago = cls.today - datetime.timedelta(days=7)
if cls.today.month == 12:
... | ListFiltersTests |
python | ray-project__ray | rllib/callbacks/tests/test_callbacks_old_api_stack.py | {
"start": 256,
"end": 748
} | class ____(DefaultCallbacks):
def __init__(self):
super().__init__()
self.counts = Counter()
def on_episode_start(self, *args, **kwargs):
self.counts.update({"start": 1})
def on_episode_step(self, *args, **kwargs):
self.counts.update({"step": 1})
def on_episode_end(sel... | EpisodeAndSampleCallbacks |
python | tensorflow__tensorflow | tensorflow/python/distribute/tpu_strategy_test.py | {
"start": 41146,
"end": 45576
} | class ____(test.TestCase):
def test_prefetch_to_device_default(self):
strategy = get_tpu_strategy()
dataset = dataset_ops.Dataset.range(
strategy.num_replicas_in_sync * 2,
output_type=dtypes.float32).batch(strategy.num_replicas_in_sync)
# Check default, should prefetch to TPU.
datase... | TPUStrategyDataPrefetchTest |
python | getsentry__sentry | tests/sentry/tasks/test_post_process.py | {
"start": 30533,
"end": 32910
} | class ____(BasePostProgressGroupMixin):
@patch("sentry.rules.processing.processor.RuleProcessor")
def test_group_inbox_regression(self, mock_processor: MagicMock) -> None:
new_event = self.create_event(data={"message": "testing"}, project_id=self.project.id)
group = new_event.group
asse... | InboxTestMixin |
python | great-expectations__great_expectations | great_expectations/expectations/core/expect_column_distinct_values_to_equal_set.py | {
"start": 2457,
"end": 19052
} | class ____(ColumnAggregateExpectation):
__doc__ = f"""{EXPECTATION_SHORT_DESCRIPTION}
ExpectColumnDistinctValuesToEqualSet is a \
Column Aggregate Expectation.
Column Aggregate Expectations are one of the most common types of Expectation.
They are evaluated for a single column, and produce an aggr... | ExpectColumnDistinctValuesToEqualSet |
python | huggingface__transformers | src/transformers/models/qwen2_moe/modeling_qwen2_moe.py | {
"start": 6363,
"end": 10461
} | class ____(nn.Module):
def __init__(self, config, intermediate_size=None):
super().__init__()
self.config = config
self.hidden_size = config.hidden_size
self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
self.gate_proj = nn.L... | Qwen2MoeMLP |
python | walkccc__LeetCode | solutions/940. Distinct Subsequences II/940.py | {
"start": 0,
"end": 279
} | class ____:
def distinctSubseqII(self, s: str) -> int:
MOD = 1_000_000_007
# endsIn[i] := the number of subsequence that end in ('a' + i)
endsIn = [0] * 26
for c in s:
endsIn[ord(c) - ord('a')] = (sum(endsIn) + 1) % MOD
return sum(endsIn) % MOD
| Solution |
python | getsentry__sentry | src/sentry/apidocs/parameters.py | {
"start": 26650,
"end": 27925
} | class ____:
PROVIDER_KEY = OpenApiParameter(
name="providerKey",
location="query",
required=False,
type=str,
description="""Specific integration provider to filter by such as `slack`. See our [Integrations Documentation](/product/integrations/) for an updated list of provider... | IntegrationParams |
python | bokeh__bokeh | src/bokeh/models/misc/group_by.py | {
"start": 2092,
"end": 2881
} | class ____(GroupBy):
""" Group models by their names (``Model.name`` property). """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
# TODO GroupByCustomJS(GroupBy)
#--------------------------------------------... | GroupByName |
python | huggingface__transformers | tests/models/got_ocr2/test_image_processing_got_ocr2.py | {
"start": 1122,
"end": 3030
} | class ____(unittest.TestCase):
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_resize=True,
size=None,
do_normalize=True,
image_mean=[0.48145466, 0.4578275, 0.40... | GotOcr2ImageProcessingTester |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/quantization_ops/quantization_ops_test.py | {
"start": 3334,
"end": 4387
} | class ____(test_util.TensorFlowTestCase):
@test_util.run_in_graph_and_eager_modes
def test_invalid_inputs(self):
gradients = constant_op.constant(
value=[[1.0], [2.0], [4.0]], dtype=dtypes.float32)
inputs = constant_op.constant(
value=[[1.0], [2.0], [4.0]], dtype=dtypes.float32)
with s... | FakeQuantWithMinMaxVarsGradientOpTest |
python | huggingface__transformers | src/transformers/models/xlnet/modeling_xlnet.py | {
"start": 16690,
"end": 19576
} | class ____(nn.Module):
"""
Compute SQuAD 2.0 answer class from classification and start tokens hidden states.
Args:
config ([`XLNetConfig`]):
The config used by the model, will be used to grab the `hidden_size` of the model.
"""
def __init__(self, config: XLNetConfig):
... | XLNetPoolerAnswerClass |
python | pytorch__pytorch | test/distributed/optim/test_zero_redundancy_optimizer.py | {
"start": 1644,
"end": 1823
} | class ____(DistributedTestBase):
@property
def device(self):
return device_type
@property
def world_size(self):
return 1
| TestZeroRedundancyOptimizer |
python | getsentry__sentry | src/sentry/sentry_apps/models/sentry_app.py | {
"start": 2200,
"end": 2882
} | class ____(ParanoidManager["SentryApp"]):
def get_alertable_sentry_apps(self, organization_id: int) -> QuerySet:
return self.filter(
installations__organization_id=organization_id,
is_alertable=True,
installations__status=SentryAppInstallationStatus.INSTALLED,
... | SentryAppManager |
python | openai__openai-python | src/openai/types/responses/response_output_item.py | {
"start": 4553,
"end": 5624
} | class ____(BaseModel):
id: str
"""The unique ID of the approval request."""
arguments: str
"""A JSON string of arguments for the tool."""
name: str
"""The name of the tool to run."""
server_label: str
"""The label of the MCP server making the request."""
type: Literal["mcp_approv... | McpApprovalRequest |
python | astropy__astropy | astropy/io/fits/tests/test_nonstandard.py | {
"start": 150,
"end": 2325
} | class ____(FitsTestCase):
def test_create_fitshdu(self):
"""
A round trip test of creating a FitsHDU, adding a FITS file to it,
writing the FitsHDU out as part of a new FITS file, and then reading
it and recovering the original FITS file.
"""
self._test_create_fitshd... | TestNonstandardHdus |
python | tensorflow__tensorflow | tensorflow/python/data/experimental/kernel_tests/assert_prev_test.py | {
"start": 1160,
"end": 3784
} | class ____(test_base.DatasetTestBase, parameterized.TestCase):
@combinations.generate(test_base.default_test_combinations())
def testAssertPrev(self):
dataset = dataset_ops.Dataset.from_tensors(0).map(
lambda x: x, deterministic=True, num_parallel_calls=8).apply(
testing.assert_prev([("Para... | AssertPrevTest |
python | facebook__pyre-check | tools/upgrade/commands/codemods.py | {
"start": 4920,
"end": 5966
} | class ____(Command):
def __init__(self, *, local_roots: Sequence[Path], repository: Repository) -> None:
super().__init__(repository)
self._local_roots = local_roots
@staticmethod
def from_arguments(
arguments: argparse.Namespace, repository: Repository
) -> "SetUseBuck1":
... | SetUseBuck1 |
python | coleifer__peewee | tests/db_tests.py | {
"start": 23878,
"end": 25418
} | class ____(BaseTestCase):
def test_sort_models(self):
class A(Model):
pass
class B(Model):
a = ForeignKeyField(A)
class C(Model):
b = ForeignKeyField(B)
class D(Model):
c = ForeignKeyField(C)
class E(Model):
pass
... | TestSortModels |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 5771,
"end": 7646
} | class ____(RegexLexer):
"""
Generic `Smarty <http://smarty.php.net/>`_ template lexer.
Just highlights smarty code between the preprocessor directives, other
data is left untouched by the lexer.
"""
name = 'Smarty'
aliases = ['smarty']
filenames = ['*.tpl']
mimetypes = ['applicatio... | SmartyLexer |
python | google__pytype | pytype/tests/test_annotations.py | {
"start": 37948,
"end": 39693
} | class ____(test_base.BaseTest):
"""Tests usage of '...' to mean "inferred type".
This is an experimental feature that makes it possible to explicitly annotate
a type as inferred. See b/213607272.
"""
def test_variable(self):
ty = self.Infer("x: ... = 0")
self.assertTypesMatchPytd(ty, "x: int")
de... | EllipsisTest |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/pygments/formatters/html.py | {
"start": 2365,
"end": 35669
} | class ____(Formatter):
r"""
Format tokens as HTML 4 ``<span>`` tags. By default, the content is enclosed
in a ``<pre>`` tag, itself wrapped in a ``<div>`` tag (but see the `nowrap` option).
The ``<div>``'s CSS class can be set by the `cssclass` option.
If the `linenos` option is set to ``"table"``,... | HtmlFormatter |
python | PrefectHQ__prefect | tests/server/orchestration/api/ui/test_task_runs.py | {
"start": 4671,
"end": 10626
} | class ____:
@pytest.fixture
def url(self) -> str:
return "/ui/task_runs/count"
@pytest.fixture
async def create_flow_runs(
self,
session: AsyncSession,
flow: orm_models.Flow,
):
await session.execute(delete(orm_models.FlowRun))
run_1 = await models.f... | TestReadTaskRunCountsByState |
python | great-expectations__great_expectations | tests/integration/data_sources_and_expectations/test_expectation_conditions.py | {
"start": 17990,
"end": 19745
} | class ____:
"""Test that SQLAlchemy execution engines properly reject PassThroughCondition."""
@parameterize_batch_for_data_sources(
data_source_configs=[
PostgreSQLDatasourceTestConfig(
column_types={
"created_at": POSTGRESQL_TYPES.TIMESTAMP,
... | TestSqlAlchemyRejectsPassThroughCondition |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-core/dagster_dg_core/config.py | {
"start": 17502,
"end": 17821
} | class ____(TypedDict):
directory_type: Required[Literal["workspace"]]
workspace: Required[DgRawWorkspaceConfig]
cli: NotRequired[DgRawCliConfig]
def is_workspace_file_config(config: "DgFileConfig") -> TypeGuard[DgWorkspaceFileConfig]:
return config["directory_type"] == "workspace"
| DgWorkspaceFileConfig |
python | google__jax | jax/experimental/jax2tf/tests/flax_models/transformer_wmt.py | {
"start": 9707,
"end": 11323
} | class ____(nn.Module):
"""Transformer Model Encoder for sequence to sequence translation.
Attributes:
config: TransformerConfig dataclass containing hyperparameters.
shared_embedding: a shared embedding layer to use.
"""
config: TransformerConfig
shared_embedding: Any = None
@nn.compact
def __ca... | Encoder |
python | streamlit__streamlit | lib/streamlit/elements/widgets/multiselect.py | {
"start": 5559,
"end": 21059
} | class ____:
@overload
def multiselect(
self,
label: str,
options: OptionSequence[T],
default: Any | None = None,
format_func: Callable[[Any], str] = str,
key: Key | None = None,
help: str | None = None,
on_change: WidgetCallback | None = None,
... | MultiSelectMixin |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI019_0.py | {
"start": 5581,
"end": 5706
} | class ____:
@classmethod
def m[S](cls: "type[S]") -> "type[S]": ... # PYI019
| BadSubscriptReturnTypeWithStringTypeHints |
python | donnemartin__interactive-coding-challenges | online_judges/nim/test_can_win_nim.py | {
"start": 18,
"end": 675
} | class ____(unittest.TestCase):
def test_can_win_nim(self):
solution = Solution()
self.assertRaises(TypeError, solution.can_win_nim, None)
self.assertEqual(solution.can_win_nim(1), True)
self.assertEqual(solution.can_win_nim(2), True)
self.assertEqual(solution.can_win_nim(3),... | TestSolution |
python | rapidsai__cudf | docs/cudf/source/_ext/PandasCompat.py | {
"start": 1054,
"end": 2844
} | class ____(BaseAdmonition, SphinxDirective):
# this enables content in the directive
has_content = True
def run(self):
targetid = "PandasCompat-%d" % self.env.new_serialno("PandasCompat")
targetnode = nodes.target("", "", ids=[targetid])
PandasCompat_node = PandasCompat("\n".join(s... | PandasCompatDirective |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/pool/base.py | {
"start": 4169,
"end": 4230
} | class ____(_ConnDialect):
is_async = True
| _AsyncConnDialect |
python | apache__airflow | providers/elasticsearch/tests/unit/elasticsearch/hooks/test_elasticsearch.py | {
"start": 1878,
"end": 2632
} | class ____:
def setup_method(self):
self.connection = Connection(host="localhost", port=9200, schema="http")
class UnitTestElasticsearchSQLHook(ElasticsearchSQLHook):
conn_name_attr = "elasticsearch_conn_id"
self.db_hook = UnitTestElasticsearchSQLHook()
self.db_hook.get... | TestElasticsearchSQLHookConn |
python | pytorch__pytorch | torch/distributed/_symmetric_memory/_nvshmem_triton.py | {
"start": 3634,
"end": 46972
} | class ____:
"""
A class to register kernel functions that ** require NVSHMEM initialization **
"""
# Class variable to store the functions to be initialized
_to_init: dict[str, Any] = {}
@classmethod
def register(cls, name: str) -> None:
"""
Register a kernel function with ... | NvshmemKernelRegistry |
python | encode__django-rest-framework | tests/authentication/test_authentication.py | {
"start": 21839,
"end": 23081
} | class ____(TestCase):
def test_base_authentication_abstract_method(self):
with pytest.raises(NotImplementedError):
BaseAuthentication().authenticate({})
def test_basic_authentication_raises_error_if_user_not_found(self):
auth = BasicAuthentication()
with pytest.raises(excep... | BasicAuthenticationUnitTests |
python | huggingface__transformers | tests/pipelines/test_pipelines_mask_generation.py | {
"start": 1649,
"end": 7291
} | class ____(unittest.TestCase):
model_mapping = dict(list(MODEL_FOR_MASK_GENERATION_MAPPING.items()) if MODEL_FOR_MASK_GENERATION_MAPPING else [])
def get_test_pipeline(
self,
model,
tokenizer=None,
image_processor=None,
feature_extractor=None,
processor=None,
... | MaskGenerationPipelineTests |
python | ApeWorX__ape | tests/functional/test_project.py | {
"start": 41630,
"end": 42780
} | class ____:
def test_iter(self, smaller_project):
actual = list(iter(smaller_project.contracts))
assert len(actual) > 0
assert "Other" in actual
def test_compile(self, smaller_project):
path = smaller_project.sources.lookup("Other.json")
actual = list(smaller_project.con... | TestContractManager |
python | getsentry__sentry | src/sentry/utils/concurrent.py | {
"start": 4438,
"end": 5454
} | class ____:
"""
This class provides an API for executing tasks in different contexts
(immediately, or asynchronously.)
NOTE: This is *not* compatible with the ``concurrent.futures.Executor``
API! Rather than ``submit`` accepting the function arguments, the function
must already have the argumen... | Executor |
python | google__jax | jax/experimental/jax2tf/tests/tf_test_util.py | {
"start": 2457,
"end": 6110
} | class ____:
tf_type: str # The standard Tf.Operation.type
op_type: str # The rest are OpMetadata fields from _Xla... attributes
op_name: str
source_file: str
source_line: str
def SaveAndLoadModel(model: tf.Module,
save_gradients=True) -> tf.Module:
# Roundtrip through saved model on... | OpMetadataGraph |
python | huggingface__transformers | src/transformers/models/ministral/modular_ministral.py | {
"start": 8661,
"end": 8710
} | class ____(Qwen2RMSNorm):
pass
| MinistralRMSNorm |
python | cython__cython | Cython/Compiler/Tests/TestParseTreeTransforms.py | {
"start": 2282,
"end": 3478
} | class ____: # (TransformTest): # Disabled!
def test_simplified(self):
t = self.run_pipeline([WithTransform(None)], """
with x:
y = z ** 3
""")
self.assertCode("""
$0_0 = x
$0_2 = $0_0.__exit__
$0_0.__enter__()
$0_1 = True
try:
... | TestWithTransform |
python | pytorch__pytorch | test/dynamo/test_higher_order_ops.py | {
"start": 35825,
"end": 79346
} | class ____(torch.nn.Module):
def forward(self, s77: "Sym(s77)", s27: "Sym(s27)", L_x_: "f32[s77, s27]", s94: "Sym(s94)", L_y_: "f32[s27, s94]"):
l_x_ = L_x_
l_y_ = L_y_
wrap_body_1 = self.wrap_body_1
wrap = torch.ops.higher_order.wrap(wrap_body_1, s77, s27, l_x_, s94, l_y_); wrap_b... | GraphModule |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/linalg/linear_operator_test.py | {
"start": 3947,
"end": 16338
} | class ____(test.TestCase):
def test_all_shape_properties_defined_by_the_one_property_shape(self):
shape = (1, 2, 3, 4)
operator = LinearOperatorShape(shape)
self.assertAllEqual(shape, operator.shape)
self.assertAllEqual(4, operator.tensor_rank)
self.assertAllEqual((1, 2), operator.batch_shape)
... | LinearOperatorTest |
python | apache__airflow | providers/git/src/airflow/providers/git/hooks/git.py | {
"start": 1059,
"end": 4340
} | class ____(BaseHook):
"""
Hook for git repositories.
:param git_conn_id: Connection ID for SSH connection to the repository
"""
conn_name_attr = "git_conn_id"
default_conn_name = "git_default"
conn_type = "git"
hook_name = "GIT"
@classmethod
def get_ui_field_behaviour(cls) ->... | GitHook |
python | getsentry__sentry | tests/sentry/api/test_api_pagination_check.py | {
"start": 285,
"end": 2788
} | class ____(TestCase):
def test_if_wrong_api_method_fails(self) -> None:
class ExampleEndpoint(TestCase, Endpoint):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.access = "read"
# Required to go through the dispatch method... | APIPaginationCheckTestCase |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/dataflow.py | {
"start": 6309,
"end": 6509
} | class ____:
"""Helper class with Dataflow job types."""
JOB_TYPE_UNKNOWN = "JOB_TYPE_UNKNOWN"
JOB_TYPE_BATCH = "JOB_TYPE_BATCH"
JOB_TYPE_STREAMING = "JOB_TYPE_STREAMING"
| DataflowJobType |
python | pandas-dev__pandas | pandas/core/reshape/merge.py | {
"start": 31594,
"end": 82366
} | class ____:
"""
Perform a database (SQL) merge operation between two DataFrame or Series
objects using either columns as keys or their row indexes
"""
_merge_type = "merge"
how: JoinHow | Literal["asof"]
on: IndexLabel | None
# left_on/right_on may be None when passed, but in validate_s... | _MergeOperation |
python | PyCQA__pylint | tests/functional/u/using_constant_test.py | {
"start": 391,
"end": 3448
} | class ____:
def method(self):
pass
instance = Class()
if collections: # [using-constant-test]
pass
# GenExpr
if (node for node in range(10)): # [using-constant-test]
pass
if lambda: None: # [using-constant-test]
pass
if function: # [using-constant-test]
pass
if Class: # [using-consta... | Class |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_dataplex.py | {
"start": 14420,
"end": 16568
} | class ____:
@mock.patch(HOOK_STR)
@mock.patch(DATASCANJOB_STR)
def test_execute(self, mock_data_scan_job, hook_mock):
op = DataplexGetDataQualityScanResultOperator(
task_id="get_data_scan_result",
project_id=PROJECT_ID,
region=REGION,
job_id=JOB_ID,
... | TestDataplexGetDataQualityScanResultOperator |
python | sympy__sympy | sympy/physics/secondquant.py | {
"start": 42721,
"end": 46920
} | class ____(Function):
"""
The Commutator: [A, B] = A*B - B*A
The arguments are ordered according to comparison operators
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.secondquant import Commutator
>>> A, B = symbols('A,B', commutative=False)
>>> Commutato... | Commutator |
python | PyCQA__pylint | doc/data/messages/m/method-cache-max-size-none/good.py | {
"start": 161,
"end": 304
} | class ____:
def __init__(self):
self.result = []
def fibonacci(self, n):
self.result.append(cached_fibonacci(n))
| Fibonnaci |
python | bokeh__bokeh | src/bokeh/models/tickers.py | {
"start": 9662,
"end": 9986
} | class ____(AdaptiveTicker):
''' Generate ticks on a linear scale.
.. note::
This class may be renamed to ``LinearTicker`` in the future.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
| BasicTicker |
python | getsentry__sentry | src/sentry/issues/search.py | {
"start": 789,
"end": 998
} | class ____(Protocol):
def __call__(
self,
groupby: Sequence[str],
having: Sequence[Any],
orderby: Sequence[str],
) -> Mapping[str, Any]: ...
| IntermediateSearchQueryPartial |
python | plotly__plotly.py | plotly/graph_objs/scattermap/_cluster.py | {
"start": 233,
"end": 9682
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattermap"
_path_str = "scattermap.cluster"
_valid_props = {
"color",
"colorsrc",
"enabled",
"maxzoom",
"opacity",
"opacitysrc",
"size",
"sizesrc",
"step",
"stepsrc",
... | Cluster |
python | getsentry__sentry | src/sentry/api/serializers/models/relay.py | {
"start": 279,
"end": 598
} | class ____(Serializer):
def serialize(self, obj, attrs, user, **kwargs):
return {
"relayId": str(obj.relay_id),
"version": str(obj.version),
"publicKey": obj.public_key,
"firstSeen": obj.first_seen,
"lastSeen": obj.last_seen,
}
| RelaySerializer |
python | jmcnamara__XlsxWriter | xlsxwriter/app.py | {
"start": 316,
"end": 6103
} | class ____(xmlwriter.XMLwriter):
"""
A class for writing the Excel XLSX App file.
"""
###########################################################################
#
# Public API.
#
###########################################################################
def __init__(self) -> No... | App |
python | pytorch__pytorch | torch/_inductor/fx_passes/group_batch_fusion.py | {
"start": 48277,
"end": 48458
} | class ____(BatchMathOpsPreGradFusion):
def __init__(self, **kwargs):
super().__init__(torch.detach, **kwargs)
@register_fusion("batch_nan_to_num")
| BatchDetachPreGradFusion |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/metadata.py | {
"start": 651,
"end": 850
} | class ____(graphene.ObjectType):
path = graphene.NonNull(graphene.String)
class Meta:
interfaces = (GrapheneMetadataEntry,)
name = "PathMetadataEntry"
| GraphenePathMetadataEntry |
python | dagster-io__dagster | python_modules/dagster/dagster_tests/core_tests/resource_tests/pythonic_resources/test_type_signatures.py | {
"start": 4221,
"end": 4633
} | class ____(ConfigurableResource):
_my_schema: str = Field(alias="schema")
reveal_type(ResourceWithAlias.__init__)
my_resource = ResourceWithAlias(schema="foo")
"""
)
pyright_out = get_pyright_reveal_type_output(filename)
# Ensure constructor signature shows schema as the alias
... | ResourceWithAlias |
python | pytest-dev__pytest | src/_pytest/config/__init__.py | {
"start": 33872,
"end": 34587
} | class ____(MutableMapping[str, Any]):
"""Compatibility proxy for the deprecated Config.inicfg."""
__slots__ = ("_config",)
def __init__(self, config: Config) -> None:
self._config = config
def __getitem__(self, key: str) -> Any:
return self._config._inicfg[key].value
def __setite... | _DeprecatedInicfgProxy |
python | walkccc__LeetCode | solutions/531. Lonely Pixel I/531.py | {
"start": 0,
"end": 707
} | class ____:
def findLonelyPixel(self, picture: list[list[str]]) -> int:
m = len(picture)
n = len(picture[0])
ans = 0
rows = [0] * m # rows[i] := the number of B's in rows i
cols = [0] * n # cols[i] := the number of B's in cols i
for i in range(m):
for j in range(n):
if picture... | Solution |
python | h5py__h5py | h5py/tests/test_file.py | {
"start": 16059,
"end": 18827
} | class ____(TestCase):
"""
Feature: File format compatibility bounds can be specified when
opening a file.
"""
@classmethod
def setUpClass(cls):
super().setUpClass()
# Current latest library bound label
if h5py.version.hdf5_version_tuple < (1, 11, 4):
... | TestNewLibver |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 573107,
"end": 573873
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for DeploymentReviewer."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("DeploymentReviewerEdge"), graphql_name="edges")
"""A list of edges."... | DeploymentReviewerConnection |
python | google__jax | jax/_src/pallas/fuser/fusible_dtype.py | {
"start": 2614,
"end": 2671
} | class ____:
allow_conversion: bool = False
| FusibleTyRules |
python | prabhupant__python-ds | data_structures/bst/bfs.py | {
"start": 21,
"end": 601
} | class ____():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def bfs(root):
if not root:
return
queue = collections.deque([root])
while queue:
temp = queue.popleft()
print(temp.val)
if temp.right:
qu... | Node |
python | huggingface__transformers | src/transformers/models/umt5/modeling_umt5.py | {
"start": 3110,
"end": 4060
} | class ____(nn.Module):
def __init__(self, config: UMT5Config):
super().__init__()
self.wi = nn.Linear(config.d_model, config.d_ff, bias=False)
self.wo = nn.Linear(config.d_ff, config.d_model, bias=False)
self.dropout = nn.Dropout(config.dropout_rate)
self.act = ACT2FN[config.... | UMT5DenseActDense |
python | walkccc__LeetCode | solutions/2852. Sum of Remoteness of All Cells/2852.py | {
"start": 0,
"end": 998
} | class ____:
def sumRemoteness(self, grid: list[list[int]]) -> int:
DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))
n = len(grid)
summ = sum(max(0, cell) for row in grid for cell in row)
ans = 0
def dfs(i: int, j: int) -> tuple[int, int]:
"""
Returns the (count, componentSum) of the connecte... | Solution |
python | PyCQA__pylint | tests/functional/a/arguments_differ.py | {
"start": 2366,
"end": 2484
} | class ____(Staticmethod):
def func(self, data): # [arguments-differ]
super().func(data)
| StaticmethodChild2 |
python | django__django | tests/check_framework/test_model_field_deprecation.py | {
"start": 1513,
"end": 2879
} | class ____(SimpleTestCase):
def test_default_details(self):
class MyField(models.Field):
system_check_removed_details = {}
class Model(models.Model):
name = MyField()
model = Model()
self.assertEqual(
model.check(),
[
... | TestRemovedField |
python | getsentry__sentry | tests/sentry/auth/test_helper.py | {
"start": 23397,
"end": 24774
} | class ____(AuthIdentityHandlerTest):
def setUp(self) -> None:
super().setUp()
with assume_test_silo_mode(SiloMode.REGION):
member = OrganizationMember.objects.get(
organization=self.organization, user_id=self.user.id
)
self.identity_id = self.identity[... | HasVerifiedAccountTest |
python | pytorch__pytorch | torch/distributed/launcher/api.py | {
"start": 5947,
"end": 13786
} | class ____:
"""
Launches an torchelastic agent on the container that invoked the entrypoint.
1. Pass the ``entrypoint`` arguments as non ``kwargs`` (e.g. no named parameters)/
``entrypoint`` can be a function or a command.
2. The return value is a map of each worker's output mapped
... | elastic_launch |
python | pallets__werkzeug | src/werkzeug/routing/matcher.py | {
"start": 391,
"end": 774
} | class ____:
"""A representation of a rule state.
This includes the *rules* that correspond to the state and the
possible *static* and *dynamic* transitions to the next state.
"""
dynamic: list[tuple[RulePart, State]] = field(default_factory=list)
rules: list[Rule] = field(default_factory=list)... | State |
python | matplotlib__matplotlib | galleries/examples/animation/bayes_update.py | {
"start": 567,
"end": 2113
} | class ____:
def __init__(self, ax, prob=0.5):
self.success = 0
self.prob = prob
self.line, = ax.plot([], [], 'k-')
self.x = np.linspace(0, 1, 200)
self.ax = ax
# Set up plot parameters
self.ax.set_xlim(0, 1)
self.ax.set_ylim(0, 10)
self.ax.gri... | UpdateDist |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.