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 | django__django | tests/gis_tests/distapp/tests.py | {
"start": 15601,
"end": 31346
} | class ____(FuncTestMixin, TestCase):
fixtures = ["initial"]
@skipUnlessDBFeature("has_Area_function")
def test_area(self):
# Reference queries:
# SELECT ST_Area(poly) FROM distapp_southtexaszipcode;
area_sq_m = [
5437908.90234375,
10183031.4389648,
... | DistanceFunctionsTests |
python | allegroai__clearml | clearml/backend_api/services/v2_13/queues.py | {
"start": 65078,
"end": 67441
} | class ____(Request):
"""
Moves a task entry one step forward towards the top of the queue.
:param queue: Queue id
:type queue: str
:param task: Task id
:type task: str
:param count: Number of positions in the queue to move the task forward
relative to the current position. Optional,... | MoveTaskForwardRequest |
python | getsentry__sentry | tests/sentry/notifications/api/endpoints/test_user_notification_details.py | {
"start": 1259,
"end": 1818
} | class ____(UserNotificationDetailsTestBase):
method = "put"
def test_saves_and_returns_values(self) -> None:
org = self.create_organization()
self.create_member(user=self.user, organization=org)
data = {
"personalActivityNotifications": True,
"selfAssignOnResolve... | UserNotificationDetailsPutTest |
python | getsentry__sentry | src/sentry/models/deletedteam.py | {
"start": 185,
"end": 1055
} | class ____(DeletedEntry):
"""
This model tracks an intent to delete. If an org is marked pending_delete
through the UI, a deletedteam is created to log this deletion.
This model does not account for aborted or failed deletions and is currently
unable to log deletions that occur implicitly (i.e. whe... | DeletedTeam |
python | getsentry__sentry | tests/sentry_plugins/github/test_provider.py | {
"start": 6300,
"end": 9549
} | class ____(TestCase):
@cached_property
def provider(self) -> GitHubAppsRepositoryProvider:
return GitHubAppsRepositoryProvider("github_apps")
@patch.object(
GithubPluginAppsClient,
"get_repositories",
return_value=orjson.loads(INSTALLATION_REPOSITORIES_API_RESPONSE),
)
... | GitHubAppsProviderTest |
python | pytorch__pytorch | torch/utils/_pytree.py | {
"start": 23760,
"end": 23988
} | class ____(Generic[K, T]):
key: K
def __str__(self) -> str:
return f"[{self.key!r}]"
def get(self, mapping: Mapping[K, T]) -> T:
return mapping[self.key]
@dataclasses.dataclass(frozen=True)
| MappingKey |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI059.py | {
"start": 1585,
"end": 1647
} | class ____(Generic[T], str, metaclass=type): # PYI059
...
| C2 |
python | pandas-dev__pandas | pandas/tests/indexing/test_iloc.py | {
"start": 45367,
"end": 47198
} | class ____:
# NB: this test should work for _any_ Series we can pass as
# series_with_simple_index
def test_iloc_float_raises(self, series_with_simple_index, frame_or_series):
# GH#4892
# float_indexers should raise exceptions
# on appropriate Index types & accessors
# this ... | TestILocErrors |
python | kamyu104__LeetCode-Solutions | Python/number-of-flowers-in-full-bloom.py | {
"start": 85,
"end": 674
} | class ____(object):
def fullBloomFlowers(self, flowers, persons):
"""
:type flowers: List[List[int]]
:type persons: List[int]
:rtype: List[int]
"""
cnt = collections.Counter()
for s, e in flowers:
cnt[s] += 1
cnt[e+1] -= 1
event... | Solution |
python | Lightning-AI__lightning | tests/tests_pytorch/loops/test_loops.py | {
"start": 45954,
"end": 46213
} | class ____:
def __init__(self, start=0):
self.index = start
def __iter__(self):
for i in range(self.index, len(self)):
self.index = i
yield self.index
def __len__(self):
return 10
| NotStatefulIterable |
python | getsentry__sentry | tests/sentry/models/test_projecttemplate.py | {
"start": 104,
"end": 666
} | class ____(TestCase):
def setUp(self) -> None:
self.org = self.create_organization()
def tearDown(self) -> None:
self.org.delete()
def test_create_simple_project_template(self) -> None:
project_template = ProjectTemplate.objects.create(
name="test_project_template", org... | ProjectTemplateTest |
python | Pylons__pyramid | tests/test_scripts/test_pdistreport.py | {
"start": 1930,
"end": 2155
} | class ____:
def __init__(self, name):
self.version = '1'
self.metadata = email.message.Message()
self.metadata['Name'] = name
self.metadata['Summary'] = f'summary for {name=}'
| DummyDistribution |
python | allegroai__clearml | clearml/utilities/pigar/reqs.py | {
"start": 3619,
"end": 19663
} | class ____(object):
def __init__(self, fpath: str, lineno: int) -> None:
self._fpath = fpath
self._lineno = lineno - 1
self._modules = ImportedModules()
self._str_codes = collections.deque()
self._try_imports = set()
def visit_Import(self, node: ast.Import, try_: bool = ... | ImportChecker |
python | huggingface__transformers | src/transformers/models/nystromformer/modeling_nystromformer.py | {
"start": 16333,
"end": 17055
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = NystromformerPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.h... | NystromformerLMPredictionHead |
python | protocolbuffers__protobuf | objectivec/DevTools/pddm.py | {
"start": 4365,
"end": 11565
} | class ____(object):
"""Hold a set of macros and can resolve/expand them."""
def __init__(self, a_file=None):
"""Initializes the collection.
Args:
a_file: The file like stream to parse.
Raises:
PDDMError if there are any issues.
"""
self._macros = dict()
if a_file:
self.P... | MacroCollection |
python | allegroai__clearml | clearml/backend_api/services/v2_9/projects.py | {
"start": 53338,
"end": 54213
} | class ____(Request):
"""
:param project: Project id
:type project: str
"""
_service = "projects"
_action = "get_by_id"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {"project": {"description": "Project id", "type": "string"}},
"required": ["projec... | GetByIdRequest |
python | davidhalter__jedi | jedi/api/__init__.py | {
"start": 28824,
"end": 32428
} | class ____(Script):
"""
Jedi's API for Python REPLs.
Implements all of the methods that are present in :class:`.Script` as well.
In addition to completions that normal REPL completion does like
``str.upper``, Jedi also supports code completion based on static code
analysis. For example Jedi wi... | Interpreter |
python | keon__algorithms | tests/test_maths.py | {
"start": 12099,
"end": 12500
} | class ____(unittest.TestCase):
"""[summary]
Test for the file find_order_simple.py
Arguments:
unittest {[type]} -- [description]
"""
def test_find_order_simple(self):
self.assertEqual(1, find_order(1, 1))
self.assertEqual(6, find_order(3, 7))
self.assertEqual(-1, fi... | TestFindOrder |
python | pytorch__pytorch | test/distributed/test_c10d_common.py | {
"start": 81852,
"end": 82995
} | class ____(MultiProcessTestCase):
@property
def world_size(self):
return 4
def setUp(self):
super().setUp()
self._spawn_processes()
def tearDown(self):
super().tearDown()
try:
os.remove(self.file_name)
except OSError:
pass
de... | LocalRankTest |
python | walkccc__LeetCode | solutions/137. Single Number II/137.py | {
"start": 0,
"end": 183
} | class ____:
def singleNumber(self, nums: list[int]) -> int:
ones = 0
twos = 0
for num in nums:
ones ^= num & ~twos
twos ^= num & ~ones
return ones
| Solution |
python | django__django | tests/forms_tests/tests/test_formsets.py | {
"start": 72088,
"end": 72214
} | class ____(Form):
title = CharField()
pub_date = DateField()
ArticleFormSet = formset_factory(ArticleForm)
| ArticleForm |
python | pypa__pip | src/pip/_vendor/urllib3/contrib/securetransport.py | {
"start": 12361,
"end": 29652
} | class ____(object):
"""
API-compatibility wrapper for Python's OpenSSL wrapped socket object.
Note: _makefile_refs, _drop(), and _reuse() are needed for the garbage
collector of PyPy.
"""
def __init__(self, socket):
self.socket = socket
self.context = None
self._makefil... | WrappedSocket |
python | pytorch__pytorch | test/fx/quantization.py | {
"start": 7291,
"end": 12814
} | class ____:
def __init__(
self, mod, patterns=_DEFAULT_QUANTIZATION_PATTERNS, quant_ctor=DefaultQuant
):
self.root = mod
self.graph = mod.graph
self.quant_ctor = quant_ctor
# cached information for observe
self.state_dict = self.root.state_dict()
self.mod... | Quantizer |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 104197,
"end": 104750
} | class ____(SendrecvmsgBase):
# Base class for tests on connectionless-mode sockets. Users must
# supply sockets on attributes cli and serv to be mapped to
# cli_sock and serv_sock respectively.
@property
def serv_sock(self):
return self.serv
@property
def cli_sock(self):
r... | SendrecvmsgConnectionlessBase |
python | getsentry__sentry | tests/sentry/integrations/gitlab/tasks/test_pr_comment.py | {
"start": 5046,
"end": 7586
} | class ____(GitlabCommentTestCase):
def test_simple(self) -> None:
"""one pr with one issue"""
commit = self.add_commit_to_repo(self.repo, self.user, self.project)
pr = self.add_pr_to_commit(commit)
groupowner = self.add_groupowner_to_commit(commit, self.project, self.user)
r... | TestPrToIssueQuery |
python | apache__airflow | airflow-ctl/src/airflowctl/api/datamodels/generated.py | {
"start": 72790,
"end": 73044
} | class ____(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
actions: Annotated[
list[BulkCreateActionPoolBody | BulkUpdateActionPoolBody | BulkDeleteActionPoolBody],
Field(title="Actions"),
]
| BulkBodyPoolBody |
python | pypa__warehouse | tests/unit/test_sessions.py | {
"start": 21407,
"end": 23965
} | class ____:
def test_has_options(self):
assert set(session_view.options) == {"uses_session"}
@pytest.mark.parametrize("uses_session", [False, None])
def test_invalid_session(self, uses_session):
context = pretend.stub()
request = pretend.stub(session=pretend.stub())
response... | TestSessionView |
python | python__mypy | mypy/stubutil.py | {
"start": 14977,
"end": 16098
} | class ____:
"""Abstract base class for extracting a list of FunctionSigs for each function."""
def remove_self_type(
self, inferred: list[FunctionSig] | None, self_var: str
) -> list[FunctionSig] | None:
"""Remove type annotation from self/cls argument"""
if inferred:
fo... | SignatureGenerator |
python | PrefectHQ__prefect | src/prefect/client/base.py | {
"start": 17095,
"end": 26895
} | class ____(httpx.Client):
"""
A Prefect wrapper for the async httpx client with support for retry-after headers
for the provided status codes (typically 429, 502 and 503).
Additionally, this client will always call `raise_for_status` on responses.
For more details on rate limit headers, see:
[... | PrefectHttpxSyncClient |
python | sympy__sympy | sympy/codegen/fnodes.py | {
"start": 18605,
"end": 18679
} | class ____(FFunction):
""" Fortran kind function. """
nargs = 1
| kind |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/components/creating-an-inline-component/asset-with-schedule-final.py | {
"start": 51,
"end": 600
} | class ____(dg.Component, dg.Model, dg.Resolvable):
asset_key: list[str]
cron_schedule: str
def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions:
@dg.asset(key=dg.AssetKey(self.asset_key))
def asset():
return randint(1, 100)
schedule = dg.ScheduleDefi... | AssetWithSchedule |
python | jazzband__django-simple-history | simple_history/tests/models.py | {
"start": 15945,
"end": 16154
} | class ____(models.Model):
name = models.CharField(max_length=30)
email = models.EmailField(max_length=255, unique=True)
register(ContactRegister, table_name="contacts_register_history")
| ContactRegister |
python | django__django | django/contrib/postgres/aggregates/general.py | {
"start": 910,
"end": 996
} | class ____(Aggregate):
function = "BOOL_OR"
output_field = BooleanField()
| BoolOr |
python | openai__openai-python | src/openai/resources/files.py | {
"start": 14032,
"end": 27045
} | class ____(AsyncAPIResource):
@cached_property
def with_raw_response(self) -> AsyncFilesWithRawResponse:
"""
This property can be used as a prefix for any HTTP method call to return
the raw response object instead of the parsed content.
For more information, see https://www.gith... | AsyncFiles |
python | pytorch__pytorch | test/test_autograd.py | {
"start": 379190,
"end": 392359
} | class ____(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return x.clone()
@staticmethod
def forward(ctx, gO):
return gO.clone()
def get_out():
inp = torch.rand(2, requires_grad=True)
# The python function is first so that it runs
# last in the backward pass
... | Foo |
python | doocs__leetcode | solution/3500-3599/3567.Minimum Absolute Difference in Sliding Submatrix/Solution.py | {
"start": 0,
"end": 590
} | class ____:
def minAbsDiff(self, grid: List[List[int]], k: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
ans = [[0] * (n - k + 1) for _ in range(m - k + 1)]
for i in range(m - k + 1):
for j in range(n - k + 1):
nums = []
for x in range(i,... | Solution |
python | django__django | tests/admin_views/test_adminsite.py | {
"start": 407,
"end": 782
} | class ____(admin.AdminSite):
site_title = "Custom title"
site_header = "Custom site"
custom_site = CustomAdminSite(name="test_custom_adminsite")
custom_site.register(User)
urlpatterns = [
path("test_admin/admin/", site.urls),
path("test_custom_admin/admin/", custom_site.urls),
]
@override_settings... | CustomAdminSite |
python | getsentry__sentry | tests/sentry/integrations/msteams/test_action_state_change.py | {
"start": 1262,
"end": 15989
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user(is_superuser=False)
owner = self.create_user()
self.org = self.create_organization(owner=owner)
self.team = self.create_team(organization=self.org, members=[self.user])
wit... | StatusActionTest |
python | PyCQA__pylint | tests/functional/a/assignment/assignment_from_no_return.py | {
"start": 306,
"end": 677
} | class ____:
def some_method(self):
pass
@decorate
def some_other_decorated_method(self):
pass
def some_other_method(self):
value = self.some_method() # [assignment-from-no-return]
other_value = self.some_other_decorated_method()
return value + other_value
VA... | Class |
python | falconry__falcon | tests/test_default_router.py | {
"start": 3677,
"end": 25146
} | class ____:
def __init__(self, times, eggs=False):
self._times = times
self._eggs = eggs
def convert(self, fragment):
item = fragment
if self._eggs:
item += '&eggs'
return ', '.join(item for i in range(self._times))
# ======================================... | SpamConverter |
python | google__jax | jax/_src/shard_map.py | {
"start": 51223,
"end": 52471
} | class ____(Exception):
pass
def _match_spec(mesh: Mesh, check_vma, manual_axes, src_pspec: PartitionSpec,
dst_pspec: PartitionSpec, x: JaxType) -> JaxType:
fn = HashablePartial(_match, mesh, check_vma, manual_axes, src_pspec,
dst_pspec)
with core.eval_context(), api.disable... | _RepError |
python | mlflow__mlflow | tests/gateway/tools.py | {
"start": 519,
"end": 2625
} | class ____:
def __init__(self, config_path: str | Path, *args, **kwargs):
self.port = get_safe_port()
self.host = "localhost"
self.url = f"http://{self.host}:{self.port}"
self.workers = 2
self.process = subprocess.Popen(
[
sys.executable,
... | Gateway |
python | getsentry__sentry | src/sentry/utils/event_frames.py | {
"start": 937,
"end": 1062
} | class ____(Protocol):
def __call__(self, frame: EventFrame) -> str | None:
pass
@dataclass(frozen=True)
| FrameMunger |
python | apache__airflow | dev/breeze/src/airflow_breeze/utils/selective_checks.py | {
"start": 3861,
"end": 4987
} | class ____(Enum):
ENVIRONMENT_FILES = auto()
PYTHON_PRODUCTION_FILES = auto()
JAVASCRIPT_PRODUCTION_FILES = auto()
ALWAYS_TESTS_FILES = auto()
API_FILES = auto()
GIT_PROVIDER_FILES = auto()
STANDARD_PROVIDER_FILES = auto()
API_CODEGEN_FILES = auto()
HELM_FILES = auto()
DEPENDENCY... | FileGroupForCi |
python | bokeh__bokeh | src/bokeh/events.py | {
"start": 8922,
"end": 9465
} | class ____(ModelEvent):
''' Announce a button click event on a Bokeh button widget.
'''
event_name = 'button_click'
def __init__(self, model: AbstractButton | None) -> None:
from .models.widgets import AbstractButton, ToggleButtonGroup
if model is not None and not isinstance(model, (Ab... | ButtonClick |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_task_instances.py | {
"start": 76844,
"end": 95681
} | class ____(TestTaskInstanceEndpoint):
def test_should_respond_200(self, test_client, session):
self.create_task_instances(session, task_instances=[{"state": State.SUCCESS}], with_ti_history=True)
response = test_client.get(
"/dags/example_python_operator/dagRuns/TEST_DAG_RUN_ID/taskInsta... | TestGetTaskInstanceTry |
python | tiangolo__fastapi | docs_src/dependencies/tutorial008b.py | {
"start": 238,
"end": 735
} | class ____(Exception):
pass
def get_username():
try:
yield "Rick"
except OwnerError as e:
raise HTTPException(status_code=400, detail=f"Owner error: {e}")
@app.get("/items/{item_id}")
def get_item(item_id: str, username: str = Depends(get_username)):
if item_id not in data:
r... | OwnerError |
python | django__django | tests/model_fields/test_mixins.py | {
"start": 177,
"end": 283
} | class ____(FieldCacheMixin):
@cached_property
def cache_name(self):
return "example"
| Example |
python | jazzband__django-formtools | tests/wizard/namedwizardtests/tests.py | {
"start": 15609,
"end": 15886
} | class ____(NamedUrlCookieWizardView):
def dispatch(self, request, *args, **kwargs):
response = super().dispatch(request, *args, **kwargs)
return response, self
@override_settings(ROOT_URLCONF='tests.wizard.namedwizardtests.urls')
| TestNamedUrlCookieWizardView |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/runs.py | {
"start": 5712,
"end": 7110
} | class ____(GenericScalar, graphene.Scalar):
class Meta:
description = """This type is used when passing in a configuration object
for pipeline configuration. Can either be passed in as a string (the
YAML configuration object) or as the configuration object itself. In
either case, the... | GrapheneRunConfigData |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_cmath.py | {
"start": 668,
"end": 2691
} | class ____(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path, target=None):
# Check if the import is the problematic one
if fullname in redirect_imports:
try:
# Attempt to import the standalone module
name = fullname.removeprefix("test.")
... | RedirectImportFinder |
python | huggingface__transformers | src/transformers/models/dinov3_vit/modular_dinov3_vit.py | {
"start": 5907,
"end": 9528
} | class ____(nn.Module):
inv_freq: torch.Tensor
def __init__(self, config: DINOv3ViTConfig):
super().__init__()
self.config = config
self.base = config.rope_theta
self.head_dim = config.hidden_size // config.num_attention_heads
self.num_patches_h = config.image_size // co... | DINOv3ViTRopePositionEmbedding |
python | great-expectations__great_expectations | tests/expectations/test_dataclass_serializable_dot_dict_pattern.py | {
"start": 809,
"end": 12436
} | class ____(SerializableDictDot):
alpha_var: int
beta_var: MyEnum
A_list: List[MyClassA]
B_list: List[MyClassB]
enum_list: List[MyEnum] = field(default_factory=list)
some_tuple: Optional[Tuple[MyClassA, MyClassB]] = None
@property
def num_As(self):
return len(self.A_list)
@p... | MyClassC |
python | doocs__leetcode | solution/1000-1099/1054.Distant Barcodes/Solution.py | {
"start": 0,
"end": 333
} | class ____:
def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
cnt = Counter(barcodes)
barcodes.sort(key=lambda x: (-cnt[x], x))
n = len(barcodes)
ans = [0] * len(barcodes)
ans[::2] = barcodes[: (n + 1) // 2]
ans[1::2] = barcodes[(n + 1) // 2 :]
re... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-okta/unit_tests/test_streams.py | {
"start": 4402,
"end": 6080
} | class ____:
def test_next_page_token(self, oauth_config, users_instance, url_base, api_url, start_date):
stream = get_stream_by_name("users", config=oauth_config)
response = MagicMock(requests.Response)
response.links = {"next": {"url": f"{api_url}?param1=test_value1¶m2=test_value2"}}
... | TestNextPageToken |
python | doocs__leetcode | solution/2600-2699/2685.Count the Number of Complete Components/Solution.py | {
"start": 0,
"end": 658
} | class ____:
def countCompleteComponents(self, n: int, edges: List[List[int]]) -> int:
def dfs(i: int) -> (int, int):
vis[i] = True
x, y = 1, len(g[i])
for j in g[i]:
if not vis[j]:
a, b = dfs(j)
x += a
... | Solution |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/bigquery.py | {
"start": 87569,
"end": 93206
} | class ____(GoogleCloudBaseOperator):
"""
Update BigQuery Table Schema.
Updates fields on a table schema based on contents of the supplied schema_fields_updates
parameter. The supplied schema does not need to be complete, if the field
already exists in the schema you only need to supply keys & value... | BigQueryUpdateTableSchemaOperator |
python | ApeWorX__ape | src/ape/types/coverage.py | {
"start": 3399,
"end": 6912
} | class ____(BaseModel):
"""
The individual coverage of a function defined in a smart contact.
"""
name: str
"""
The display name of the function.
"""
full_name: str
"""
The unique name of the function.
"""
statements: list[CoverageStatement] = []
"""
For stateme... | FunctionCoverage |
python | scikit-image__scikit-image | tests/skimage/_shared/test_utils.py | {
"start": 7179,
"end": 16393
} | class ____:
@pytest.mark.skipif(not have_numpydoc, reason="requires numpydoc")
def test_docstring_removed_param(self):
# function name and doc are preserved
assert _func_deprecated_params.__name__ == "_func_deprecated_params"
if sys.flags.optimize < 2:
# if PYTHONOPTIMIZE is ... | Test_deprecate_parameter |
python | walkccc__LeetCode | solutions/1144. Decrease Elements To Make Array Zigzag/1144.py | {
"start": 0,
"end": 327
} | class ____:
def movesToMakeZigzag(self, nums: list[int]) -> int:
decreasing = [0] * 2
for i, num in enumerate(nums):
l = nums[i - 1] if i > 0 else 1001
r = nums[i + 1] if i + 1 < len(nums) else 1001
decreasing[i % 2] += max(0, num - min(l, r) + 1)
return min(decreasing[0], decreasing[1... | Solution |
python | pyqtgraph__pyqtgraph | pyqtgraph/examples/jupyter_console_example.py | {
"start": 1654,
"end": 3601
} | class ____(QtWidgets.QMainWindow):
def __init__(self, dark_mode=True):
super().__init__()
central_dock_area = DockArea()
# create plot widget (and dock)
self.plot_widget = pg.PlotWidget()
plot_dock = Dock(name="Plot Widget Dock", closable=True)
plot_dock.addWidget(s... | MainWindow |
python | more-itertools__more-itertools | tests/test_more.py | {
"start": 50672,
"end": 54379
} | class ____(TestCase):
"""Tests for ``split_when()``"""
@staticmethod
def _split_when_before(iterable, pred):
return mi.split_when(iterable, lambda _, c: pred(c))
@staticmethod
def _split_when_after(iterable, pred):
return mi.split_when(iterable, lambda c, _: pred(c))
# split_b... | SplitWhenTests |
python | facebook__pyre-check | tools/upgrade/commands/tests/pysa_version_update_test.py | {
"start": 405,
"end": 1399
} | class ____(unittest.TestCase):
@patch("json.dumps")
@patch("json.loads")
@patch.object(Configuration, "find_parent_file")
@patch.object(Configuration, "set_pysa_version")
@patch.object(Configuration, "write")
@patch("builtins.open")
def test_run_pysa_version_update(
self,
ope... | UpdatePysaVersionTest |
python | getsentry__sentry | src/sentry/overwatch/endpoints/overwatch_rpc.py | {
"start": 3749,
"end": 5971
} | class ____(Endpoint):
"""
Returns the resolved config for a Sentry organization.
GET /prevent/pr-review/configs/resolved?sentryOrgId={orgId}&gitOrgName={gitOrgName}&provider={provider}
"""
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
owner = ApiOwner.CODECOV
authe... | PreventPrReviewResolvedConfigsEndpoint |
python | django__django | tests/template_tests/test_custom.py | {
"start": 25075,
"end": 37260
} | class ____(TagTestCase):
def test_inclusion_tags(self):
c = Context({"value": 42})
templates = [
(
"{% load inclusion %}{% inclusion_no_params %}",
"inclusion_no_params - Expected result\n",
),
(
"{% load inclusion ... | InclusionTagTests |
python | tensorflow__tensorflow | tensorflow/python/data/kernel_tests/tf_record_test_base.py | {
"start": 1208,
"end": 8444
} | class ____(test_base.DatasetTestBase):
"""Base class for testing TFRecord-based features."""
def setUp(self):
super(FeaturesTestBase, self).setUp()
self._num_files = 2
self._num_records = 7
self._filenames = self._createFiles()
def make_batch_feature(self,
filenames,
... | FeaturesTestBase |
python | mlflow__mlflow | mlflow/gateway/config.py | {
"start": 5657,
"end": 5920
} | class ____(ConfigModel):
anthropic_api_key: str
anthropic_version: str = "2023-06-01"
@field_validator("anthropic_api_key", mode="before")
def validate_anthropic_api_key(cls, value):
return _resolve_api_key_from_input(value)
| AnthropicConfig |
python | Lightning-AI__lightning | src/lightning/pytorch/utilities/model_summary/model_summary.py | {
"start": 4957,
"end": 21335
} | class ____:
"""Generates a summary of all layers in a :class:`~lightning.pytorch.core.LightningModule`.
Args:
model: The model to summarize (also referred to as the root module).
max_depth: Maximum depth of modules to show. Use -1 to show all modules or 0 to show no
summary. Defaul... | ModelSummary |
python | pypa__warehouse | tests/unit/utils/test_static.py | {
"start": 96,
"end": 1214
} | class ____:
def test_returns_when_valid(self, monkeypatch):
monkeypatch.setattr(
ManifestCacheBuster,
"get_manifest",
lambda x: {"/the/path/style.css": "/the/busted/path/style.css"},
)
cb = ManifestCacheBuster("warehouse:static/dist/manifest.json")
... | TestManifestCacheBuster |
python | plotly__plotly.py | plotly/graph_objs/violin/hoverlabel/_font.py | {
"start": 233,
"end": 17138
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "violin.hoverlabel"
_path_str = "violin.hoverlabel.font"
_valid_props = {
"color",
"colorsrc",
"family",
"familysrc",
"lineposition",
"linepositionsrc",
"shadow",
"shadowsrc",
"siz... | Font |
python | scikit-image__scikit-image | benchmarks/benchmark_filters.py | {
"start": 536,
"end": 918
} | class ____:
"""Benchmark for 3d sobel filters."""
def setup(self):
try:
filters.sobel(np.ones((8, 8, 8)))
except ValueError:
raise NotImplementedError("3d sobel unavailable")
self.image3d = data.binary_blobs(length=256, n_dim=3).astype(float)
def time_sobel_... | FiltersSobel3D |
python | kamyu104__LeetCode-Solutions | Python/maximum-odd-binary-number.py | {
"start": 504,
"end": 719
} | class ____(object):
def maximumOddBinaryNumber(self, s):
"""
:type s: str
:rtype: str
"""
n = s.count('1')
return "".join(['1']*(n-1)+['0']*(len(s)-n)+['1'])
| Solution2 |
python | paramiko__paramiko | paramiko/auth_handler.py | {
"start": 37417,
"end": 43006
} | class ____(AuthHandler):
"""
AuthHandler, and just auth, no service requests!
.. versionadded:: 3.2
"""
# NOTE: this purposefully duplicates some of the parent class in order to
# modernize, refactor, etc. The intent is that eventually we will collapse
# this one onto the parent in a backw... | AuthOnlyHandler |
python | scrapy__scrapy | scrapy/extensions/feedexport.py | {
"start": 10326,
"end": 11715
} | class ____(BlockingFeedStorage):
def __init__(
self,
uri: str,
use_active_mode: bool = False,
*,
feed_options: dict[str, Any] | None = None,
):
u = urlparse(uri)
if not u.hostname:
raise ValueError(f"Got a storage URI without a hostname: {uri}"... | FTPFeedStorage |
python | coleifer__peewee | tests/sqlite.py | {
"start": 86080,
"end": 86198
} | class ____(TestModel):
month = ForeignKeyField(CalendarMonth, backref='days')
value = IntegerField()
| CalendarDay |
python | openai__openai-python | src/openai/types/graders/multi_grader.py | {
"start": 600,
"end": 1018
} | class ____(BaseModel):
calculate_output: str
"""A formula to calculate the output based on grader results."""
graders: Graders
"""
A StringCheckGrader object that performs a string comparison between input and
reference using a specified operation.
"""
name: str
"""The name of the ... | MultiGrader |
python | huggingface__transformers | tests/utils/test_hf_argparser.py | {
"start": 2019,
"end": 2165
} | class ____:
foo: MixedTypeEnum = "toto"
def __post_init__(self):
self.foo = MixedTypeEnum(self.foo)
@dataclass
| MixedTypeEnumExample |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/lib/metadata_service/models/generated/ConnectorMetadataDefinitionV0.py | {
"start": 10788,
"end": 11484
} | class ____(BaseModel):
class Config:
extra = Extra.forbid
enabled: bool
name: Optional[str] = None
dockerRepository: Optional[str] = None
dockerImageTag: Optional[str] = None
supportsDbt: Optional[bool] = None
supportsNormalization: Optional[bool] = None
license: Optional[str] =... | RegistryOverrides |
python | crytic__slither | slither/solc_parsing/variables/variable_declaration.py | {
"start": 808,
"end": 8341
} | class ____:
# pylint: disable=too-many-branches
def __init__(self, variable: Variable, variable_data: Dict) -> None:
"""
A variable can be declared through a statement, or directly.
If it is through a statement, the following children may contain
the init value.
It may be... | VariableDeclarationSolc |
python | huggingface__transformers | src/transformers/models/falcon_h1/modeling_falcon_h1.py | {
"start": 10000,
"end": 16354
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: FalconH1Config, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
sel... | FalconH1RotaryEmbedding |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/test_responses_spec.py | {
"start": 407,
"end": 498
} | class ____(BaseSchema):
get_employee_role: int
get_employee_department: int
| ToolCalls |
python | kamyu104__LeetCode-Solutions | Python/bitwise-and-of-numbers-range.py | {
"start": 29,
"end": 232
} | class ____(object):
# @param m, an integer
# @param n, an integer
# @return an integer
def rangeBitwiseAnd(self, m, n):
while m < n:
n &= n - 1
return n
| Solution |
python | marshmallow-code__apispec | tests/schemas.py | {
"start": 1827,
"end": 1878
} | class ____(fields.String):
pass
| CustomStringField |
python | google__pytype | pytype/abstract/_typing.py | {
"start": 28029,
"end": 36157
} | class ____:
"""A late annotation.
A late annotation stores a string expression and a snapshot of the VM stack at
the point where the annotation was introduced. Once the expression is
resolved, the annotation pretends to be the resolved type; before that, it
pretends to be an unsolvable. This effect is achiev... | LateAnnotation |
python | pytorch__pytorch | test/jit/test_convert_activation.py | {
"start": 848,
"end": 4326
} | class ____(JitTestCase):
def test_check_no_type_promotion(self):
dtypes = [
torch.bool,
torch.int8,
torch.int16,
torch.int32,
torch.int64,
torch.float32,
torch.float64,
]
# restore_mutation.h contains a mappi... | TestFunctionalToInplaceActivation |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/overloadImpl1.py | {
"start": 2038,
"end": 2496
} | class ____: ...
T_CD = TypeVar("T_CD", ClassC, ClassD)
@overload
def func7(cls: type[ClassC], var: int) -> ClassC: ...
@overload
def func7(cls: type[ClassD], var: str) -> ClassD: ...
def func7(cls: type[T_CD], var: int | str) -> T_CD:
return cls()
T_str = TypeVar("T_str", bound=str)
@overload
def func8(... | ClassD |
python | getsentry__sentry | tests/sentry/users/api/endpoints/test_user_identity_config.py | {
"start": 345,
"end": 1571
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.superuser = self.create_user(is_superuser=True)
self.staff_user = self.create_user(is_staff=True)
self.slack_idp = self.create_identity_provider(type="slack", external_id="A")
self.github_idp = self.crea... | UserIdentityConfigTest |
python | ray-project__ray | rllib/offline/tests/test_json_reader.py | {
"start": 224,
"end": 1282
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
ray.init()
@classmethod
def tearDownClass(cls) -> None:
ray.shutdown()
def test_itr_batches(self):
"""Test that the json reader iterates over batches of rows correctly."""
rllib_dir = Path(__fi... | TestJsonReader |
python | getsentry__sentry | src/sentry/workflow_engine/handlers/condition/existing_high_priority_issue_handler.py | {
"start": 367,
"end": 869
} | class ____(DataConditionHandler[WorkflowEventData]):
group = DataConditionHandler.Group.WORKFLOW_TRIGGER
comparison_json_schema = {"type": "boolean"}
@staticmethod
def evaluate_value(event_data: WorkflowEventData, comparison: Any) -> bool:
state = event_data.group_state
if state is None... | ExistingHighPriorityIssueConditionHandler |
python | pytorch__pytorch | tools/testing/target_determination/heuristics/filepath.py | {
"start": 2999,
"end": 4405
} | class ____(HeuristicInterface):
# Heuristic based on folders in the file path. Takes each folder of each
# changed file and attempts to find matches based on those folders
def __init__(self, **kwargs: dict[str, Any]) -> None:
super().__init__(**kwargs)
def get_prediction_confidence(self, tests... | Filepath |
python | getsentry__sentry | tests/sentry/profiles/consumers/test_process.py | {
"start": 551,
"end": 3608
} | class ____(TestCase):
@staticmethod
def processing_factory() -> ProcessProfileStrategyFactory:
return ProcessProfileStrategyFactory()
@patch("sentry.profiles.consumers.process.factory.process_profile_task.delay")
def test_basic_profile_to_task(self, process_profile_task: MagicMock) -> None:
... | TestProcessProfileConsumerStrategy |
python | huggingface__transformers | src/transformers/models/gemma3n/modular_gemma3n.py | {
"start": 84204,
"end": 88748
} | class ____(Gemma3Attention):
def __init__(self, config: Gemma3nTextConfig, layer_idx: int):
super().__init__(config, layer_idx)
self.is_causal = True
del self.attn_logit_softcapping
self.scaling = 1.0
self.v_norm = Gemma3nRMSNorm(dim=config.head_dim, eps=config.rms_norm_eps, ... | Gemma3nTextAttention |
python | huggingface__transformers | src/transformers/models/aimv2/modeling_aimv2.py | {
"start": 7594,
"end": 9914
} | class ____(nn.Module):
def __init__(self, config: Aimv2TextConfig):
super().__init__()
embed_dim = config.hidden_size
self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
# positi... | Aimv2TextEmbeddings |
python | doocs__leetcode | solution/3600-3699/3663.Find The Least Frequent Digit/Solution.py | {
"start": 0,
"end": 316
} | class ____:
def getLeastFrequentDigit(self, n: int) -> int:
cnt = [0] * 10
while n:
n, x = divmod(n, 10)
cnt[x] += 1
ans, f = 0, inf
for x, v in enumerate(cnt):
if 0 < v < f:
f = v
ans = x
return ans
| Solution |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/asset/decorators.py | {
"start": 2318,
"end": 5036
} | class ____(PythonOperator):
def __init__(self, *, definition_name: str, uri: str | None = None, **kwargs) -> None:
super().__init__(**kwargs)
self._definition_name = definition_name
@classmethod
def from_definition(cls, definition: AssetDefinition | MultiAssetDefinition) -> Self:
_v... | _AssetMainOperator |
python | pytorch__pytorch | torch/_inductor/cpu_vec_isa.py | {
"start": 1109,
"end": 5412
} | class ____:
_bit_width: int
_macro: list[str]
_arch_flags: str
_dtype_nelements: dict[torch.dtype, int]
# Note [Checking for Vectorized Support in Inductor]
# TorchInductor CPU vectorization reuses PyTorch vectorization utility functions
# Hence, TorchInductor would depend on Sleef* to acce... | VecISA |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 20182,
"end": 20288
} | class ____(BaseModel, extra="forbid"):
context: "ContextInput" = Field(..., description="")
| ContextQuery |
python | doocs__leetcode | solution/0200-0299/0235.Lowest Common Ancestor of a Binary Search Tree/Solution.py | {
"start": 164,
"end": 514
} | class ____:
def lowestCommonAncestor(
self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode'
) -> 'TreeNode':
while 1:
if root.val < min(p.val, q.val):
root = root.right
elif root.val > max(p.val, q.val):
root = root.left
else:
... | Solution |
python | pennersr__django-allauth | allauth/headless/contrib/rest_framework/authentication.py | {
"start": 361,
"end": 1125
} | class ____(authentication.BaseAuthentication):
"""
This authentication class uses the X-Session-Token that django-allauth
is using for authentication purposes.
"""
def authenticate(self, request: HttpRequest):
token = self.get_session_token(request)
if token:
return auth... | XSessionTokenAuthentication |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/functions.py | {
"start": 43542,
"end": 47191
} | class ____(FunctionElement[_T]):
r"""Describe a named SQL function.
The :class:`.Function` object is typically generated from the
:data:`.func` generation object.
:param \*clauses: list of column expressions that form the arguments
of the SQL function call.
:param type\_: optional :class:`.... | Function |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.