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 | spyder-ide__spyder | spyder/plugins/layout/layouts.py | {
"start": 566,
"end": 1870
} | class ____(BaseGridLayoutType):
ID = DefaultLayouts.SpyderLayout
def __init__(self, parent_plugin):
super().__init__(parent_plugin)
self.add_area(
[Plugins.Projects, Plugins.OutlineExplorer],
row=0,
column=0,
row_span=2,
visible=False... | SpyderLayout |
python | openai__gym | gym/envs/mujoco/swimmer.py | {
"start": 111,
"end": 1676
} | class ____(MuJocoPyEnv, utils.EzPickle):
metadata = {
"render_modes": [
"human",
"rgb_array",
"depth_array",
],
"render_fps": 25,
}
def __init__(self, **kwargs):
observation_space = Box(low=-np.inf, high=np.inf, shape=(8,), dtype=np.float6... | SwimmerEnv |
python | ray-project__ray | python/ray/data/aggregate.py | {
"start": 33143,
"end": 34968
} | class ____(AggregateFnV2[Set[Any], List[Any]]):
"""Defines unique aggregation.
Example:
.. testcode::
import ray
from ray.data.aggregate import Unique
ds = ray.data.range(100)
ds = ds.add_column("group_key", lambda x: x % 3)
# Calculating ... | Unique |
python | kamyu104__LeetCode-Solutions | Python/peeking-iterator.py | {
"start": 59,
"end": 954
} | class ____(object):
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.iterator = iterator
self.val_ = None
self.has_next_ = iterator.hasNext()
self.has_peeked_ = False
def peek(self):
... | PeekingIterator |
python | py-pdf__pypdf | tests/__init__.py | {
"start": 2467,
"end": 4294
} | class ____:
def __init__(self, strict=False) -> None:
self.strict = strict
def get_object(self, indirect_reference):
class DummyObj:
def get_object(self) -> "DummyObj":
return self
return DictionaryObject()
def get_reference(self, obj):
return I... | ReaderDummy |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/mariadb.py | {
"start": 2479,
"end": 3724
} | class ____(MySQLDialect):
is_mariadb = True
supports_statement_cache = True
supports_native_uuid = True
_allows_uuid_binds = True
name = "mariadb"
preparer: type[MySQLIdentifierPreparer] = MariaDBIdentifierPreparer
type_compiler_cls = MariaDBTypeCompiler
colspecs = util.update_copy(My... | MariaDBDialect |
python | huggingface__transformers | src/transformers/models/blip_2/modeling_blip_2.py | {
"start": 30358,
"end": 31488
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layer = nn.ModuleList(
[Blip2QFormerLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.gradient_checkpointing = False
@can_return_tu... | Blip2QFormerEncoder |
python | airbytehq__airbyte | airbyte-ci/connectors/connectors_qa/tests/unit_tests/test_checks/test_documentation.py | {
"start": 7389,
"end": 8947
} | class ____:
def test_fail_when_documentation_file_path_is_none(self, mocker):
# Arrange
connector = mocker.Mock(technical_name="test-connector", documentation_file_path=None)
# Act
result = documentation.CheckDocumentationExists()._run(connector)
# Assert
assert res... | TestCheckDocumentationExists |
python | huggingface__transformers | tests/models/bert_generation/test_modeling_bert_generation.py | {
"start": 17268,
"end": 18066
} | class ____(unittest.TestCase):
@slow
def test_inference_no_head_absolute_embedding(self):
model = BertGenerationEncoder.from_pretrained(
"google/bert_for_seq_generation_L-24_bbc_encoder", attn_implementation="eager"
)
input_ids = torch.tensor([[101, 7592, 1010, 2026, 3899, 20... | BertGenerationEncoderIntegrationTest |
python | Pylons__pyramid | tests/test_traversal.py | {
"start": 20595,
"end": 21035
} | class ____(unittest.TestCase):
def _callFUT(self, context):
from pyramid.traversal import find_root
return find_root(context)
def test_it(self):
dummy = DummyContext()
baz = DummyContext()
baz.__parent__ = dummy
baz.__name__ = 'baz'
dummy.__parent__ = No... | FindRootTests |
python | python-openxml__python-docx | src/docx/parts/numbering.py | {
"start": 119,
"end": 699
} | class ____(XmlPart):
"""Proxy for the numbering.xml part containing numbering definitions for a document
or glossary."""
@classmethod
def new(cls) -> "NumberingPart":
"""Newly created numbering part, containing only the root ``<w:numbering>`` element."""
raise NotImplementedError
@... | NumberingPart |
python | great-expectations__great_expectations | tests/datasource/fluent/data_asset/data_connector/test_google_cloud_storage_data_connector.py | {
"start": 1039,
"end": 25232
} | class ____:
# noinspection PyMethodMayBeStatic,PyUnusedLocal
def list_blobs(
self,
bucket_or_name,
max_results=None,
prefix=None,
delimiter=None,
**kwargs,
) -> Iterator:
return iter([])
@pytest.mark.big
@mock.patch(
"great_expectations.datasourc... | MockGCSClient |
python | PyCQA__pylint | tests/functional/u/unused/unused_import_assigned_to.py | {
"start": 289,
"end": 344
} | class ____:
uuid = test(default=uuid.uuid4)
| BaseModel |
python | readthedocs__readthedocs.org | readthedocs/doc_builder/backends/sphinx.py | {
"start": 6687,
"end": 6874
} | class ____(BaseSphinx):
relative_output_dir = "html"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.sphinx_builder = "html"
| HtmlBuilder |
python | coleifer__peewee | tests/sqlcipher_ext.py | {
"start": 3152,
"end": 3678
} | class ____(CleanUpModelTestCase):
database = config_db
def test_configuration_via_pragma(self):
# Write some data so the database file is created.
self.database.execute_sql('create table foo (data TEXT)')
self.database.close()
self.database.connect()
self.assertEqual(in... | TestSqlCipherConfiguration |
python | pytorch__pytorch | test/distributions/test_distributions.py | {
"start": 227564,
"end": 249956
} | class ____(DistributionsTestCase):
def setUp(self):
super().setUp()
class Binomial30(Binomial):
def __init__(self, probs):
super().__init__(30, probs)
# These are pairs of distributions with 4 x 4 parameters as specified.
# The first of the pair e.g. ber... | TestKL |
python | jd__tenacity | tests/test_asyncio.py | {
"start": 4547,
"end": 4851
} | class ____(unittest.TestCase):
def test_trio_basic(self):
thing = NoIOErrorAfterCount(5)
@retry
async def trio_function():
await trio.sleep(0.00001)
return thing.go()
trio.run(trio_function)
assert thing.counter == thing.count
| TestTrio |
python | readthedocs__readthedocs.org | readthedocs/integrations/models.py | {
"start": 904,
"end": 5205
} | class ____(models.Manager):
"""HTTP exchange manager methods."""
# Filter rules for request headers to remove from the output
REQ_FILTER_RULES = [
re.compile("^X-Forwarded-.*$", re.I),
re.compile("^X-Real-Ip$", re.I),
]
@transaction.atomic
def from_exchange(self, req, resp, rel... | HttpExchangeManager |
python | pytorch__pytorch | torch/distributions/one_hot_categorical.py | {
"start": 354,
"end": 4433
} | class ____(Distribution):
r"""
Creates a one-hot categorical distribution parameterized by :attr:`probs` or
:attr:`logits`.
Samples are one-hot coded vectors of size ``probs.size(-1)``.
.. note:: The `probs` argument must be non-negative, finite and have a non-zero sum,
and it will b... | OneHotCategorical |
python | pytorch__pytorch | test/mobile/model_test/tensor_ops.py | {
"start": 8028,
"end": 8578
} | class ____(torch.nn.Module):
def forward(self):
return self.tensor_view_ops()
def tensor_view_ops(self):
x = torch.randn(4, 4, 1)
y = torch.randn(4, 4, 2)
return len(
x[0, 2:],
x.detach(),
x.detach_(),
x.diagonal(),
x.e... | TensorViewOpsModule |
python | pytorch__pytorch | torch/_inductor/codegen/wrapper.py | {
"start": 24211,
"end": 26517
} | class ____(MemoryPlanningLine):
node: BufferLike
def __post_init__(self):
assert V.graph.scheduler.current_node is not None
self.scheduler_node_index = V.graph.scheduler.nodes.index(
V.graph.scheduler.current_node
)
def should_reuse_buffer(self, free_line: FreeIfNotReus... | AllocateLine |
python | conda__conda | conda/gateways/repodata/jlap/interface.py | {
"start": 4391,
"end": 4659
} | class ____(JlapRepoInterface):
"""
Support repodata.json.zst (if available) without checking .jlap
"""
def _repodata_state_copy(self, state: dict | RepodataState):
return RepodataStateSkipFormat(dict=state, skip_formats=["jlap"])
| ZstdRepoInterface |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 142592,
"end": 143480
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of ApproveDeployments"""
__schema__ = github_schema
__field_names__ = ("workflow_run_id", "environment_ids", "comment", "client_mutation_id")
workflow_run_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="workflowRunId")
"""The... | ApproveDeploymentsInput |
python | getsentry__sentry | tests/snuba/rules/conditions/test_event_frequency.py | {
"start": 51384,
"end": 51599
} | class ____(ErrorEventMixin, EventFrequencyConditionTestCase):
pass
@freeze_time(
(timezone.now() - timedelta(days=2)).replace(hour=12, minute=40, second=0, microsecond=0)
)
| ErrorIssueFrequencyConditionTestCase |
python | ansible__ansible | test/units/module_utils/facts/test_facts.py | {
"start": 6038,
"end": 6227
} | class ____(BaseTestFactsPlatform):
platform_id = 'OpenBSD'
fact_class = network.openbsd.OpenBSDNetwork
collector_class = network.openbsd.OpenBSDNetworkCollector
| TestOpenBSDNetwork |
python | falconry__falcon | tests/test_cookies.py | {
"start": 2632,
"end": 17856
} | class ____:
def on_get(self, req, resp):
# change lax to strict
resp.unset_cookie('foo', same_site='Strict')
# change strict to lax
resp.unset_cookie('bar')
# change none to ''
resp.unset_cookie('baz', same_site='')
# change '' to none
resp.unset_cooki... | CookieUnsetSameSite |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_ps.py | {
"start": 31727,
"end": 51625
} | class ____(FigureCanvasBase):
fixed_dpi = 72
filetypes = {'ps': 'Postscript',
'eps': 'Encapsulated Postscript'}
def get_default_filetype(self):
return 'ps'
def _print_ps(
self, fmt, outfile, *,
metadata=None, papertype=None, orientation='portrait',
... | FigureCanvasPS |
python | spack__spack | lib/spack/spack/test/error_messages.py | {
"start": 3190,
"end": 3440
} | class ____(Package):
version("2.1")
version("2.0")
variant("v1", default=True)
depends_on("t2")
depends_on("t2@:2.0", when="@:2.0")
depends_on("t3")
depends_on("t3~v1", when="@2.0")
""",
)
_pkgt3 = (
"t3",
"""\
| T4 |
python | plotly__plotly.py | plotly/graph_objs/layout/ternary/caxis/_title.py | {
"start": 235,
"end": 2875
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.ternary.caxis"
_path_str = "layout.ternary.caxis.title"
_valid_props = {"font", "text"}
@property
def font(self):
"""
Sets this axis' title font.
The 'font' property is an instance of Font
that may be ... | Title |
python | PrefectHQ__prefect | tests/cli/test_api_command.py | {
"start": 15355,
"end": 16920
} | class ____:
"""Test edge cases and special scenarios."""
def test_invalid_http_method(self, respx_mock: MockRouter) -> None:
"""Test invalid HTTP method shows helpful error."""
with temporary_settings({PREFECT_API_URL: "http://localhost:4200/api"}):
result = invoke_and_assert(
... | TestEdgeCases |
python | matplotlib__matplotlib | lib/matplotlib/transforms.py | {
"start": 88413,
"end": 89616
} | class ____(Affine2DBase):
"""
`BboxTransformTo` is a transformation that linearly transforms points from
the unit bounding box to a given `Bbox`.
"""
is_separable = True
def __init__(self, boxout, **kwargs):
"""
Create a new `BboxTransformTo` that linearly transforms
po... | BboxTransformTo |
python | huggingface__transformers | src/transformers/models/csm/processing_csm.py | {
"start": 1169,
"end": 1271
} | class ____(AudioKwargs, total=False):
encoded_length_kwargs: Optional[dict[str, Any]]
| CsmAudioKwargs |
python | dagster-io__dagster | python_modules/dagster/dagster/_utils/concurrency.py | {
"start": 1607,
"end": 1778
} | class ____:
run_id: str
step_key: str
enqueued_timestamp: datetime
assigned_timestamp: Optional[datetime]
priority: Optional[int]
@record
| PendingStepInfo |
python | numba__numba | numba/tests/test_support.py | {
"start": 13232,
"end": 14139
} | class ____(TestCase):
def test_assertRefCount(self):
# Use objects to avoid interning
x = object()
y = object()
l = []
with self.assertRefCount(x, y):
pass
with self.assertRaises(AssertionError) as cm:
# y gains a reference
with se... | TestMisc |
python | doocs__leetcode | solution/1300-1399/1399.Count Largest Group/Solution.py | {
"start": 0,
"end": 414
} | class ____:
def countLargestGroup(self, n: int) -> int:
cnt = Counter()
ans = mx = 0
for i in range(1, n + 1):
s = 0
while i:
s += i % 10
i //= 10
cnt[s] += 1
if mx < cnt[s]:
mx = cnt[s]
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/minimum-runes-to-add-to-cast-spell.py | {
"start": 1225,
"end": 2054
} | class ____(object):
def minRunesToAdd(self, n, crystals, flowFrom, flowTo):
"""
:type n: int
:type crystals: List[int]
:type flowFrom: List[int]
:type flowTo: List[int]
:rtype: int
"""
adj = [[] for _ in xrange(n)]
for i in xrange(len(flowFrom)... | Solution |
python | pytorch__pytorch | test/distributed/test_functional_api.py | {
"start": 6309,
"end": 9105
} | class ____(MultiThreadedTestCase):
@property
def world_size(self):
return 4
def setUp(self):
super().setUp()
self._spawn_threads()
"""
The behavior we want is as follow:
- rankset+tag will always result in the same PG.
Do we enforce this by failing creation of new ... | TestPgTag |
python | altair-viz__altair | altair/vegalite/v6/api.py | {
"start": 30073,
"end": 32407
} | class ____(_BaseWhen):
"""
Utility class for ``when-then-otherwise`` conditions.
Represents the state after calling :func:`.when()`.
This partial state requires calling :meth:`When.then()` to finish the condition.
References
----------
`polars.when <https://docs.pola.rs/py-polars/html/ref... | When |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol22.py | {
"start": 1126,
"end": 1211
} | class ____(Protocol[_T1, _T2]):
def m2(self, a: _T1 | _T2) -> tuple[_T1, _T2]: ...
| P4 |
python | doocs__leetcode | solution/0300-0399/0343.Integer Break/Solution2.py | {
"start": 0,
"end": 258
} | class ____:
def integerBreak(self, n: int) -> int:
if n < 4:
return n - 1
if n % 3 == 0:
return pow(3, n // 3)
if n % 3 == 1:
return pow(3, n // 3 - 1) * 4
return pow(3, n // 3) * 2
| Solution |
python | pytest-dev__pytest-xdist | src/xdist/scheduler/loadgroup.py | {
"start": 131,
"end": 2273
} | class ____(LoadScopeScheduling):
"""Implement load scheduling across nodes, but grouping test by xdist_group mark.
This class behaves very much like LoadScopeScheduling, but it groups tests by xdist_group mark
instead of the module or class to which they belong to.
"""
def __init__(self, config: p... | LoadGroupScheduling |
python | walkccc__LeetCode | solutions/972. Equal Rational Numbers/972.py | {
"start": 0,
"end": 825
} | class ____:
def isRationalEqual(self, s: str, t: str) -> bool:
ratios = [1, 1 / 9, 1 / 99, 1 / 999, 1 / 9999]
def valueOf(s: str) -> float:
if s.find('(') == -1:
return float(s)
# Get the indices.
leftParenIndex = s.find('(')
rightParenIndex = s.find(')')
dotIndex = s.f... | Solution |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/operators/test_bedrock.py | {
"start": 1652,
"end": 2959
} | class ____:
MODEL_ID = "meta.llama2-13b-chat-v1"
TEST_PROMPT = "A very important question."
GENERATED_RESPONSE = "An important answer."
@pytest.fixture
def mock_runtime_conn(self) -> Generator[BaseAwsConnection, None, None]:
with mock.patch.object(BedrockRuntimeHook, "conn") as _conn:
... | TestBedrockInvokeModelOperator |
python | doocs__leetcode | solution/1500-1599/1548.The Most Similar Path in a Graph/Solution.py | {
"start": 0,
"end": 969
} | class ____:
def mostSimilar(
self, n: int, roads: List[List[int]], names: List[str], targetPath: List[str]
) -> List[int]:
g = [[] for _ in range(n)]
for a, b in roads:
g[a].append(b)
g[b].append(a)
m = len(targetPath)
f = [[inf] * n for _ in range... | Solution |
python | apache__airflow | providers/microsoft/azure/tests/unit/microsoft/azure/operators/test_wasb_delete_blob.py | {
"start": 999,
"end": 2386
} | class ____:
_config = {
"container_name": "container",
"blob_name": "blob",
}
def setup_method(self):
args = {"owner": "airflow", "start_date": datetime.datetime(2017, 1, 1)}
self.dag = DAG("test_dag_id", schedule=None, default_args=args)
def test_init(self):
op... | TestWasbDeleteBlobOperator |
python | getsentry__sentry | tests/sentry/seer/explorer/test_tools.py | {
"start": 51540,
"end": 59580
} | class ____(APITestCase, SpanTestCase, SnubaTestCase):
def setUp(self):
super().setUp()
self.ten_mins_ago = before_now(minutes=10)
@patch("sentry.seer.explorer.tools._convert_profile_to_execution_tree")
@patch("sentry.seer.explorer.tools.fetch_profile_data")
def test_rpc_get_profile_flam... | TestRpcGetProfileFlamegraph |
python | tensorflow__tensorflow | tensorflow/python/feature_column/feature_column_v2_test.py | {
"start": 56560,
"end": 94100
} | class ____(test.TestCase):
def test_raises_if_empty_feature_columns(self):
with self.assertRaisesRegex(ValueError,
'feature_columns must not be empty'):
fc_old.linear_model(features={}, feature_columns=[])
def test_should_be_feature_column(self):
with self.assertRaise... | OldLinearModelTest |
python | yaml__pyyaml | lib/yaml/tokens.py | {
"start": 1359,
"end": 1410
} | class ____(Token):
id = '['
| FlowSequenceStartToken |
python | python-attrs__attrs | typing-examples/baseline.py | {
"start": 1160,
"end": 1556
} | class ____:
num: int | str = attrs.field(
validator=attrs.validators.or_(
# Various types of validators.
attrs.validators.ge(0),
attrs.validators.instance_of(str),
)
)
attrs.validators.set_disabled(True)
attrs.validators.set_disabled(False)
with attrs.vali... | ValidatedInconsistentOr |
python | getsentry__sentry | tests/sentry/projects/project_rules/test_creator.py | {
"start": 614,
"end": 3598
} | class ____(TestCase):
def setUp(self) -> None:
self.user = self.create_user()
self.org = self.create_organization(name="bloop", owner=self.user)
self.project = self.create_project(
teams=[self.create_team()], name="foo", fire_project_created=True
)
self.creator =... | TestProjectRuleCreator |
python | ray-project__ray | python/ray/serve/tests/test_healthcheck.py | {
"start": 655,
"end": 8831
} | class ____:
def __init__(self):
self.healthy = True
self.should_hang = False
def check_health(self):
if self.should_hang:
import time
time.sleep(10000)
elif not self.healthy:
raise Exception("intended to fail")
def __call__(self, *args):... | Patient |
python | getsentry__sentry | src/sentry/preprod/size_analysis/models.py | {
"start": 1141,
"end": 1300
} | class ____(BaseModel):
size_diff: int
head_size: int | None
base_size: int | None
path: str
item_type: str | None
type: DiffType
| DiffItem |
python | django__django | django/contrib/auth/migrations/0012_alter_user_first_name_max_length.py | {
"start": 43,
"end": 411
} | class ____(migrations.Migration):
dependencies = [
("auth", "0011_update_proxy_permissions"),
]
operations = [
migrations.AlterField(
model_name="user",
name="first_name",
field=models.CharField(
blank=True, max_length=150, verbose_name="f... | Migration |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-facebook-marketing/unit_tests/test_config_migrations.py | {
"start": 13960,
"end": 15577
} | class ____:
OLD_TEST_CONFIG = _config_path(f"{_MIGRATE_DEFAULT_ACTION_BREAKDOWNS_CONFIGS_PATH}/test_old_config.json")
NEW_TEST_CONFIG = _config_path(f"{_MIGRATE_DEFAULT_ACTION_BREAKDOWNS_CONFIGS_PATH}/test_new_config.json")
@staticmethod
def revert_migration(config_path: str) -> None:
with open... | TestMigrateDefaultActionBreakdowns |
python | mlflow__mlflow | mlflow/genai/optimize/types.py | {
"start": 3468,
"end": 4127
} | class ____:
"""
The output type of `eval_fn` in the
:py:func:`mlflow.genai.optimize.BasePromptOptimizer.optimize()` API.
Args:
inputs: The inputs of the evaluation.
outputs: The outputs of the prediction function.
expectations: The expected outputs.
score: The score of t... | EvaluationResultRecord |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/array_ops_test.py | {
"start": 39302,
"end": 40784
} | class ____(object):
"""Tests that we can compute a gradient for var^2."""
def __init__(self, test, var, varnp, use_tape):
self.test = test
self.var = var
self.varnp = varnp
self.use_tape = use_tape
def __getitem__(self, spec):
with test_util.AbstractGradientTape(
use_tape=self.use_ta... | GradSliceChecker |
python | pytorch__pytorch | test/test_fx_experimental.py | {
"start": 67483,
"end": 71575
} | class ____(JitTestCase):
@onlyCPU
@ops(op_db, allowed_dtypes=(torch.float,))
def test_normalize_operator_exhaustive(self, device, dtype, op):
# These ops currently don't trace in FX for various reasons (i.e. they take a list of tensors)
fx_fail = {"cat", "stack", "hstack", "vstack", "dstack"... | TestNormalizeOperators |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 108359,
"end": 109111
} | class ____(TypeDecorator):
# previous workaround for array of enum
impl = postgresql.ARRAY
cache_ok = True
# note expanding logic is checking _is_array here so that has to
# translate through the TypeDecorator
def bind_expression(self, bindvalue):
return sa.cast(bindvalue, self)
d... | _ArrayOfEnum |
python | readthedocs__readthedocs.org | readthedocs/config/models.py | {
"start": 2828,
"end": 3022
} | class ____(ConfigBaseModel):
ranking: dict[str, int] = {}
ignore: list[str] = [
"search.html",
"search/index.html",
"404.html",
"404/index.html",
]
| Search |
python | huggingface__transformers | src/transformers/models/efficientloftr/modeling_efficientloftr.py | {
"start": 19975,
"end": 22203
} | class ____(nn.Module):
def __init__(self, config: EfficientLoFTRConfig, layer_idx: int):
super().__init__()
self.q_aggregation_kernel_size = config.q_aggregation_kernel_size
self.aggregation = EfficientLoFTRAggregationLayer(config)
self.attention = EfficientLoFTRAttention(config, la... | EfficientLoFTRAggregatedAttention |
python | ansible__ansible | .azure-pipelines/scripts/publish-codecov.py | {
"start": 539,
"end": 657
} | class ____:
name: str
path: pathlib.Path
flags: t.List[str]
@dataclasses.dataclass(frozen=True)
| CoverageFile |
python | getsentry__sentry | src/sentry/models/organizationmember.py | {
"start": 3488,
"end": 6947
} | class ____(BaseManager["OrganizationMember"]):
def get_contactable_members_for_org(self, organization_id: int) -> QuerySet:
"""Get a list of members we can contact for an organization through email."""
# TODO(Steve): check member-limit:restricted
return self.filter(
organization_... | OrganizationMemberManager |
python | sqlalchemy__sqlalchemy | test/sql/test_external_traversal.py | {
"start": 10817,
"end": 13154
} | class ____(fixtures.TestBase):
"""test the special binary product visit"""
def _assert_traversal(self, expr, expected):
canary = []
def visit(binary, l, r):
canary.append((binary.operator, l, r))
print(binary.operator, l, r)
sql_util.visit_binary_product(visit,... | BinaryEndpointTraversalTest |
python | python-openxml__python-docx | src/docx/enum/text.py | {
"start": 5370,
"end": 6394
} | class ____(BaseXmlEnum):
"""Specifies the tab stop alignment to apply.
MS API name: `WdTabAlignment`
URL: https://msdn.microsoft.com/EN-US/library/office/ff195609.aspx
"""
LEFT = (0, "left", "Left-aligned.")
"""Left-aligned."""
CENTER = (1, "center", "Center-aligned.")
"""Center-alig... | WD_TAB_ALIGNMENT |
python | getsentry__sentry | src/sentry/issues/grouptype.py | {
"start": 15160,
"end": 15571
} | class ____(GroupType):
type_id = 1911
slug = "performance_m_n_plus_one_db_queries_experimental"
description = "MN+1 Query (Experimental)"
category = GroupCategory.PERFORMANCE.value
category_v2 = GroupCategory.DB_QUERY.value
noise_config = NoiseConfig()
default_priority = PriorityLevel.LOW
... | PerformanceMNPlusOneDBQueriesExperimentalGroupType |
python | getsentry__sentry | src/sentry/integrations/discord/webhooks/command.py | {
"start": 2712,
"end": 5966
} | class ____(MessagingIntegrationCommandDispatcher[str]):
request: DiscordRequest
@property
def integration_spec(self) -> MessagingIntegrationSpec:
return DiscordMessagingSpec()
def help_handler(self, input: CommandInput) -> IntegrationResponse[str]:
return IntegrationResponse(
... | DiscordCommandDispatcher |
python | viewflow__viewflow | viewflow/workflow/flow/views/actions.py | {
"start": 445,
"end": 1087
} | class ____(
mixins.SuccessMessageMixin,
mixins.TaskSuccessUrlMixin,
mixins.TaskViewTemplateNames,
generic.FormView,
):
"""
Default assign view for flow task.
Get confirmation from user, assigns task and redirects to task pages
"""
form_class = forms.Form
template_filename = "ta... | AssignTaskView |
python | Delgan__loguru | loguru/_string_parsers.py | {
"start": 63,
"end": 9324
} | class ____:
"""Provide static methods to compute the next occurrence of various time frequencies.
Includes hourly, daily, weekly, monthly, and yearly frequencies
based on a given datetime object.
"""
@staticmethod
def hourly(t: datetime.datetime) -> datetime.datetime:
"""Compute the ne... | Frequencies |
python | jupyterlab__jupyterlab | jupyterlab/labextensions.py | {
"start": 5851,
"end": 7413
} | class ____(BaseExtensionApp):
description = """Install labextension(s)
Usage
jupyter labextension install [--pin-version-as <alias,...>] <package...>
This installs JupyterLab extensions similar to yarn add or npm install.
Pass a list of comma separate names to the --pin-version-as flag
... | InstallLabExtensionApp |
python | kubernetes-client__python | kubernetes/client/models/v1_container_image.py | {
"start": 383,
"end": 4498
} | 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... | V1ContainerImage |
python | fluentpython__example-code-2e | 21-async/mojifinder/bottle.py | {
"start": 58878,
"end": 68791
} | class ____(object):
""" Storage class for a response body as well as headers and cookies.
This class does support dict-like case-insensitive item-access to
headers, but is NOT a dict. Most notably, iterating over a response
yields parts of the body and not the headers.
:param body:... | BaseResponse |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/ddl.py | {
"start": 14746,
"end": 14941
} | class ____(_CreateDropBase[_SI]):
def __init__(self, element: _SI, if_not_exists: bool = False) -> None:
super().__init__(element)
self.if_not_exists = if_not_exists
| _CreateBase |
python | plotly__plotly.py | plotly/graph_objs/sunburst/marker/colorbar/title/_font.py | {
"start": 233,
"end": 9954
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "sunburst.marker.colorbar.title"
_path_str = "sunburst.marker.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
... | Font |
python | jazzband__django-formtools | tests/wizard/test_forms.py | {
"start": 1300,
"end": 1522
} | class ____(forms.ModelForm):
class Meta:
model = TestModel
fields = '__all__'
TestModelFormSet = forms.models.modelformset_factory(TestModel, form=TestModelForm, extra=2, fields='__all__')
| TestModelForm |
python | kamyu104__LeetCode-Solutions | Python/detect-cycles-in-2d-grid.py | {
"start": 56,
"end": 521
} | class ____(object):
def __init__(self, n):
self.set = range(n)
self.count = n
def find_set(self, x):
if self.set[x] != x:
self.set[x] = self.find_set(self.set[x]) # path compression.
return self.set[x]
def union_set(self, x, y):
x_root, y_root = map(self.f... | UnionFind |
python | getsentry__sentry | tests/sentry/api/bases/test_organization.py | {
"start": 13783,
"end": 14835
} | class ____(TestCase):
@cached_property
def endpoint(self):
return OrganizationEndpoint()
@cached_property
def user(self):
return self.create_user("tester@test.com")
@cached_property
def member(self):
return self.create_user("member@test.com")
@cached_property
d... | BaseOrganizationEndpointTest |
python | jazzband__django-waffle | waffle/tests/test_models.py | {
"start": 188,
"end": 1461
} | class ____(TestCase):
def test_natural_keys(self):
flag = get_waffle_flag_model().objects.create(name='test-flag')
switch = get_waffle_switch_model().objects.create(name='test-switch')
sample = get_waffle_sample_model().objects.create(name='test-sample', percent=0)
self.assertEqual(... | ModelsTests |
python | dagster-io__dagster | python_modules/libraries/dagster-gcp/dagster_gcp/bigquery/types.py | {
"start": 3265,
"end": 3686
} | class ____(ConfigScalar):
def __init__(self):
super().__init__(
key=type(self).__name__,
given_name=type(self).__name__,
scalar_kind=ConfigScalarKind.STRING,
)
def post_process(self, value):
if not _is_valid_dataset(value):
raise PostProce... | _Dataset |
python | apache__airflow | providers/google/tests/unit/google/common/hooks/test_base_google.py | {
"start": 3723,
"end": 5013
} | class ____:
@pytest.mark.parametrize(
("exc", "retryable"),
[
(RefreshError("Other error", "test body"), False),
(RefreshError("Unable to acquire impersonated credentials", "test body"), True),
(ValueError(), False),
],
)
def test_is_refresh_creden... | TestRefreshCredentialsRetry |
python | vyperlang__vyper | vyper/abi_types.py | {
"start": 4505,
"end": 5133
} | class ____(ABIType):
def __init__(self, bytes_bound):
if not bytes_bound >= 0:
raise InvalidABIType("Negative bytes_bound provided to ABI_Bytes")
self.bytes_bound = bytes_bound
def is_dynamic(self):
return True
# note that static_size for dynamic types is always 0
... | ABI_Bytes |
python | apache__airflow | providers/cncf/kubernetes/src/airflow/providers/cncf/kubernetes/callbacks.py | {
"start": 1181,
"end": 1295
} | class ____(str, Enum):
"""Enum class for execution mode."""
SYNC = "sync"
ASYNC = "async"
| ExecutionMode |
python | google__pytype | pytype/overlays/special_builtins.py | {
"start": 26165,
"end": 26778
} | class ____(BuiltinClass):
"""Static method decorator."""
# Minimal signature, only used for constructing exceptions.
_SIGNATURE = function.Signature.from_param_names("staticmethod", ("func",))
_NAME = "staticmethod"
def call(self, node, func, args, alias_map=None):
if len(args.posargs) != 1:
raise... | StaticMethod |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 11281,
"end": 11559
} | class ____(str, Enum):
"""
Class with TriggeredBy types for DagRun.
"""
CLI = "cli"
OPERATOR = "operator"
REST_API = "rest_api"
UI = "ui"
TEST = "test"
TIMETABLE = "timetable"
ASSET = "asset"
BACKFILL = "backfill"
| DagRunTriggeredByType |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/io_management/input_managers.py | {
"start": 5470,
"end": 5983
} | class ____(MyIOManager):
def load_input(self, context: dg.InputContext):
if context.upstream_output is None:
# load input from table since there is no upstream output
return read_dataframe_from_table(name="table_1")
else:
return super().load_input(context)
# end... | MyNewInputLoader |
python | huggingface__transformers | src/transformers/models/splinter/modeling_splinter.py | {
"start": 25340,
"end": 26459
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when start and end positions are provided):
Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
start_logits (`torch.FloatTensor` of shape `(batch_size, num_questions, ... | SplinterForPreTrainingOutput |
python | getsentry__sentry | src/sentry/auth/services/auth/model.py | {
"start": 6125,
"end": 7313
} | class ____(RpcModel):
id: int = -1
organization_id: int = -1
provider: str = ""
flags: RpcAuthProviderFlags = Field(default_factory=lambda: RpcAuthProviderFlags())
config: dict[str, Any]
default_role: int = -1
default_global_access: bool = False
def __hash__(self) -> int:
return... | RpcAuthProvider |
python | kamyu104__LeetCode-Solutions | Python/rearrange-words-in-a-sentence.py | {
"start": 33,
"end": 327
} | class ____(object):
def arrangeWords(self, text):
"""
:type text: str
:rtype: str
"""
result = text.split()
result[0] = result[0].lower()
result.sort(key=len)
result[0] = result[0].title()
return " ".join(result)
| Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/callbacks/base_handler.py | {
"start": 317,
"end": 1664
} | class ____(ABC):
"""Base callback handler that can be used to track event starts and ends."""
def __init__(
self,
event_starts_to_ignore: List[CBEventType],
event_ends_to_ignore: List[CBEventType],
) -> None:
"""Initialize the base callback handler."""
self.event_sta... | BaseCallbackHandler |
python | getsentry__sentry | tests/sentry/core/endpoints/test_organization_member_details.py | {
"start": 1303,
"end": 1497
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-member-details"
def setUp(self) -> None:
super().setUp()
self.login_as(self.user)
| OrganizationMemberTestBase |
python | pandas-dev__pandas | pandas/tests/frame/indexing/test_indexing.py | {
"start": 638,
"end": 52559
} | class ____:
def test_getitem(self, float_frame):
# Slicing
sl = float_frame[:20]
assert len(sl.index) == 20
# Column access
for _, series in sl.items():
assert len(series.index) == 20
tm.assert_index_equal(series.index, sl.index)
for key, _ i... | TestDataFrameIndexing |
python | fastapi__sqlmodel | tests/test_enums_models.py | {
"start": 64,
"end": 121
} | class ____(str, enum.Enum):
A = "A"
B = "B"
| MyEnum1 |
python | getsentry__sentry | tests/sentry/deletions/test_file.py | {
"start": 325,
"end": 5494
} | class ____(TestCase):
def test_get_query_filter_orphaned_release_file(self) -> None:
"""Test that orphaned release.file type Files are selected for deletion"""
project = self.create_project()
self.create_release(project=project)
# Create an orphaned release.file (no ReleaseFile poin... | FileDeletionTaskTest |
python | davidhalter__jedi | test/refactor/extract_function.py | {
"start": 8278,
"end": 8629
} | class ____:
# comment
def ab(self, b):
#foo
local1 = 3
local2 = 4
return local1 * glob1 * b
# bar
def f(self, b, c):
#? 11 text {'new_name': 'ab', 'until_line': 11, 'until_column': 10}
return self.ab(b)
# ---------------------------------------------... | X |
python | walkccc__LeetCode | solutions/2145. Count the Hidden Sequences/2145-2.py | {
"start": 0,
"end": 352
} | class ____:
def numberOfArrays(
self,
differences: list[int],
lower: int,
upper: int,
) -> int:
prefix = 0
mn = 0 # Starts from 0.
mx = 0 # Starts from 0.
for d in differences:
prefix += d
mn = min(mn, prefix)
mx = max(mx, prefix)
return max(0, (uppe... | Solution |
python | allegroai__clearml | clearml/backend_api/services/v2_13/events.py | {
"start": 68537,
"end": 72410
} | class ____(Request):
"""
Scroll through task events, sorted by timestamp
:param task: Task ID
:type task: str
:param order: 'asc' (default) or 'desc'.
:type order: str
:param scroll_id: Pass this value on next call to get next page
:type scroll_id: str
:param batch_size: Number of e... | GetTaskEventsRequest |
python | pennersr__django-allauth | tests/apps/account/test_logout.py | {
"start": 947,
"end": 2245
} | class ____(TestCase):
@override_settings(ACCOUNT_LOGOUT_ON_GET=True)
def test_logout_view_on_get(self):
c, resp = self._logout_view("get")
self.assertTemplateUsed(resp, "account/messages/logged_out.txt")
@override_settings(ACCOUNT_LOGOUT_ON_GET=False)
def test_logout_view_on_post(self):... | LogoutTests |
python | getsentry__sentry | tests/sentry/identity/test_oauth2.py | {
"start": 930,
"end": 6297
} | class ____(TestCase):
def setUp(self) -> None:
sentry.identity.register(DummyProvider)
super().setUp()
self.request = RequestFactory().get("/")
self.request.subdomain = None
def tearDown(self) -> None:
super().tearDown()
sentry.identity.unregister(DummyProvider)
... | OAuth2CallbackViewTest |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_django/DJ008.py | {
"start": 3576,
"end": 3827
} | class ____(models.Model):
"""Model with type-annotated abstract = True - should not trigger DJ008"""
new_field = models.CharField(max_length=10)
class Meta(TypedModelMeta):
abstract: ClassVar[bool] = True
| TypeAnnotatedAbstractModel1 |
python | walkccc__LeetCode | solutions/2939. Maximum Xor Product/2939.py | {
"start": 0,
"end": 289
} | class ____:
def maximumXorProduct(self, a: int, b: int, n: int) -> int:
MOD = 1_000_000_007
for bit in (2**i for i in range(n)):
# Pick a bit if it makes min(a, b) larger.
if a * b < (a ^ bit) * (b ^ bit):
a ^= bit
b ^= bit
return a * b % MOD
| Solution |
python | gevent__gevent | src/gevent/tests/test__backdoor.py | {
"start": 755,
"end": 1697
} | class ____(socket.socket):
__slots__ = ('banner',)
def __init__(self, *args, **kwargs):
self.banner = None
super(SocketWithBanner, self).__init__(*args, **kwargs)
def __enter__(self):
return socket.socket.__enter__(self)
def __exit__(self, t, v, tb):
return socket.sock... | SocketWithBanner |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.