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 | spack__spack | lib/spack/spack/version/git_ref_lookup.py | {
"start": 936,
"end": 8225
} | class ____(AbstractRefLookup):
"""An object for cached lookups of git refs
GitRefLookup objects delegate to the MISC_CACHE for locking. GitRefLookup objects may
be attached to a GitVersion to allow for comparisons between git refs and versions as
represented by tags in the git repository.
"""
... | GitRefLookup |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/pep695.py | {
"start": 296,
"end": 1848
} | class ____:
"""This is class Foo."""
type Pep695Alias = Foo
"""This is PEP695 type alias."""
type Pep695AliasUndocumented = Foo
TypeAliasTypeExplicit = TypeAliasType('TypeAliasTypeExplicit', Foo) # NoQA: UP040
"""This is an explicitly constructed typing.TypeAlias."""
HandlerTypeAliasType = TypeAliasType('Hand... | Foo |
python | joke2k__faker | faker/providers/address/th_TH/__init__.py | {
"start": 84,
"end": 9261
} | class ____(AddressProvider):
street_name_formats = ("{{street_prefix}}{{last_name}}",)
street_address_formats = ("{{building_number}} {{street_name}}",)
address_formats = OrderedDict(
(
(
"{{street_address}} {{tambon}} {{amphoe}} {{province}} {{postcode}}",
... | Provider |
python | wandb__wandb | tools/graphql_codegen/plugin.py | {
"start": 17670,
"end": 20032
} | class ____(ast.NodeTransformer):
"""Applies various modifications to a generated module with pydantic classes."""
def visit_Module(self, node: ast.Module) -> Any:
# Prepend shared import statements to the module. Ruff will clean this up later.
node.body = [
make_import_from("__futur... | PydanticModuleRewriter |
python | tiangolo__fastapi | docs_src/security/tutorial005.py | {
"start": 1250,
"end": 1345
} | class ____(BaseModel):
username: Union[str, None] = None
scopes: List[str] = []
| TokenData |
python | huggingface__transformers | src/transformers/models/mimi/modeling_mimi.py | {
"start": 27591,
"end": 32455
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: MimiConfig, layer_idx: Optional[int] = None):
super().__init__()
self.config = config
self.layer_idx = layer_idx
if layer_idx is None:
logger.warning... | MimiAttention |
python | graphql-python__graphene | graphene/validation/tests/test_depth_limit_validator.py | {
"start": 443,
"end": 541
} | class ____(ObjectType):
class meta:
name = "Dog"
interfaces = (PetType,)
| DogType |
python | bokeh__bokeh | src/bokeh/document/json.py | {
"start": 1814,
"end": 1921
} | class ____(TypedDict):
kind: Literal["MessageSent"]
msg_type: str
msg_data: Any | None
| MessageSent |
python | apache__airflow | providers/teradata/src/airflow/providers/teradata/operators/teradata_compute_cluster.py | {
"start": 16027,
"end": 19101
} | class ____(_TeradataComputeClusterOperator):
"""
Teradata Compute Cluster Operator to Resume the specified Teradata Vantage Cloud Lake Compute Cluster.
Resumes the Teradata Vantage Lake Computer Cluster by employing the RESUME SQL statement within the
Teradata Vantage Lake Compute Cluster SQL Interface... | TeradataComputeClusterResumeOperator |
python | huggingface__transformers | src/transformers/models/sam3/modeling_sam3.py | {
"start": 81284,
"end": 86647
} | class ____(Sam3PreTrainedModel):
"""
Mask decoder that combines object queries with pixel-level features to predict instance masks.
Also produces a semantic segmentation output and supports cross-attention to prompts.
"""
_can_record_outputs = {
"attentions": Sam3Attention,
}
def _... | Sam3MaskDecoder |
python | run-llama__llama_index | llama-index-integrations/embeddings/llama-index-embeddings-azure-openai/llama_index/embeddings/azure_openai/base.py | {
"start": 1009,
"end": 7014
} | class ____(OpenAIEmbedding):
azure_endpoint: Optional[str] = Field(
default=None, description="The Azure endpoint to use.", validate_default=True
)
azure_deployment: Optional[str] = Field(
default=None, description="The Azure deployment to use.", validate_default=True
)
api_base: st... | AzureOpenAIEmbedding |
python | huggingface__transformers | tests/models/rag/test_modeling_rag.py | {
"start": 25685,
"end": 40726
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temp_dir = tempfile.TemporaryDirectory()
cls.dataset_path = cls.temp_dir.name
cls.index_path = os.path.join(cls.temp_dir.name, "index.faiss")
ds = load_dataset("hf-internal-testing/wiki_dpr_dummy")["train"]
... | RagModelIntegrationTests |
python | huggingface__transformers | src/transformers/models/sam3_tracker/configuration_sam3_tracker.py | {
"start": 6703,
"end": 11021
} | class ____(PreTrainedConfig):
r"""
[`Sam3TrackerConfig`] is the configuration class to store the configuration of a [`Sam3TrackerModel`]. It is used to instantiate a
SAM3_TRACKER model according to the specified arguments, defining the memory attention, memory encoder, and image encoder
configs. Instant... | Sam3TrackerConfig |
python | matplotlib__matplotlib | galleries/examples/misc/demo_agg_filter.py | {
"start": 2369,
"end": 2912
} | class ____(BaseFilter):
def __init__(self, sigma, alpha=0.3, color=(0, 0, 0), offsets=(0, 0)):
self.gauss_filter = GaussianFilter(sigma, alpha, color)
self.offset_filter = OffsetFilter(offsets)
def get_pad(self, dpi):
return max(self.gauss_filter.get_pad(dpi),
self.o... | DropShadowFilter |
python | pytorch__pytorch | torch/_functorch/_aot_autograd/descriptors.py | {
"start": 15897,
"end": 16243
} | class ____(DifferentiableAOTInput):
"""The input is a parameter, whose FQN is target"""
target: str
def expr(self) -> str:
return f"self.get_parameter({self.target!r})"
def is_param(self) -> bool:
return True
def is_buffer(self) -> bool:
return False
@dataclasses.datacl... | ParamAOTInput |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/dagster/subschema/daemon.py | {
"start": 761,
"end": 1175
} | class ____(BaseModel, extra="forbid"):
maxConcurrentRuns: Optional[IntSource] = None
tagConcurrencyLimits: Optional[list[TagConcurrencyLimit]] = None
dequeueIntervalSeconds: Optional[IntSource] = None
dequeueNumWorkers: Optional[IntSource] = None
dequeueUseThreads: Optional[bool] = None
blockOpC... | QueuedRunCoordinatorConfig |
python | walkccc__LeetCode | solutions/923. 3Sum With Multiplicity/923.py | {
"start": 0,
"end": 566
} | class ____:
def threeSumMulti(self, arr: list[int], target: int) -> int:
MOD = 1_000_000_007
ans = 0
count = collections.Counter(arr)
for i, x in count.items():
for j, y in count.items():
k = target - i - j
if k not in count:
continue
if i == j and j == k:
... | Solution |
python | numpy__numpy | numpy/typing/tests/data/pass/scalars.py | {
"start": 268,
"end": 335
} | class ____:
def __complex__(self) -> complex:
return 3j
| C |
python | huggingface__transformers | src/transformers/models/sam_hq/configuration_sam_hq.py | {
"start": 1220,
"end": 3356
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`SamHQPromptEncoderModel`].The [`SamHQPromptEncoderModel`]
module is used to encode the input 2D points and bounding boxes. Instantiating a configuration defaults will yield a
similar configuration to tha... | SamHQPromptEncoderConfig |
python | langchain-ai__langchain | libs/core/langchain_core/tracers/stdout.py | {
"start": 6425,
"end": 6715
} | class ____(FunctionCallbackHandler):
"""Tracer that prints to the console."""
name: str = "console_callback_handler"
def __init__(self, **kwargs: Any) -> None:
"""Create a ConsoleCallbackHandler."""
super().__init__(function=print, **kwargs)
| ConsoleCallbackHandler |
python | walkccc__LeetCode | solutions/2749. Minimum Operations to Make the Integer Zero/2749.py | {
"start": 0,
"end": 650
} | class ____:
def makeTheIntegerZero(self, num1: int, num2: int) -> int:
# If k operations are used, num1 - [(num2 + 2^{i_1}) + (num2 + 2^{i_2}) +
# ... + (num2 + 2^{i_k})] = 0. So, num1 - k * num2 = (2^{i_1} + 2^{i_2} +
# ... + 2^{i_k}), where i_1, i_2, ..., i_k are in the range [0, 60].
# Note that fo... | Solution |
python | pyca__cryptography | src/cryptography/hazmat/primitives/asymmetric/ed448.py | {
"start": 1976,
"end": 4002
} | class ____(metaclass=abc.ABCMeta):
@classmethod
def generate(cls) -> Ed448PrivateKey:
from cryptography.hazmat.backends.openssl.backend import backend
if not backend.ed448_supported():
raise UnsupportedAlgorithm(
"ed448 is not supported by this version of OpenSSL.",
... | Ed448PrivateKey |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-azure-code-interpreter/llama_index/tools/azure_code_interpreter/base.py | {
"start": 1807,
"end": 11337
} | class ____(BaseToolSpec):
"""
Azure Code Interpreter tool spec.
Leverages Azure Dynamic Sessions to execute Python code.
"""
spec_functions = ["code_interpreter", "list_files"]
def __init__(
self,
pool_management_endpoint: Optional[str] = None,
session_id: Optional[str... | AzureCodeInterpreterToolSpec |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 63639,
"end": 64053
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("alt", "image_url", "caption")
alt = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="alt")
image_url = sgqlc.types.Field(sgqlc.types.non_null(URI), graphql_name... | CheckRunOutputImage |
python | sphinx-doc__sphinx | sphinx/environment/adapters/asset.py | {
"start": 231,
"end": 573
} | class ____:
def __init__(self, env: BuildEnvironment) -> None:
self.env = env
def get_original_image_uri(self, name: str) -> str:
"""Get the original image URI."""
while _StrPath(name) in self.env.original_image_uri:
name = self.env.original_image_uri[_StrPath(name)]
... | ImageAdapter |
python | langchain-ai__langchain | libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_structured_output_retry.py | {
"start": 2262,
"end": 11955
} | class ____(BaseModel):
"""Weather report schema for testing."""
temperature: float
conditions: str
@tool
def get_weather(city: str) -> str:
"""Get the weather for a given city.
Args:
city: The city to get weather for.
Returns:
Weather information for the city.
"""
re... | WeatherReport |
python | numba__numba | numba/tests/test_sysinfo.py | {
"start": 310,
"end": 2489
} | class ____(TestCase):
def setUp(self):
super(TestSysInfo, self).setUp()
self.info = nsi.get_sysinfo()
self.safe_contents = {
int: (
nsi._cpu_count,
),
float: (
nsi._runtime,
),
str: (
... | TestSysInfo |
python | getsentry__sentry | tests/sentry/integrations/jira/test_uninstalled.py | {
"start": 627,
"end": 3989
} | class ____(APITestCase):
external_id = "it2may+cody"
kid = "cudi"
shared_secret = "garden"
path = "/extensions/jira/uninstalled/"
def jwt_token_secret(self):
jira_signing_algorithm = "HS256"
return jwt.encode(
{
"iss": self.external_id,
"a... | JiraUninstalledTest |
python | google__pytype | pytype/overlays/future_overlay.py | {
"start": 140,
"end": 450
} | class ____(overlay.Overlay):
"""A custom overlay for the 'future' module."""
def __init__(self, ctx):
member_map = {
"with_metaclass": metaclass.WithMetaclass.make,
}
ast = ctx.loader.import_name("future.utils")
super().__init__(ctx, "future.utils", member_map, ast)
| FutureUtilsOverlay |
python | rq__rq | rq/executions.py | {
"start": 373,
"end": 4291
} | class ____:
"""Class to represent an execution of a job."""
def __init__(self, id: str, job_id: str, connection: Redis):
self.id = id
self.job_id = job_id
self.connection = connection
right_now = now()
self.created_at = right_now
self.last_heartbeat = right_now
... | Execution |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 116244,
"end": 116435
} | class ____:
xlSpanishTuteoAndVoseo = 1 # from enum XlSpanishModes
xlSpanishTuteoOnly = 0 # from enum XlSpanishModes
xlSpanishVoseoOnly = 2 # from enum XlSpanishModes
| SpanishModes |
python | google__jax | tests/pallas/tpu_sparsecore_pallas_test.py | {
"start": 61575,
"end": 61720
} | class ____(TCTilingMixin, PipelineTest):
pass
if __name__ == "__main__":
absltest.main(testLoader=jtu.JaxTestLoader())
| PipelineTestWithTCTiling |
python | streamlit__streamlit | lib/tests/streamlit/runtime/caching/storage/dummy_cache_storage_test.py | {
"start": 990,
"end": 2971
} | class ____(unittest.TestCase):
def setUp(self) -> None:
super().setUp()
self.context = CacheStorageContext(
function_key="func-key",
function_display_name="func-display-name",
persist="disk",
)
self.dummy_cache_storage = DummyCacheStorage()
... | DummyCacheStorageManagerTest |
python | getsentry__sentry-python | sentry_sdk/profiler/transaction_profiler.py | {
"start": 17661,
"end": 21851
} | class ____(ABC):
mode = "unknown" # type: ProfilerMode
def __init__(self, frequency):
# type: (int) -> None
self.interval = 1.0 / frequency
self.sampler = self.make_sampler()
# cap the number of new profiles at any time so it does not grow infinitely
self.new_profiles... | Scheduler |
python | has2k1__plotnine | plotnine/themes/themeable.py | {
"start": 55469,
"end": 55712
} | class ____(themeable):
"""
How to box up multiple legends
Parameters
----------
theme_element : Literal["vertical", "horizontal"]
Whether to stack up the legends vertically or
horizontally.
"""
| legend_box |
python | django__django | tests/migration_test_data_persistence/migrations/0001_initial.py | {
"start": 43,
"end": 647
} | class ____(migrations.Migration):
dependencies = []
operations = [
migrations.CreateModel(
name="Book",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
primary_key=True,... | Migration |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-dashvector/llama_index/readers/dashvector/base.py | {
"start": 178,
"end": 3145
} | class ____(BaseReader):
"""
DashVector reader.
Args:
api_key (str): DashVector API key.
endpoint (str): DashVector cluster endpoint.
"""
def __init__(self, api_key: str, endpoint: str):
"""Initialize with parameters."""
try:
import dashvector
ex... | DashVectorReader |
python | urllib3__urllib3 | src/urllib3/util/url.py | {
"start": 2942,
"end": 15205
} | class ____(
typing.NamedTuple(
"Url",
[
("scheme", typing.Optional[str]),
("auth", typing.Optional[str]),
("host", typing.Optional[str]),
("port", typing.Optional[int]),
("path", typing.Optional[str]),
("query", typing.Optional[... | Url |
python | pypa__warehouse | warehouse/accounts/interfaces.py | {
"start": 158,
"end": 218
} | class ____(RateLimiterException):
pass
| TooManyFailedLogins |
python | sympy__sympy | sympy/utilities/_compilation/runners.py | {
"start": 9068,
"end": 9630
} | class ____(CompilerRunner):
environ_key_compiler = 'CXX'
environ_key_flags = 'CXXFLAGS'
compiler_dict = OrderedDict([
('gnu', 'g++'),
('intel', 'icpc'),
('llvm', 'clang++'),
])
# First is the default, c++0x == c++11
standards = ('c++98', 'c++0x')
std_formater = {
... | CppCompilerRunner |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/components/asset_factory/asset_factory_component.py | {
"start": 304,
"end": 2404
} | class ____(dg.Component, dg.Model, dg.Resolvable):
# highlight-start
access_key_id: str = dg.Field
secret_access_key: str = dg.Field
etl_job: list[EtlJob]
# highlight-end
def build_defs(self, context: dg.ComponentLoadContext) -> dg.Definitions:
_assets = []
for etl in self.etl... | AssetFactory |
python | PyCQA__pylint | tests/functional/p/protected_access.py | {
"start": 561,
"end": 1042
} | class ____:
@property
def _light_internal(self) -> None:
return None
@staticmethod
def func(light) -> None:
print(light._light_internal) # [protected-access]
def func(light: Light) -> None:
print(light._light_internal) # [protected-access]
# os._exit is excluded from the prote... | Light |
python | django__django | django/contrib/postgres/search.py | {
"start": 8663,
"end": 8962
} | class ____(SearchQueryCombinable, CombinedExpression):
def __init__(self, lhs, connector, rhs, config, output_field=None):
self.config = config
super().__init__(lhs, connector, rhs, output_field)
def __str__(self):
return "(%s)" % super().__str__()
| CombinedSearchQuery |
python | streamlit__streamlit | lib/streamlit/elements/bokeh_chart.py | {
"start": 940,
"end": 2746
} | class ____:
@gather_metrics("bokeh_chart")
def bokeh_chart(
self,
figure: object, # noqa: ARG002
use_container_width: bool = True, # noqa: ARG002
) -> DeltaGenerator:
"""Display an interactive Bokeh chart.
Bokeh is a charting library for Python. You can find
... | BokehMixin |
python | django__django | tests/csrf_tests/tests.py | {
"start": 7653,
"end": 8036
} | class ____(TestingHttpRequest):
"""
TestingHttpRequest that can raise errors when accessing POST data.
"""
post_error = None
def _get_post(self):
if self.post_error is not None:
raise self.post_error
return self._post
def _set_post(self, post):
self._post =... | PostErrorRequest |
python | getsentry__sentry | src/sentry/models/organizationonboardingtask.py | {
"start": 1544,
"end": 3344
} | class ____(BaseManager["OrganizationOnboardingTask"]):
def record(
self,
organization_id: int,
task: int,
status: OnboardingTaskStatus = OnboardingTaskStatus.COMPLETE,
**kwargs,
) -> bool:
"""Record the completion of an onboarding task. Caches the completion. Retu... | OrganizationOnboardingTaskManager |
python | gevent__gevent | src/gevent/tests/test__subprocess.py | {
"start": 12371,
"end": 14977
} | class ____(unittest.TestCase):
@mock.patch('os.closerange')
@mock.patch('gevent.subprocess._set_inheritable')
@mock.patch('gevent.subprocess.os_close')
def test_close_fds_brute_force(self, close, set_inheritable, closerange):
keep = (
4, 5,
# Leave a hole
# 6... | TestFDs |
python | sqlalchemy__sqlalchemy | test/orm/test_joins.py | {
"start": 84092,
"end": 101887
} | class ____(fixtures.MappedTest, AssertsCompiledSQL):
run_setup_mappers = "once"
run_inserts = "once"
run_deletes = None
__dialect__ = "default"
@classmethod
def define_tables(cls, metadata):
Table(
"nodes",
metadata,
Column(
"id", Inte... | SelfReferentialTest |
python | huggingface__transformers | src/transformers/trainer_utils.py | {
"start": 7494,
"end": 7645
} | class ____(ExplicitEnum):
END = "end"
EVERY_SAVE = "every_save"
CHECKPOINT = "checkpoint"
ALL_CHECKPOINTS = "all_checkpoints"
| HubStrategy |
python | jazzband__django-waffle | waffle/tests/test_mixin.py | {
"start": 2726,
"end": 3722
} | class ____(TestCase):
def setUp(self):
super().setUp()
self.request = get()
def test_switch_must_be_active(self):
view = views.SwitchView
self.assertRaises(Http404, process_request, self.request, view)
Switch.objects.create(name='foo', active=True)
response = pr... | WaffleSwitchMixinTest |
python | pyparsing__pyparsing | pyparsing/util.py | {
"start": 5001,
"end": 5367
} | class ____(dict):
"""
A memoizing mapping that retains all deleted items
"""
def __delitem__(self, key):
pass
def _escape_regex_range_chars(s: str) -> str:
# escape these chars: ^-[]
for c in r"\^-[]":
s = s.replace(c, _bslash + c)
s = s.replace("\n", r"\n")
s = s.repl... | UnboundedMemo |
python | apache__airflow | airflow-core/tests/unit/cli/commands/test_connection_command.py | {
"start": 27075,
"end": 28402
} | class ____:
parser = cli_parser.get_parser()
def setup_method(self):
clear_db_connections(add_default_connections_back=False)
def test_cli_delete_connections(self, session, stdout_capture):
merge_conn(
Connection(
conn_id="new1",
conn_type="mysql... | TestCliDeleteConnections |
python | RaRe-Technologies__gensim | gensim/test/test_similarities.py | {
"start": 82082,
"end": 83218
} | class ____(unittest.TestCase):
def test_editdist_same_unicode_kind_latin1(self):
"""Test editdist returns the expected result with two Latin-1 strings."""
expected = 2
actual = editdist('Zizka', 'siska')
assert expected == actual
def test_editdist_same_unicode_kind_ucs2(self):
... | TestFastSS |
python | huggingface__transformers | src/transformers/models/swin2sr/modeling_swin2sr.py | {
"start": 30260,
"end": 33714
} | class ____(Swin2SRPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
if config.num_channels == 3 and config.num_channels_out == 3:
mean = torch.tensor([0.4488, 0.4371, 0.4040]).view(1, 3, 1, 1)
else:
mean = torch.zeros... | Swin2SRModel |
python | walkccc__LeetCode | solutions/952. Largest Component Size by Common Factor/952.py | {
"start": 514,
"end": 964
} | class ____:
def largestComponentSize(self, nums: list[int]) -> int:
ans = 0
uf = UnionFind(max(nums) + 1)
count = collections.Counter()
for num in nums:
for x in range(2, math.isqrt(num) + 1):
if num % x == 0:
uf.unionByRank(num, x)
uf.unionByRank(num, num // x)
... | Solution |
python | bokeh__bokeh | src/bokeh/util/compiler.py | {
"start": 3723,
"end": 4195
} | class ____(Implementation):
''' Base class for representing Bokeh custom model implementations that may
be given as inline code in some language.
Args:
code (str) :
The source code for the implementation
file (str, optional)
A file path to a file containing the sour... | Inline |
python | psf__requests | tests/test_utils.py | {
"start": 5046,
"end": 5531
} | class ____:
@pytest.mark.parametrize(
"value, expected",
(
([("key", "val")], [("key", "val")]),
((("key", "val"),), [("key", "val")]),
({"key": "val"}, [("key", "val")]),
(None, None),
),
)
def test_valid(self, value, expected):
... | TestToKeyValList |
python | PyCQA__pylint | tests/functional/u/unexpected_special_method_signature.py | {
"start": 2945,
"end": 3096
} | class ____:
def __enter__(self):
return self
def __exit__(self, exc_type=None, value=None, tb=None):
pass
| SecondGoodContextManager |
python | bokeh__bokeh | tests/unit/bokeh/test_client_server.py | {
"start": 2270,
"end": 2326
} | class ____(Model):
values = Dict(String, Any)
| DictModel |
python | realpython__materials | python-unittest/vehicles.py | {
"start": 249,
"end": 490
} | class ____(Vehicle):
def __init__(self, make, model, loading_capacity):
super().__init__(make, model)
self.loading_capacity = loading_capacity
def vehicle_factory(cls, *args, **kwargs):
return cls(*args, **kwargs)
| Truck |
python | walkccc__LeetCode | solutions/227. Basic Calculator II/227.py | {
"start": 0,
"end": 658
} | class ____:
def calculate(self, s: str) -> int:
ans = 0
prevNum = 0
currNum = 0
op = '+'
for i, c in enumerate(s):
if c.isdigit():
currNum = currNum * 10 + int(c)
if not c.isdigit() and c != ' ' or i == len(s) - 1:
if op == '+' or op == '-':
ans += prevNum
... | Solution |
python | agronholm__apscheduler | src/apscheduler/datastores/base.py | {
"start": 281,
"end": 678
} | class ____(DataStore):
"""Base class for data stores."""
_event_broker: EventBroker = attrs.field(init=False)
_logger: Logger = attrs.field(init=False)
async def start(
self, exit_stack: AsyncExitStack, event_broker: EventBroker, logger: Logger
) -> None:
self._event_broker = event... | BaseDataStore |
python | numba__numba | numba/testing/main.py | {
"start": 6085,
"end": 19688
} | class ____(unittest.main):
"""
A TestProgram subclass adding the following options:
* a -R option to enable reference leak detection
* a --profile option to enable profiling of the test run
* a -m option for parallel execution
* a -l option to (only) list tests
Currently the options are onl... | NumbaTestProgram |
python | sqlalchemy__sqlalchemy | test/orm/test_query.py | {
"start": 216628,
"end": 226598
} | class ____(_fixtures.FixtureTest, AssertsCompiledSQL):
run_inserts = None
__dialect__ = "default"
def _fixture1(self):
User, Address, Dingaling, HasDingaling = (
self.classes.User,
self.classes.Address,
self.classes.Dingaling,
self.classes.HasDingalin... | WithTransientOnNone |
python | sympy__sympy | sympy/physics/quantum/hilbert.py | {
"start": 6725,
"end": 7707
} | class ____(HilbertSpace):
"""The Hilbert space for second quantization.
Technically, this Hilbert space is a infinite direct sum of direct
products of single particle Hilbert spaces [1]_. This is a mess, so we have
a class to represent it directly.
Examples
========
>>> from sympy.physics... | FockSpace |
python | numpy__numpy | numpy/_core/tests/test_unicode.py | {
"start": 5146,
"end": 5301
} | class ____(CreateValues):
"""Check the creation of valued arrays (size 1, UCS4 values)"""
ulen = 1
ucs_value = ucs4_value
| TestCreateValues_1_UCS4 |
python | pypa__pip | src/pip/_internal/exceptions.py | {
"start": 27114,
"end": 28366
} | class ____(DiagnosticPipError):
"""Raised when the downloader receives fewer bytes than advertised
in the Content-Length header."""
reference = "incomplete-download"
def __init__(self, download: _FileDownload) -> None:
# Dodge circular import.
from pip._internal.utils.misc import forma... | IncompleteDownloadError |
python | wandb__wandb | tests/fixtures/wandb_backend_spy/spy.py | {
"start": 7269,
"end": 14840
} | class ____:
"""A snapshot of the W&B backend state."""
_spy: WandbBackendSpy | None
def run_ids(self) -> set[str]:
"""Returns the IDs of all runs."""
spy = self._assert_valid()
return set(spy._runs.keys())
def uploaded_files(self, *, run_id: str) -> set[str]:
"""Return... | WandbBackendSnapshot |
python | pytorch__pytorch | torch/__init__.py | {
"start": 73233,
"end": 73457
} | class ____(_LegacyStorage):
@classproperty
def dtype(self):
_warn_typed_storage_removal(stacklevel=3)
return self._dtype
@classproperty
def _dtype(self):
return torch.qint8
| QInt8Storage |
python | dagster-io__dagster | python_modules/libraries/dagster-azure/dagster_azure/fakes/fake_adls2_resource.py | {
"start": 1975,
"end": 2950
} | class ____:
"""Stateful mock of an ADLS2 service client for testing.
Wraps a ``mock.MagicMock``. Containers are implemented using an in-memory dict.
"""
def __init__(self, account_name, credential="fake-creds"):
self._account_name = account_name
self._credential = mock.MagicMock()
... | FakeADLS2ServiceClient |
python | facelessuser__soupsieve | tests/test_level4/test_scope.py | {
"start": 73,
"end": 2758
} | class ____(util.TestCase):
"""Test scope selectors."""
MARKUP = """
<html id="root">
<head>
</head>
<body>
<div id="div">
<p id="0" class="somewordshere">Some text <span id="1"> in a paragraph</span>.</p>
<a id="2" href="http://google.com">Link</a>
<span id="3" class="herewords"... | TestScope |
python | django__django | tests/custom_managers/models.py | {
"start": 5486,
"end": 5597
} | class ____(Car):
class Meta:
proxy = True
default_manager_name = "fast_cars"
| FastCarAsDefault |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_T.py | {
"start": 9839,
"end": 11344
} | class ____(Benchmark):
r"""
Trigonometric 2 objective function.
This class defines the Trigonometric 2 [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{Trigonometric2}}(x) = 1 + \sum_{i=1}^{n} 8 \sin^2
... | Trigonometric02 |
python | huggingface__transformers | tests/models/marian/test_modeling_marian.py | {
"start": 17742,
"end": 19632
} | class ____(MarianIntegrationTest):
@slow
def test_forward(self):
src, tgt = ["I am a small frog"], ["Ich bin ein kleiner Frosch."]
expected_ids = [38, 121, 14, 697, 38848, 0]
model_inputs = self.tokenizer(src, text_target=tgt, return_tensors="pt").to(torch_device)
self.assertLi... | TestMarian_EN_DE_More |
python | pytorch__pytorch | torch/testing/_internal/common_device_type.py | {
"start": 50872,
"end": 50993
} | class ____(skipIf):
def __init__(self, dep, reason):
super().__init__(dep, reason, device_type="mps")
| skipMPSIf |
python | lepture__authlib | authlib/jose/rfc7518/rsa_key.py | {
"start": 863,
"end": 4581
} | class ____(AsymmetricKey):
"""Key class of the ``RSA`` key type."""
kty = "RSA"
PUBLIC_KEY_CLS = RSAPublicKey
PRIVATE_KEY_CLS = RSAPrivateKeyWithSerialization
PUBLIC_KEY_FIELDS = ["e", "n"]
PRIVATE_KEY_FIELDS = ["d", "dp", "dq", "e", "n", "p", "q", "qi"]
REQUIRED_JSON_FIELDS = ["e", "n"]
... | RSAKey |
python | doocs__leetcode | solution/0400-0499/0488.Zuma Game/Solution.py | {
"start": 0,
"end": 853
} | class ____:
def findMinStep(self, board: str, hand: str) -> int:
def remove(s):
while len(s):
next = re.sub(r'B{3,}|G{3,}|R{3,}|W{3,}|Y{3,}', '', s)
if len(next) == len(s):
break
s = next
return s
visited = ... | Solution |
python | huggingface__transformers | src/transformers/models/qwen3_omni_moe/modeling_qwen3_omni_moe.py | {
"start": 56685,
"end": 60918
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: Qwen3OmniMoeTextConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
... | Qwen3OmniMoeThinkerTextRotaryEmbedding |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 143963,
"end": 144610
} | class ____(sgqlc.types.Input):
"""Autogenerated input type of ArchiveProjectV2Item"""
__schema__ = github_schema
__field_names__ = ("project_id", "item_id", "client_mutation_id")
project_id = sgqlc.types.Field(sgqlc.types.non_null(ID), graphql_name="projectId")
"""The ID of the Project to archive t... | ArchiveProjectV2ItemInput |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/initsubclass1.py | {
"start": 542,
"end": 610
} | class ____(ClassA, param1="0", param3=datetime.now()):
pass
| ClassC |
python | kamyu104__LeetCode-Solutions | Python/find-the-safest-path-in-a-grid.py | {
"start": 33,
"end": 765
} | class ____(object): # Time: O(n * alpha(n)), Space: O(n)
def __init__(self, n):
self.set = range(n)
self.rank = [0]*n
def find_set(self, x):
stk = []
while self.set[x] != x: # path compression
stk.append(x)
x = self.set[x]
while stk:
... | UnionFind |
python | django__django | tests/serializers/test_xml.py | {
"start": 3670,
"end": 4700
} | class ____(
SerializersTransactionTestBase, TransactionTestCase
):
serializer_name = "xml"
fwd_ref_str = """<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
<object pk="1" model="serializers.article">
<field to="serializers.author" name="author" rel="ManyToOneRel">1</field>
... | XmlSerializerTransactionTestCase |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/docstring.py | {
"start": 845,
"end": 1011
} | class ____():
# don't lose this class comment ...
"""Empty class.
But it has comments
""" # ... neither lose this class comment
| CommentBeforeDocstring |
python | ansible__ansible | test/lib/ansible_test/_internal/util.py | {
"start": 20347,
"end": 20809
} | class ____(WrappedThread, metaclass=abc.ABCMeta):
"""Thread to read stdout from a subprocess."""
def __init__(self, handle: t.IO[bytes], buffer: t.BinaryIO, name: str) -> None:
super().__init__(self._run, f'{self.__class__.__name__}: {name}')
self.handle = handle
self.buffer = buffer
... | ReaderThread |
python | keras-team__keras | integration_tests/torch_workflow_test.py | {
"start": 310,
"end": 996
} | class ____(testing.TestCase):
def test_keras_layer_in_nn_module(self):
net = Net()
# Test using Keras layer in a nn.Module.
# Test forward pass
self.assertAllEqual(list(net(torch.empty(100, 10)).shape), [100, 1])
# Test KerasVariables are added as nn.Parameter.
self.... | TorchWorkflowTest |
python | getsentry__sentry | src/sentry/models/grouplink.py | {
"start": 570,
"end": 1080
} | class ____(BaseManager["GroupLink"]):
def get_group_issues(self, group: Group, external_issue_id: str | None = None) -> QuerySet:
kwargs = dict(
group=group,
project_id=group.project_id,
linked_type=GroupLink.LinkedType.issue,
relationship=GroupLink.Relationsh... | GroupLinkManager |
python | yandexdataschool__Practical_RL | week06_policy_based/atari_wrappers.py | {
"start": 1359,
"end": 2591
} | class ____(Wrapper):
"""Makes fire action when reseting environment.
Some environments are fixed until the agent makes the fire action,
this wrapper makes this action so that the epsiode starts automatically.
"""
def __init__(self, env):
super().__init__(env)
action_meanings = env.... | FireReset |
python | Pylons__pyramid | tests/test_urldispatch.py | {
"start": 25119,
"end": 25206
} | class ____:
def __init__(self, generator):
self.generate = generator
| DummyRoute |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_table10.py | {
"start": 315,
"end": 2492
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("table10.xlsx")
self.ignore_files = [
"xl/calcChain.xml",
"[Content_Types].xml",
"xl/_rels/workbook.xml.rels... | TestCompareXLSXFiles |
python | walkccc__LeetCode | solutions/2441. Largest Positive Integer That Exists With Its Negative/2441.py | {
"start": 0,
"end": 220
} | class ____:
def findMaxK(self, nums: list[int]) -> int:
ans = -1
seen = set()
for num in nums:
if -num in seen:
ans = max(ans, abs(num))
else:
seen.add(num)
return ans
| Solution |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_primitive.py | {
"start": 8155,
"end": 12580
} | class ____:
def test_eq(self) -> None:
assert bcpp.Int() is not int
assert (bcpp.Int() == bcpp.Int()) is True
assert (bcpp.Int(default=0) == bcpp.Int()) is True
assert (bcpp.Int(default=1) == bcpp.Int()) is False
assert (bcpp.Int() == bcpp.Int(default=1)) is False
... | Test_Int |
python | Textualize__textual | src/textual/widgets/_tabbed_content.py | {
"start": 6939,
"end": 23958
} | class ____(Widget):
"""A container with associated tabs to toggle content visibility."""
ALLOW_MAXIMIZE = True
DEFAULT_CSS = """
TabbedContent {
height: auto;
&> ContentTabs {
dock: top;
}
}
"""
active: reactive[str] = reactive("", init=False)
"""The... | TabbedContent |
python | sqlalchemy__sqlalchemy | test/dialect/oracle/test_dialect.py | {
"start": 30562,
"end": 33353
} | class ____:
@property
def name(self):
raise NotImplementedError
@property
def dbapi(self):
raise NotImplementedError
@property
def dialect_cls(self):
raise NotImplementedError
def test_cx_oracle_service_name(self):
url_string = f"oracle+{self.name}://scott:... | BaseConnectArgsTest |
python | realpython__materials | python-class/square.py | {
"start": 0,
"end": 380
} | class ____:
def __init__(self, side):
self.side = side
@property
def side(self):
return self._side
@side.setter
def side(self, value):
if not isinstance(value, int | float) or value <= 0:
raise ValueError("positive number expected")
self._side = value
... | Square |
python | pypa__pipenv | pipenv/installers.py | {
"start": 7167,
"end": 8161
} | class ____(Installer):
def _find_installer(self):
return self._find_python_installer_by_name_and_env("asdf", "ASDF_DIR")
def iter_installable_versions(self):
"""Iterate through CPython versions available for asdf to install."""
for name in self._run("list-all", "python").stdout.splitlin... | Asdf |
python | realpython__materials | duck-typing-python/vehicles_abc.py | {
"start": 38,
"end": 515
} | class ____(ABC):
def __init__(self, make, model, color):
self.make = make
self.model = model
self.color = color
@abstractmethod
def start(self):
raise NotImplementedError("This method must be implemented")
@abstractmethod
def stop(self):
raise NotImplemented... | Vehicle |
python | aio-libs__aiohttp | aiohttp/web_urldispatcher.py | {
"start": 22803,
"end": 24435
} | class ____(PrefixResource):
def __init__(self, prefix: str, app: "Application") -> None:
super().__init__(prefix)
self._app = app
self._add_prefix_to_resources(prefix)
def add_prefix(self, prefix: str) -> None:
super().add_prefix(prefix)
self._add_prefix_to_resources(pre... | PrefixedSubAppResource |
python | spack__spack | var/spack/test_repos/spack_repo/builtin_mock/packages/dep_diamond_patch_mid2/package.py | {
"start": 217,
"end": 807
} | class ____(Package):
r"""Package that requires a patch on a dependency
W
/ \
X Y
\ /
Z
This is package Y
"""
homepage = "http://www.example.com"
url = "http://www.example.com/patch-a-dependency-1.0.tar.gz"
version("1.0", md5="0123456789abcdef0123456789abcdef")
# single patch fil... | DepDiamondPatchMid2 |
python | wandb__wandb | wandb/sdk/backend/backend.py | {
"start": 368,
"end": 1327
} | class ____:
interface: InterfaceBase | None
_settings: Settings
_done: bool
_service: service_connection.ServiceConnection | None
def __init__(
self,
settings: Settings,
service: service_connection.ServiceConnection | None = None,
) -> None:
self._done = False... | Backend |
python | pikepdf__pikepdf | src/pikepdf/canvas.py | {
"start": 1659,
"end": 2607
} | class ____(ABC):
"""Base class for fonts."""
@abstractmethod
def text_width(
self, text: str | bytes, fontsize: float | int | Decimal
) -> float | int | Decimal:
"""Estimate the width of a text string when rendered with the given font."""
@abstractmethod
def register(self, pdf:... | Font |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.