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 | getsentry__sentry | tests/sentry/issues/auto_source_code_config/test_code_mapping.py | {
"start": 3280,
"end": 13680
} | class ____(TestCase):
@pytest.fixture(autouse=True)
def inject_fixtures(self, caplog: pytest.LogCaptureFixture) -> None:
self._caplog = caplog
def setUp(self) -> None:
super().setUp()
self.foo_repo = RepoAndBranch("Test-Organization/foo", "master")
self.bar_repo = RepoAndBra... | TestDerivedCodeMappings |
python | ray-project__ray | doc/source/serve/doc_code/object_detection.py | {
"start": 312,
"end": 955
} | class ____:
def __init__(self, object_detection_handle: DeploymentHandle):
self.handle = object_detection_handle
@app.get(
"/detect",
responses={200: {"content": {"image/jpeg": {}}}},
response_class=Response,
)
async def detect(self, image_url: str):
image = awai... | APIIngress |
python | walkccc__LeetCode | solutions/2598. Smallest Missing Non-negative Integer After Operations/2598.py | {
"start": 0,
"end": 279
} | class ____:
def findSmallestInteger(self, nums: list[int], value: int) -> int:
count = collections.Counter([num % value for num in nums])
for i in range(len(nums)):
if count[i % value] == 0:
return i
count[i % value] -= 1
return len(nums)
| Solution |
python | kamyu104__LeetCode-Solutions | Python/longest-happy-string.py | {
"start": 44,
"end": 1144
} | class ____(object):
def longestDiverseString(self, a, b, c):
"""
:type a: int
:type b: int
:type c: int
:rtype: str
"""
max_heap = []
if a:
heapq.heappush(max_heap, (-a, 'a'))
if b:
heapq.heappush(max_heap, (-b, 'b'))
... | Solution |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_collections.py | {
"start": 32152,
"end": 34375
} | class ____(__TestCase):
def validate_abstract_methods(self, abc, *names):
methodstubs = dict.fromkeys(names, lambda s, *args: 0)
# everything should work will all required methods are present
with torch._dynamo.error_on_graph_break(False):
C = type('C', (abc,), methodstubs)
... | ABCTestCase |
python | kubernetes-client__python | kubernetes/client/models/v1beta1_service_cidr_list.py | {
"start": 383,
"end": 7041
} | 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... | V1beta1ServiceCIDRList |
python | pandas-dev__pandas | pandas/io/clipboard/__init__.py | {
"start": 2079,
"end": 9757
} | class ____(PyperclipException):
pass
def _stringifyText(text) -> str:
acceptedTypes = (str, int, float, bool)
if not isinstance(text, acceptedTypes):
raise PyperclipException(
f"only str, int, float, and bool values "
f"can be copied to the clipboard, not {type(text).__name... | PyperclipTimeoutException |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 36705,
"end": 36883
} | class ____(axis_ticks_major_x, axis_ticks_major_y):
"""
x & y axis major tick lines
Parameters
----------
theme_element : element_line
"""
| axis_ticks_major |
python | dagster-io__dagster | python_modules/dagster/dagster/_daemon/daemon.py | {
"start": 9776,
"end": 10693
} | class ____(DagsterDaemon):
@classmethod
def daemon_type(cls) -> str:
return "SCHEDULER"
def scheduler_delay_instrumentation(
self, scheduler_id: str, next_iteration_timestamp: float, now_timestamp: float
) -> None:
pass
def core_loop(
self,
workspace_process... | SchedulerDaemon |
python | getsentry__sentry | src/sentry/grouping/parameterization.py | {
"start": 9513,
"end": 11981
} | class ____:
def __init__(
self,
regex_pattern_keys: Sequence[str],
experimental: bool = False,
):
self._experimental = experimental
self._parameterization_regex = self._make_regex_from_patterns(regex_pattern_keys)
self.matches_counter: defaultdict[str, int] = defa... | Parameterizer |
python | django-debug-toolbar__django-debug-toolbar | tests/test_integration_async.py | {
"start": 9595,
"end": 22824
} | class ____(IntegrationTestCase):
async def test_middleware_in_async_mode(self):
response = await self.async_client.get("/async_execute_sql/")
self.assertEqual(response.status_code, 200)
self.assertContains(response, "djDebug")
@override_settings(DEFAULT_CHARSET="iso-8859-1")
async d... | DebugToolbarIntegrationTestCase |
python | getsentry__sentry | src/sentry/users/api/endpoints/user_identity_config.py | {
"start": 3126,
"end": 3786
} | class ____(UserEndpoint):
publish_status = {
"GET": ApiPublishStatus.PRIVATE,
}
permission_classes = (UserAndStaffPermission,)
def get(self, request: Request, user: User) -> Response:
"""
Retrieve all of a user's SocialIdentity, Identity, and AuthIdentity values
```````... | UserIdentityConfigEndpoint |
python | getsentry__sentry | src/sentry/migrations/0945_move_discover_models.py | {
"start": 147,
"end": 2076
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | facebook__pyre-check | client/language_server/tests/connections_test.py | {
"start": 2813,
"end": 4685
} | class ____(testslide.TestCase):
async def _test_connect_async(self, socket_path: Path) -> None:
async with connect_async(socket_path) as (input_channel, output_channel):
await output_channel.write("abc\n")
result = (await input_channel.readline()).strip()
self.assertEqual... | AsyncConnectionTest |
python | pytorch__pytorch | test/torch_np/numpy_tests/lib/test_function_base.py | {
"start": 5158,
"end": 7317
} | class ____(TestCase):
def test_axes(self):
assert_raises(np.AxisError, np.flip, np.ones(4), axis=1)
assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=2)
assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=-3)
assert_raises(np.AxisError, np.flip, np.ones((4, 4)), axis=... | TestFlip |
python | dask__distributed | distributed/diagnostics/plugin.py | {
"start": 19052,
"end": 20528
} | class ____(InstallPlugin):
"""A plugin to conda install a set of packages
This accepts a set of packages to install on the scheduler and all
workers as well as options to use when installing.
You can also optionally ask for the workers to restart after
performing this installation.
.. note::
... | CondaInstall |
python | getsentry__sentry | tests/sentry/incidents/endpoints/test_organization_combined_rule_index_endpoint.py | {
"start": 807,
"end": 55230
} | class ____(BaseAlertRuleSerializerTest, APITestCase):
endpoint = "sentry-api-0-organization-combined-rules"
def setUp(self) -> None:
super().setUp()
self.team = self.create_team(
organization=self.organization,
name="Mariachi Band",
members=[self.user],
... | OrganizationCombinedRuleIndexEndpointTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/indices/tree/select_leaf_retriever.py | {
"start": 1887,
"end": 15660
} | class ____(BaseRetriever):
"""
Tree select leaf retriever.
This class traverses the index graph and searches for a leaf node that can best
answer the query.
Args:
query_template (Optional[BasePromptTemplate]): Tree Select Query Prompt
(see :ref:`Prompt-Templates`).
quer... | TreeSelectLeafRetriever |
python | doocs__leetcode | solution/0100-0199/0166.Fraction to Recurring Decimal/Solution.py | {
"start": 0,
"end": 699
} | class ____:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
if numerator == 0:
return "0"
ans = []
neg = (numerator > 0) ^ (denominator > 0)
if neg:
ans.append("-")
a, b = abs(numerator), abs(denominator)
ans.append(str(a ... | Solution |
python | joke2k__faker | faker/providers/date_time/it_IT/__init__.py | {
"start": 46,
"end": 786
} | class ____(DateTimeProvider):
DAY_NAMES = {
"0": "domenica",
"1": "lunedì",
"2": "martedì",
"3": "mercoledì",
"4": "giovedì",
"5": "venerdì",
"6": "sabato",
}
MONTH_NAMES = {
"01": "gennaio",
"02": "febbraio",
"03": "marzo",
... | Provider |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/job.py | {
"start": 1452,
"end": 1583
} | class ____(BaseModel):
"""Job Collection Response."""
jobs: Iterable[JobResponse]
total_entries: int
| JobCollectionResponse |
python | django-haystack__django-haystack | haystack/templatetags/highlight.py | {
"start": 188,
"end": 4320
} | class ____(template.Node):
def __init__(
self, text_block, query, html_tag=None, css_class=None, max_length=None
):
self.text_block = template.Variable(text_block)
self.query = template.Variable(query)
self.html_tag = html_tag
self.css_class = css_class
self.max_l... | HighlightNode |
python | google__jax | tests/svd_test.py | {
"start": 1269,
"end": 10914
} | class ____(jtu.JaxTestCase):
@jtu.sample_product(
shape=[(4, 5), (3, 4, 5), (2, 3, 4, 5)],
dtype=jtu.dtypes.floating + jtu.dtypes.complex,
)
@jax.default_matmul_precision('float32')
def testSvdvals(self, shape, dtype):
rng = jtu.rand_default(self.rng())
args_maker = lambda: [rng(shape, dtyp... | SvdTest |
python | ray-project__ray | doc/source/serve/doc_code/tutorial_pytorch.py | {
"start": 337,
"end": 1678
} | class ____:
def __init__(self):
self.model = resnet18(pretrained=True).eval()
self.preprocessor = transforms.Compose(
[
transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Lambda(lambda t: t... | ImageModel |
python | pypa__setuptools | setuptools/_vendor/jaraco/collections/__init__.py | {
"start": 3698,
"end": 9127
} | class ____(Dict[_RangeMapKT, _VT]):
"""
A dictionary-like object that uses the keys as bounds for a range.
Inclusion of the value for that range is determined by the
key_match_comparator, which defaults to less-than-or-equal.
A value is returned for a key if it is the first key that matches in
t... | RangeMap |
python | pytorch__pytorch | torch/_dynamo/variables/functions.py | {
"start": 103476,
"end": 105184
} | class ____(VariableTracker):
grid: "TritonGridType"
kernel: "TritonKernelType"
kernel_idx: Optional[int]
kernel_source: "AttrSource"
def __init__(
self, kernel: Any, kernel_idx: Optional[int], grid: Any, **kwargs: Any
) -> None:
self.kernel_source = kwargs.pop("kernel_source", N... | TritonKernelVariable |
python | allegroai__clearml | clearml/backend_api/services/v2_9/models.py | {
"start": 79590,
"end": 83090
} | class ____(Response):
"""
Response of models.set_ready endpoint.
:param updated: Number of models updated (0 or 1)
:type updated: int
:param published_task: Result of publishing of the model's associated task (if
exists). Returned only if the task was published successfully as part of the
... | SetReadyResponse |
python | pytransitions__transitions | tests/test_add_remove.py | {
"start": 206,
"end": 2689
} | class ____(TestCase):
def test_garbage_collection(self):
states = ['A', 'B', 'C', 'D', 'E', 'F']
machine = Machine(model=[], states=states, initial='A', name='Test Machine')
machine.add_transition('advance', 'A', 'B')
machine.add_transition('advance', 'B', 'C')
machine.add_... | TestTransitionsAddRemove |
python | pandas-dev__pandas | pandas/core/flags.py | {
"start": 219,
"end": 4211
} | class ____:
"""
Flags that apply to pandas objects.
“Flags” differ from “metadata”. Flags reflect properties of the pandas
object (the Series or DataFrame). Metadata refer to properties of the
dataset, and should be stored in DataFrame.attrs.
Parameters
----------
obj : Series or DataF... | Flags |
python | ijl__orjson | test/test_enum.py | {
"start": 429,
"end": 592
} | class ____:
def __init__(self, val):
self.val = val
def default(obj):
if isinstance(obj, Custom):
return obj.val
raise TypeError
| Custom |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 112687,
"end": 113157
} | class ____(sgqlc.types.Enum):
"""The different kinds of goals a GitHub Sponsors member can have.
Enumeration Choices:
* `MONTHLY_SPONSORSHIP_AMOUNT`: The goal is about getting a
certain amount in USD from sponsorships each month.
* `TOTAL_SPONSORS_COUNT`: The goal is about reaching a certain
... | SponsorsGoalKind |
python | neetcode-gh__leetcode | python/0219-contains-duplicate-ii.py | {
"start": 0,
"end": 364
} | class ____:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
window = set()
L = 0
for R in range(len(nums)):
if R - L > k:
window.remove(nums[L])
L += 1
if nums[R] in window:
return True
w... | Solution |
python | davidhalter__jedi | jedi/inference/gradual/typing.py | {
"start": 14352,
"end": 14907
} | class ____(ValueWrapper):
def py__call__(self, arguments):
ordered_args = arguments.unpack()
next(ordered_args, (None, None))
_, second_arg = next(ordered_args, (None, None))
if second_arg is None:
return NO_VALUES
return ValueSet(
NewType(
... | NewTypeFunction |
python | pandas-dev__pandas | pandas/tests/frame/methods/test_diff.py | {
"start": 166,
"end": 10246
} | class ____:
def test_diff_requires_integer(self):
df = DataFrame(np.random.default_rng(2).standard_normal((2, 2)))
with pytest.raises(ValueError, match="periods must be an integer"):
df.diff(1.5)
# GH#44572 np.int64 is accepted
@pytest.mark.parametrize("num", [1, np.int64(1)])
... | TestDataFrameDiff |
python | walkccc__LeetCode | solutions/1291. Sequential Digits/1291.py | {
"start": 0,
"end": 399
} | class ____:
def sequentialDigits(self, low: int, high: int) -> list[int]:
ans = []
q = collections.deque([num for num in range(1, 10)])
while q:
num = q.popleft()
if num > high:
return ans
if low <= num and num <= high:
ans.append(num)
lastDigit = num % 10
if... | Solution |
python | run-llama__llama_index | llama-index-core/llama_index/core/langchain_helpers/streaming.py | {
"start": 216,
"end": 1935
} | class ____(BaseCallbackHandler):
"""Streaming callback handler."""
def __init__(self) -> None:
self._token_queue: Queue = Queue()
self._done = Event()
def __deepcopy__(self, memo: Any) -> "StreamingGeneratorCallbackHandler":
# NOTE: hack to bypass deepcopy in langchain
retu... | StreamingGeneratorCallbackHandler |
python | graphql-python__graphene | graphene/relay/tests/test_node.py | {
"start": 162,
"end": 299
} | class ____:
shared = String()
something_else = String()
def resolve_something_else(*_):
return "----"
| SharedNodeFields |
python | getsentry__sentry | src/sentry/api/endpoints/project_tags.py | {
"start": 626,
"end": 3360
} | class ____(ProjectEndpoint):
owner = ApiOwner.UNOWNED
publish_status = {
"GET": ApiPublishStatus.UNKNOWN,
}
def get(self, request: Request, project) -> Response:
try:
environment_id = get_environment_id(request, project.organization_id)
except Environment.DoesNotExis... | ProjectTagsEndpoint |
python | numba__numba | numba/core/cpu_options.py | {
"start": 96,
"end": 416
} | class ____(metaclass=ABCMeta):
"""Abstract base class for custom option values.
"""
@abstractmethod
def encode(self) -> str:
"""Returns an encoding of the values
"""
...
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.encode()})"
| AbstractOptionValue |
python | python-poetry__poetry | src/poetry/layouts/src.py | {
"start": 105,
"end": 202
} | class ____(Layout):
@property
def basedir(self) -> Path:
return Path("src")
| SrcLayout |
python | getsentry__sentry | src/sentry/integrations/slack/message_builder/prompt.py | {
"start": 226,
"end": 708
} | class ____(BlockSlackMessageBuilder):
def __init__(self, url: str) -> None:
super().__init__()
self.url = url
def build(self) -> SlackBody:
return {
"blocks": orjson.dumps(
[
self.get_markdown_block(LINK_IDENTITY_MESSAGE),
... | SlackPromptLinkMessageBuilder |
python | tqdm__tqdm | tqdm/std.py | {
"start": 1028,
"end": 1412
} | class ____(Warning):
"""base class for all tqdm warnings.
Used for non-external-code-breaking errors, such as garbled printing.
"""
def __init__(self, msg, fp_write=None, *a, **k):
if fp_write is not None:
fp_write("\n" + self.__class__.__name__ + ": " + str(msg).rstrip() + '\n')
... | TqdmWarning |
python | pytorch__pytorch | torch/nn/modules/container.py | {
"start": 22458,
"end": 27819
} | class ____(Module):
r"""Holds parameters in a list.
:class:`~torch.nn.ParameterList` can be used like a regular Python
list, but Tensors that are :class:`~torch.nn.Parameter` are properly registered,
and will be visible by all :class:`~torch.nn.Module` methods.
Note that the constructor, assigning... | ParameterList |
python | sqlalchemy__sqlalchemy | test/orm/inheritance/test_poly_loading.py | {
"start": 51966,
"end": 55568
} | class ____(
testing.AssertsExecutionResults, fixtures.TestBase
):
"""test for #7799"""
@testing.fixture
def mapping_fixture(self, registry, connection):
Base = registry.generate_base()
class BaseClass(Base):
__tablename__ = "baseclass"
id = Column(
... | NoBaseWPPlusAliasedTest |
python | openai__openai-python | src/openai/resources/audio/translations.py | {
"start": 14478,
"end": 15505
} | class ____:
def __init__(self, translations: AsyncTranslations) -> None:
self._translations = translations
self.create = async_to_streamed_response_wrapper(
translations.create,
)
def _get_response_format_type(
response_format: AudioResponseFormat | Omit,
) -> type[Transla... | AsyncTranslationsWithStreamingResponse |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_auth_token_details.py | {
"start": 5165,
"end": 10956
} | class ____(APITestCase):
endpoint = "sentry-api-0-org-auth-token-details"
method = "PUT"
def test_simple(self) -> None:
token = OrgAuthToken.objects.create(
organization_id=self.organization.id,
name="token 1",
token_hashed="ABCDEF",
token_last_charac... | OrganizationAuthTokenEditTest |
python | SmileyChris__easy-thumbnails | easy_thumbnails/optimize/conf.py | {
"start": 44,
"end": 816
} | class ____(Settings):
THUMBNAIL_OPTIMIZE_COMMAND = {'png': None, 'jpeg': None, 'gif': None}
"""
Postprocess thumbnails of type PNG, GIF or JPEG after transformation but
before storage.
Apply an external post processing program to images after they have been
manipulated by PIL or Pillow. This is... | OptimizeSettings |
python | ansible__ansible | lib/ansible/modules/user.py | {
"start": 107565,
"end": 111854
} | class ____(User):
"""
This is a HP-UX User manipulation class.
This overrides the following methods from the generic class:-
- create_user()
- remove_user()
- modify_user()
"""
platform = 'HP-UX'
distribution = None
SHADOWFILE = '/etc/shadow'
def create_user(self):
... | HPUX |
python | pytest-dev__pytest | testing/test_pastebin.py | {
"start": 219,
"end": 2702
} | class ____:
@pytest.fixture
def pastebinlist(self, monkeypatch, request) -> list[str | bytes]:
pastebinlist: list[str | bytes] = []
plugin = request.config.pluginmanager.getplugin("pastebin")
monkeypatch.setattr(plugin, "create_new_paste", pastebinlist.append)
return pastebinlist... | TestPasteCapture |
python | mlflow__mlflow | mlflow/entities/run_info.py | {
"start": 909,
"end": 5936
} | class ____(_MlflowObject):
"""
Metadata about a run.
"""
def __init__(
self,
run_id,
experiment_id,
user_id,
status,
start_time,
end_time,
lifecycle_stage,
artifact_uri=None,
run_name=None,
):
if experiment_id i... | RunInfo |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/spark_filesystem_datasource.py | {
"start": 715,
"end": 3460
} | class ____(_SparkFilePathDatasource):
"""
SparkFilesystemDatasource is a subclass of SparkDatasource which connects to
the filesystem.
"""
# class attributes
data_connector_type: ClassVar[Type[FilesystemDataConnector]] = FilesystemDataConnector
# these fields should not be passed to the exe... | SparkFilesystemDatasource |
python | doocs__leetcode | solution/2700-2799/2785.Sort Vowels in a String/Solution.py | {
"start": 0,
"end": 314
} | class ____:
def sortVowels(self, s: str) -> str:
vs = [c for c in s if c.lower() in "aeiou"]
vs.sort()
cs = list(s)
j = 0
for i, c in enumerate(cs):
if c.lower() in "aeiou":
cs[i] = vs[j]
j += 1
return "".join(cs)
| Solution |
python | ethereum__web3.py | web3/contract/contract.py | {
"start": 12008,
"end": 12329
} | class ____(BaseContractFunctions[ContractFunction]):
def __init__(
self,
abi: ABI,
w3: "Web3",
address: ChecksumAddress | None = None,
decode_tuples: bool | None = False,
) -> None:
super().__init__(abi, w3, ContractFunction, address, decode_tuples)
| ContractFunctions |
python | lepture__authlib | authlib/integrations/httpx_client/oauth1_client.py | {
"start": 464,
"end": 979
} | class ____(Auth, ClientAuth):
"""Signs the httpx request using OAuth 1 (RFC5849)."""
requires_request_body = True
def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:
url, headers, body = self.prepare(
request.method, str(request.url), request.headers, re... | OAuth1Auth |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/test_responses.py | {
"start": 601,
"end": 1689
} | class ____:
"""Test UsingToolStrategy dataclass."""
def test_basic_creation(self) -> None:
"""Test basic UsingToolStrategy creation."""
strategy = ToolStrategy(schema=_TestModel)
assert strategy.schema == _TestModel
assert strategy.tool_message_content is None
assert len... | TestUsingToolStrategy |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/invalid_return_type_index.py | {
"start": 204,
"end": 290
} | class ____:
def __index__(self):
return 3.05 # [invalid-index-return]
| Float |
python | django-guardian__django-guardian | guardian/testapp/tests/test_admin.py | {
"start": 1086,
"end": 1225
} | class ____(GuardedModelAdmin):
"""Test admin for User model with inline forms."""
inlines = [UserProfileInline]
| UserAdminWithProfile |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/distlib/metadata.py | {
"start": 22256,
"end": 39693
} | class ____(object):
"""
The metadata of a release. This implementation uses 2.1
metadata where possible. If not possible, it wraps a LegacyMetadata
instance which handles the key-value metadata format.
"""
METADATA_VERSION_MATCHER = re.compile(r'^\d+(\.\d+)*$')
NAME_MATCHER = re.compile('^... | Metadata |
python | pypa__pipenv | pipenv/patched/pip/_internal/index/collector.py | {
"start": 6496,
"end": 8192
} | class ____(Protocol):
def __call__(self, page: "IndexContent") -> Iterable[Link]: ...
def with_cached_index_content(fn: ParseLinks) -> ParseLinks:
"""
Given a function that parses an Iterable[Link] from an IndexContent, cache the
function's result (keyed by CacheablePageContent), unless the IndexConte... | ParseLinks |
python | PyCQA__pylint | tests/functional/g/generic_alias/generic_alias_related.py | {
"start": 1175,
"end": 1233
} | class ____(ClsAbstract): # [abstract-method]
pass
| Derived |
python | sqlalchemy__sqlalchemy | test/perf/compiled_extensions/row.py | {
"start": 1687,
"end": 8285
} | class ____(Case):
@staticmethod
def python():
from sqlalchemy.engine import _row_cy
py_res = load_uncompiled_module(_row_cy)
assert not py_res._is_compiled()
return py_res.BaseRow
@staticmethod
def cython():
from sqlalchemy.engine import _row_cy
assert ... | BaseRow |
python | Netflix__metaflow | metaflow/plugins/kubernetes/kubernetes_jobsets.py | {
"start": 16425,
"end": 32398
} | class ____(object):
def __init__(self, kubernetes_sdk, name, **kwargs):
self._kubernetes_sdk = kubernetes_sdk
self._kwargs = kwargs
self.name = name
def replicas(self, replicas):
self._kwargs["replicas"] = replicas
return self
def step_name(self, step_name):
... | JobSetSpec |
python | mozilla__bleach | bleach/_vendor/parse.py | {
"start": 6307,
"end": 7227
} | class ____(_NetlocResultMixinBase, _ResultMixinStr):
__slots__ = ()
@property
def _userinfo(self):
netloc = self.netloc
userinfo, have_info, hostinfo = netloc.rpartition('@')
if have_info:
username, have_password, password = userinfo.partition(':')
if not hav... | _NetlocResultMixinStr |
python | boto__boto3 | tests/functional/test_utils.py | {
"start": 675,
"end": 1430
} | class ____(unittest.TestCase):
def test_runtime_error_raised_when_shadowing_client_method(self):
botocore_session = botocore.session.get_session()
session = boto3.session.Session(
region_name='us-west-2', botocore_session=botocore_session
)
def shadows_put_object(class_a... | TestUtils |
python | pytorch__pytorch | torch/testing/_internal/common_fsdp.py | {
"start": 58984,
"end": 59453
} | class ____(nn.Module):
def __init__(self, double_nest):
super().__init__()
self.linear = nn.Linear(10, 10, bias=False).to(DEVICE_TYPE)
self.linear_skip = SkipModule().to(DEVICE_TYPE)
self.nested_linear = wrap(
NestedLinear(fsdp_wrap=double_nest), device_id=DEVICE_TYPE
... | SkipModel |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 207655,
"end": 207745
} | class ____(AsyncDefNode):
gen_type_name = 'AsyncGen'
is_asyncgen = True
| AsyncGenNode |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/dataform.py | {
"start": 1515,
"end": 1772
} | class ____(BaseGoogleLink):
"""Helper class for constructing Dataflow Job Link."""
name = "Dataform Workflow Invocation"
key = "dataform_workflow_invocation_config"
format_str = DATAFORM_WORKFLOW_INVOCATION_LINK
| DataformWorkflowInvocationLink |
python | allegroai__clearml | clearml/backend_api/services/v2_13/projects.py | {
"start": 29382,
"end": 33756
} | class ____(Request):
"""
Create a new project
:param name: Project name Unique within the company.
:type name: str
:param description: Project description.
:type description: str
:param tags: User-defined tags
:type tags: Sequence[str]
:param system_tags: System tags. This field is ... | CreateRequest |
python | pyca__cryptography | tests/hazmat/primitives/test_hash_vectors.py | {
"start": 4770,
"end": 5131
} | class ____:
test_sha3_384 = generate_hash_test(
load_hash_vectors,
os.path.join("hashes", "SHA3"),
["SHA3_384LongMsg.rsp", "SHA3_384ShortMsg.rsp"],
hashes.SHA3_384(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(hashes.SHA3_512()),
skip_messa... | TestSHA3384 |
python | pytorch__pytorch | torch/fx/experimental/symbolic_shapes.py | {
"start": 88452,
"end": 97924
} | class ____(NamedTuple):
k: sympy.Symbol
vr: Optional[ValueRanges]
val: Optional[sympy.Integer]
is_size_like: bool
@lru_cache(None)
def _maybe_evaluate_static_worker(
expr: _SympyT,
# NB: this is a tuple to ensure it can be LRU cached
symbol_info: tuple[_SymbolInfo, ...],
unbacked_only:... | _SymbolInfo |
python | sphinx-doc__sphinx | sphinx/ext/graphviz.py | {
"start": 3522,
"end": 6469
} | class ____(SphinxDirective):
"""Directive to insert arbitrary dot markup."""
has_content = True
required_arguments = 0
optional_arguments = 1
final_argument_whitespace = False
option_spec: ClassVar[OptionSpec] = {
'alt': directives.unchanged,
'align': align_spec,
'captio... | Graphviz |
python | anthropics__anthropic-sdk-python | src/anthropic/types/messages/message_batch.py | {
"start": 315,
"end": 2415
} | class ____(BaseModel):
id: str
"""Unique object identifier.
The format and length of IDs may change over time.
"""
archived_at: Optional[datetime] = None
"""
RFC 3339 datetime string representing the time at which the Message Batch was
archived and its results became unavailable.
"... | MessageBatch |
python | matplotlib__matplotlib | lib/matplotlib/backends/backend_gtk4.py | {
"start": 22918,
"end": 23632
} | class ____(backend_tools.ToolCopyToClipboardBase):
def trigger(self, *args, **kwargs):
with io.BytesIO() as f:
self.canvas.print_rgba(f)
w, h = self.canvas.get_width_height()
pb = GdkPixbuf.Pixbuf.new_from_data(f.getbuffer(),
... | ToolCopyToClipboardGTK4 |
python | getsentry__sentry | tests/sentry/dashboards/endpoints/test_organization_dashboard_details.py | {
"start": 30407,
"end": 39409
} | class ____(OrganizationDashboardDetailsTestCase):
def test_delete(self) -> None:
response = self.do_request("delete", self.url(self.dashboard.id))
assert response.status_code == 204
assert self.client.get(self.url(self.dashboard.id)).status_code == 404
assert not Dashboard.objects.... | OrganizationDashboardDetailsDeleteTest |
python | plotly__plotly.py | plotly/graph_objs/table/_cells.py | {
"start": 233,
"end": 13332
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "table"
_path_str = "table.cells"
_valid_props = {
"align",
"alignsrc",
"fill",
"font",
"format",
"formatsrc",
"height",
"line",
"prefix",
"prefixsrc",
"suffix",
... | Cells |
python | getsentry__sentry | fixtures/safe_migrations_apps/bad_flow_delete_field_pending_with_not_null_app/migrations/0001_initial.py | {
"start": 106,
"end": 589
} | class ____(CheckedMigration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="TestTable",
fields=[
(
"id",
models.AutoField(
auto_created=True, primary_key=True, s... | Migration |
python | run-llama__llama_index | docs/examples/discover_llamaindex/document_management/group_conversations.py | {
"start": 25,
"end": 2102
} | class ____:
def __init__(
self,
message_id,
message_text,
author,
timestamp,
parent_message=None,
child_message=None,
):
self.message_id = message_id
self.message_text = message_text
self.author = author
self.parent_message ... | Message |
python | ray-project__ray | rllib/core/models/torch/heads.py | {
"start": 6137,
"end": 8905
} | class ____(TorchModel):
def __init__(self, config: CNNTransposeHeadConfig) -> None:
super().__init__(config)
# Initial, inactivated Dense layer (always w/ bias).
# This layer is responsible for getting the incoming tensor into a proper
# initial image shape (w x h x filters) for the... | TorchCNNTransposeHead |
python | getsentry__sentry | tests/acceptance/test_organization_sentry_app_detailed_view.py | {
"start": 391,
"end": 2185
} | class ____(AcceptanceTestCase):
def setUp(self) -> None:
super().setUp()
self.create_project(organization=self.organization)
self.sentry_app = self.create_sentry_app(
organization_id=self.organization.id,
published=True,
verify_install=False,
n... | OrganizationSentryAppDetailedView |
python | ray-project__ray | rllib/utils/spaces/flexdict.py | {
"start": 88,
"end": 1298
} | class ____(gym.spaces.Dict):
"""Gym Dictionary with arbitrary keys updatable after instantiation
Example:
space = FlexDict({})
space['key'] = spaces.Box(4,)
See also: documentation for gym.spaces.Dict
"""
def __init__(self, spaces=None, **spaces_kwargs):
err = "Use either Dic... | FlexDict |
python | getlogbook__logbook | src/logbook/handlers.py | {
"start": 23692,
"end": 25688
} | class ____(FileHandler):
def __init__(
self,
filename,
encoding=None,
level=NOTSET,
format_string=None,
delay=False,
filter=None,
bubble=False,
compression_window_size=4 * 1024**2,
compression_quality=11,
):
super().__init__... | BrotliCompressionHandler |
python | pytorch__pytorch | torch/_inductor/runtime/hints.py | {
"start": 3720,
"end": 5481
} | class ____(typing.NamedTuple):
"""Copy device properties into a data structure not requiring torch to be imported"""
type: str # type: ignore[assignment]
index: int # type: ignore[assignment]
multi_processor_count: int
cc: int
major: int | None = None
regs_per_multiprocessor: int | None =... | DeviceProperties |
python | scipy__scipy | benchmarks/benchmarks/optimize_linprog.py | {
"start": 5488,
"end": 6929
} | class ____(Benchmark):
params = [
methods,
problems
]
param_names = ['method', 'problems']
def setup(self, meth, prob):
if prob not in enabled_problems:
raise NotImplementedError("skipped")
dir_path = os.path.dirname(os.path.realpath(__file__))
dataf... | Netlib |
python | pytorch__pytorch | test/inductor/test_torchinductor_strided_blocks.py | {
"start": 51067,
"end": 51548
} | class ____(BlockDescriptorTestBase):
device = GPU_TYPE
test_torchinductor.copy_tests(CommonTemplate, TritonBlockPointerTestGPU, GPU_TYPE)
@unittest.skipIf(
not (
HAS_CUDA_AND_TRITON
and torch.cuda.get_device_capability()[0] >= 9
and torch.version.hip is None
),
"Requires Trit... | TritonBlockPointerTestGPU |
python | astropy__astropy | astropy/table/ndarray_mixin.py | {
"start": 599,
"end": 2118
} | class ____(np.ndarray):
"""
Mixin column class to allow storage of arbitrary numpy
ndarrays within a Table. This is a subclass of numpy.ndarray
and has the same initialization options as ``np.array()``.
"""
info = NdarrayMixinInfo()
def __new__(cls, obj, *args, **kwargs):
self = n... | NdarrayMixin |
python | django__django | tests/basic/tests.py | {
"start": 30361,
"end": 33035
} | class ____(TestCase):
def test_select_on_save(self):
a1 = Article.objects.create(pub_date=datetime.now())
with self.assertNumQueries(1):
a1.save()
asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now())
with self.assertNumQueries(2):
asos.save()
... | SelectOnSaveTests |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/vector.py | {
"start": 523,
"end": 891
} | class ____(Enum):
"""Enum representing different types of VECTOR index structures.
See :ref:`oracle_vector_datatype` for background.
.. versionadded:: 2.0.41
"""
HNSW = "HNSW"
"""
The HNSW (Hierarchical Navigable Small World) index type.
"""
IVF = "IVF"
"""
The IVF (Inver... | VectorIndexType |
python | django__django | django/contrib/gis/gdal/field.py | {
"start": 4884,
"end": 5212
} | class ____(Field):
@property
def value(self):
"Return a Python `date` object for the OFTDate field."
try:
yy, mm, dd, hh, mn, ss, tz = self.as_datetime()
return date(yy.value, mm.value, dd.value)
except (TypeError, ValueError, GDALException):
return No... | OFTDate |
python | dagster-io__dagster | python_modules/automation/automation_tests/dagster_docs_tests/test_fixtures/test_public_class.py | {
"start": 298,
"end": 1688
} | class ____:
"""A public class with mixed public and non-public methods."""
@public
def public_instance_method(self):
"""This is a public instance method that should be validated."""
return "public_instance"
def non_public_instance_method(self):
"""This is a non-public instance ... | PublicClass |
python | astropy__astropy | astropy/utils/masked/tests/test_function_helpers.py | {
"start": 41444,
"end": 43614
} | class ____(MaskedArraySetup):
def test_interp(self):
xp = np.arange(5.0)
fp = np.array([1.0, 5.0, 6.0, 19.0, 20.0])
mask_fp = np.array([False, False, False, True, False])
mfp = Masked(fp, mask=mask_fp)
x = np.array([1.5, 17.0])
mask_x = np.array([False, True])
... | TestInterpolationFunctions |
python | pypa__warehouse | warehouse/subscriptions/services.py | {
"start": 11520,
"end": 13360
} | class ____(GenericBillingService):
@classmethod
def create_service(cls, context, request):
# Override api_base to hit mock-stripe in development
stripe.api_base = request.registry.settings["billing.api_base"]
stripe.api_version = request.registry.settings["billing.api_version"]
s... | MockStripeBillingService |
python | kamyu104__LeetCode-Solutions | Python/count-equal-and-divisible-pairs-in-an-array.py | {
"start": 1735,
"end": 2129
} | class ____(object):
def countPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
idxs = collections.defaultdict(list)
for i, x in enumerate(nums):
idxs[x].append(i)
return sum(idx[i]*idx[j]%k == 0 for idx in idxs.it... | Solution3 |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/types.py | {
"start": 2281,
"end": 2407
} | class ____(_NetworkAddressTypeMixin, sqltypes.TypeEngine[str]):
__visit_name__ = "MACADDR8"
PGMacAddr8 = MACADDR8
| MACADDR8 |
python | allegroai__clearml | clearml/backend_api/services/v2_9/models.py | {
"start": 67385,
"end": 72076
} | class ____(Response):
"""
Response of models.get_by_task_id endpoint.
:param model: Model info
:type model: Model
"""
_service = "models"
_action = "get_by_task_id"
_version = "2.9"
_schema = {
"definitions": {
"model": {
"properties": {
... | GetByTaskIdResponse |
python | apache__airflow | airflow-core/src/airflow/ti_deps/deps/mapped_task_upstream_dep.py | {
"start": 1490,
"end": 4744
} | class ____(BaseTIDep):
"""
Determines if the task, if mapped, is allowed to run based on its mapped dependencies.
In particular, check if upstream tasks that provide XComs used by this task for task mapping are in
states that allow the task instance to run.
"""
NAME = "Mapped dependencies have... | MappedTaskUpstreamDep |
python | pandas-dev__pandas | pandas/tests/io/formats/test_to_latex.py | {
"start": 5082,
"end": 7609
} | class ____:
def test_to_latex_empty_longtable(self):
df = DataFrame()
result = df.to_latex(longtable=True)
expected = _dedent(
r"""
\begin{longtable}{l}
\toprule
\midrule
\endfirsthead
\toprule
\midrule
... | TestToLatexLongtable |
python | pytorch__pytorch | test/distributed/pipelining/test_schedule.py | {
"start": 2140,
"end": 9166
} | class ____(TestCase):
def test_get_schedule_class(self):
# List of all expected schedule names
schedule_names = [
"1F1B",
"1f1b",
"Interleaved1F1B",
"INTERLEAVED1F1B",
"GPipe",
"LoopedBFS",
"PipelineScheduleSingle",
... | ScheduleTest |
python | getsentry__sentry | src/sentry/options/manager.py | {
"start": 1520,
"end": 2837
} | class ____(Enum):
"""
Represent the reason that prevents us from attempting an update
of an option on a specific UpdateChannel.
"""
# The option is registered with the FLAG_PRIORITIZE_DISK flag and it is
# also stored on disk as part of sentry settings. Nobody can update this.
OPTION_ON_DIS... | NotWritableReason |
python | bokeh__bokeh | src/bokeh/core/validation/check.py | {
"start": 1698,
"end": 1896
} | class ____:
error: list[ValidationIssue] = field(default_factory=list)
warning: list[ValidationIssue] = field(default_factory=list)
ValidatorType = Literal["error", "warning"]
| ValidationIssues |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_trace_logs.py | {
"start": 282,
"end": 14602
} | class ____(OrganizationEventsEndpointTestBase):
url_name = "sentry-api-0-organization-trace-logs"
def setUp(self) -> None:
super().setUp()
self.features = {
"organizations:ourlogs-enabled": True,
}
self.login_as(user=self.user)
self.url = reverse(
... | OrganizationEventsTraceEndpointTest |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.