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 | pytorch__pytorch | torch/jit/annotations.py | {
"start": 1508,
"end": 18003
} | class ____:
env = {
"torch": Module("torch", {"Tensor": torch.Tensor}),
"Tensor": torch.Tensor,
"typing": Module("typing", {"Tuple": Tuple}),
"Tuple": Tuple,
"List": List,
"Dict": Dict,
"Optional": Optional,
"Union": Union,
"Future": Future,
... | EvalEnv |
python | spack__spack | lib/spack/spack/vendor/ruamel/yaml/scalarstring.py | {
"start": 2399,
"end": 2624
} | class ____(ScalarString):
__slots__ = ()
style = '"'
def __new__(cls, value, anchor=None):
# type: (Text, Any) -> Any
return ScalarString.__new__(cls, value, anchor=anchor)
| DoubleQuotedScalarString |
python | rapidsai__cudf | python/cudf/cudf/core/mixins/notiterable.py | {
"start": 141,
"end": 575
} | class ____:
def __iter__(self) -> None:
"""
Iteration is unsupported.
See :ref:`iteration <pandas-comparison/iteration>` for more
information.
"""
raise TypeError(
f"{self.__class__.__name__} object is not iterable. "
f"Consider using `.to_arr... | NotIterable |
python | sqlalchemy__sqlalchemy | test/ext/test_horizontal_shard.py | {
"start": 31497,
"end": 36456
} | class ____(fixtures.DeclarativeMappedTest):
def _init_dbs(self):
self.db1 = db1 = testing_engine(
"sqlite:///shard1_%s.db" % provision.FOLLOWER_IDENT
)
self.db2 = db2 = testing_engine(
"sqlite:///shard2_%s.db" % provision.FOLLOWER_IDENT
)
for db in (d... | LazyLoadIdentityKeyTest |
python | ansible__ansible | test/lib/ansible_test/_internal/cli/parsers/key_value_parsers.py | {
"start": 872,
"end": 1776
} | class ____(KeyValueParser):
"""Composite argument parser for origin key/value pairs."""
def get_parsers(self, state: ParserState) -> dict[str, Parser]:
"""Return a dictionary of key names and value parsers."""
versions = CONTROLLER_PYTHON_VERSIONS
return dict(
python=Python... | OriginKeyValueParser |
python | numba__llvmlite | llvmlite/ir/values.py | {
"start": 20819,
"end": 22912
} | class ____(GlobalValue):
"""
A global variable.
"""
def __init__(self, module, typ, name, addrspace=0):
assert isinstance(typ, types.Type)
super(GlobalVariable, self).__init__(module, typ.as_pointer(addrspace),
name=name)
self.value_t... | GlobalVariable |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 521928,
"end": 522397
} | class ____(NumBinopNode):
# '@' operator.
def is_py_operation_types(self, type1, type2):
return True
def infer_builtin_types_operation(self, type1, type2):
# We really don't know anything about this operation.
return None
def generate_evaluation_code(self, code):
code... | MatMultNode |
python | ray-project__ray | python/ray/data/tests/test_numpy_support.py | {
"start": 310,
"end": 14752
} | class ____:
def __eq__(self, other):
return isinstance(other, UserObj)
def do_map_batches(data):
ds = ray.data.range(1)
ds = ds.map_batches(lambda x: {"output": data})
return ds.take_batch()["output"]
def assert_structure_equals(a, b):
assert type(a) is type(b), (type(a), type(b))
as... | UserObj |
python | walkccc__LeetCode | solutions/1948. Delete Duplicate Folders in System/1948.py | {
"start": 0,
"end": 109
} | class ____:
def __init__(self):
self.children: dict[str, TrieNode] = {}
self.deleted = False
| TrieNode |
python | has2k1__plotnine | plotnine/scales/scale_manual.py | {
"start": 4142,
"end": 4553
} | class ____(_scale_manual):
"""
Custom discrete size scale
"""
_aesthetics = ["size"]
values: InitVar[Sequence[Any] | dict[Any, Any]]
"""
Sizes that make up the palette. The values will be matched
with the `limits` of the scale or the `breaks` if provided.
If it is a dict then it sho... | scale_size_manual |
python | coleifer__peewee | tests/regressions.py | {
"start": 47108,
"end": 48623
} | class ____(ModelTestCase):
requires = [LK]
def assertNames(self, expr, expected):
query = LK.select().where(expr).order_by(LK.id)
self.assertEqual([lk.key for lk in query], expected)
def test_like_escape(self):
names = ('foo', 'foo%', 'foo%bar', 'foo_bar', 'fooxba', 'fooba')
... | TestLikeEscape |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_aux/test_migrate_database_job.py | {
"start": 16276,
"end": 19068
} | class ____:
"""Tests migrate database job service account."""
def test_should_add_component_specific_labels(self):
docs = render_chart(
values={
"migrateDatabaseJob": {
"labels": {"test_label": "test_label_value"},
},
},
... | TestMigrateDatabaseJobServiceAccount |
python | huggingface__transformers | src/transformers/models/mlcd/modular_mlcd.py | {
"start": 5817,
"end": 7317
} | class ____(VisionRotaryEmbedding):
def forward(self, num_patches_height: int, num_patches_width: int) -> torch.Tensor:
"""
Calculate the Rotary Position Embedding (RoPE) for MLCDVisionModel based on the grid size.
Args:
num_patches_height (int): Number of patches in the height d... | MLCDRotaryEmbedding |
python | tornadoweb__tornado | tornado/platform/asyncio.py | {
"start": 2397,
"end": 10207
} | class ____(IOLoop):
def initialize( # type: ignore
self, asyncio_loop: asyncio.AbstractEventLoop, **kwargs: Any
) -> None:
# asyncio_loop is always the real underlying IOLoop. This is used in
# ioloop.py to maintain the asyncio-to-ioloop mappings.
self.asyncio_loop = asyncio_loo... | BaseAsyncIOLoop |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/nonlocal_without_binding.py | {
"start": 395,
"end": 453
} | class ____:
def method(self):
nonlocal __class__
| A |
python | huggingface__transformers | src/transformers/models/bart/modeling_bart.py | {
"start": 63711,
"end": 70348
} | class ____(BartPreTrainedModel):
def __init__(self, config):
super().__init__(config)
config.num_labels = 2
self.num_labels = config.num_labels
self.model = BartModel(config)
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights an... | BartForQuestionAnswering |
python | FactoryBoy__factory_boy | tests/test_django.py | {
"start": 8443,
"end": 10447
} | class ____(django_test.TestCase):
"""Tests class Meta:
model = 'app.Model' pattern."""
def test_loading(self):
class ExampleFactory(factory.django.DjangoModelFactory):
class Meta:
model = 'djapp.StandardModel'
self.assertEqual(models.StandardModel, ExampleFacto... | DjangoModelLoadingTestCase |
python | doocs__leetcode | solution/3000-3099/3016.Minimum Number of Pushes to Type Word II/Solution.py | {
"start": 0,
"end": 229
} | class ____:
def minimumPushes(self, word: str) -> int:
cnt = Counter(word)
ans = 0
for i, x in enumerate(sorted(cnt.values(), reverse=True)):
ans += (i // 8 + 1) * x
return ans
| Solution |
python | plotly__plotly.py | plotly/graph_objs/cone/colorbar/title/_font.py | {
"start": 233,
"end": 9898
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "cone.colorbar.title"
_path_str = "cone.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
... | Font |
python | hynek__structlog | src/structlog/dev.py | {
"start": 13418,
"end": 35448
} | class ____:
r"""
Render ``event_dict`` nicely aligned, possibly in colors, and ordered.
If ``event_dict`` contains a true-ish ``exc_info`` key, it will be rendered
*after* the log line. If Rich_ or better-exceptions_ are present, in colors
and with extra context.
Tip:
Since `ConsoleRen... | ConsoleRenderer |
python | kamyu104__LeetCode-Solutions | Python/maximum-building-height.py | {
"start": 33,
"end": 828
} | class ____(object):
def maxBuilding(self, n, restrictions):
"""
:type n: int
:type restrictions: List[List[int]]
:rtype: int
"""
restrictions.extend([[1, 0], [n, n-1]])
restrictions.sort()
for i in reversed(xrange(len(restrictions)-1)):
res... | Solution |
python | mlflow__mlflow | mlflow/server/graphql/autogenerated_graphql_schema.py | {
"start": 768,
"end": 888
} | class ____(graphene.Enum):
PENDING_REGISTRATION = 1
FAILED_REGISTRATION = 2
READY = 3
| MlflowModelVersionStatus |
python | doocs__leetcode | solution/2400-2499/2421.Number of Good Paths/Solution.py | {
"start": 0,
"end": 839
} | class ____:
def numberOfGoodPaths(self, vals: List[int], edges: List[List[int]]) -> int:
def find(x):
if p[x] != x:
p[x] = find(p[x])
return p[x]
g = defaultdict(list)
for a, b in edges:
g[a].append(b)
g[b].append(a)
n... | Solution |
python | cython__cython | Cython/Compiler/Nodes.py | {
"start": 207538,
"end": 207655
} | class ____(AsyncDefNode):
gen_type_name = 'IterableCoroutine'
is_iterable_coroutine = True
| IterableAsyncDefNode |
python | huggingface__transformers | src/transformers/generation/stopping_criteria.py | {
"start": 27636,
"end": 28874
} | class ____(list):
@add_start_docstrings(STOPPING_CRITERIA_INPUTS_DOCSTRING)
def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> torch.BoolTensor:
is_done = torch.full((input_ids.shape[0],), False, device=input_ids.device, dtype=torch.bool)
for criteria in self... | StoppingCriteriaList |
python | apache__airflow | airflow-core/src/airflow/providers_manager.py | {
"start": 3111,
"end": 6106
} | class ____(MutableMapping):
"""
Lazy-loaded cached dictionary.
Dictionary, which in case you set callable, executes the passed callable with `key` attribute
at first use - and returns and caches the result.
"""
__slots__ = ["_resolved", "_raw_dict"]
def __init__(self, *args, **kw):
... | LazyDictWithCache |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/helpers/cli.py | {
"start": 999,
"end": 2958
} | class ____:
quiet: bool = True
help_message: Optional[str] = None
def log_command_results(
ctx: click.Context, command_results: List[CommandResult], logger: Logger, options: LogOptions = LogOptions()
) -> None:
"""
Log the output of the subcommands run by `run_all_subcommands`.
"""
if not... | LogOptions |
python | cython__cython | docs/examples/userguide/language_basics/optional_subclassing.py | {
"start": 96,
"end": 191
} | class ____(A):
@cython.cfunc
def foo(self, x=None):
print("B", x)
@cython.cclass
| B |
python | huggingface__transformers | tests/models/speecht5/test_modeling_speecht5.py | {
"start": 52523,
"end": 56969
} | class ____:
def __init__(
self,
parent,
batch_size=13,
encoder_seq_length=1024, # speech is longer
decoder_seq_length=1024,
is_training=False,
hidden_size=24,
num_hidden_layers=2,
num_attention_heads=2,
intermediate_size=4,
con... | SpeechT5ForSpeechToSpeechTester |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_bad_repr.py | {
"start": 465,
"end": 1278
} | class ____:
def __init__(self, value):
self.value = value
def __repr__(self):
return self.value
Frosty = BadRepr("☃")
def test_just_frosty():
assert repr(st.just(Frosty)) == "just(☃)"
def test_sampling_snowmen():
assert repr(st.sampled_from((Frosty, "hi"))) == "sampled_from((☃, 'h... | BadRepr |
python | scikit-image__scikit-image | benchmarks/benchmark_morphology.py | {
"start": 2296,
"end": 4994
} | class ____:
param_names = ["shape", "footprint", "radius", "decomposition"]
params = [
((512, 512),),
("square", "diamond", "octagon", "disk", "ellipse", "star"),
(1, 3, 5, 15, 25, 40),
(None, "sequence", "separable", "crosses"),
]
def setup(self, shape, footprint, radiu... | GrayMorphology2D |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py | {
"start": 2295,
"end": 2647
} | class ____(TypedDict):
"""Response when a human rejects the action."""
type: Literal["reject"]
"""The type of response when a human rejects the action."""
message: NotRequired[str]
"""The message sent to the model explaining why the action was rejected."""
Decision = ApproveDecision | EditDecisi... | RejectDecision |
python | django__django | tests/messages_tests/test_fallback.py | {
"start": 410,
"end": 6868
} | class ____(BaseTests, SimpleTestCase):
storage_class = FallbackStorage
def get_request(self):
self.session = {}
request = super().get_request()
request.session = self.session
return request
def get_cookie_storage(self, storage):
return storage.storages[-2]
def ... | FallbackTests |
python | falconry__falcon | falcon/testing/helpers.py | {
"start": 14218,
"end": 58300
} | class ____:
"""Simulates a WebSocket client for testing a Falcon ASGI app.
This class provides a way to test WebSocket endpoints in a Falcon ASGI app
without having to interact with an actual ASGI server. While it is certainly
important to test against a real server, a number of functional tests can be... | ASGIWebSocketSimulator |
python | google__jax | jax/_src/pallas/core.py | {
"start": 10556,
"end": 13044
} | class ____:
"""Allows to specify a bounded slice of a dimension.
Specifically, the index_map need to return a `pl.Slice/pl.ds` for this
dimension. The start and size may be dynamic, as long as the size <=
block_size.
"""
block_size: int
def __repr__(self):
return f"BoundedSlice({self.block_size})"
... | BoundedSlice |
python | PyCQA__pylint | pylint/pyreverse/main.py | {
"start": 9855,
"end": 11732
} | class ____(_ArgumentsManager, _ArgumentsProvider):
options = OPTIONS
name = "pyreverse"
def __init__(self, args: Sequence[str]) -> None:
# Immediately exit if user asks for version
if "--version" in args:
print("pyreverse is included in pylint:")
print(constants.full... | Run |
python | tiangolo__fastapi | docs_src/response_model/tutorial006_py310.py | {
"start": 78,
"end": 816
} | class ____(BaseModel):
name: str
description: str | None = None
price: float
tax: float = 10.5
items = {
"foo": {"name": "Foo", "price": 50.2},
"bar": {"name": "Bar", "description": "The Bar fighters", "price": 62, "tax": 20.2},
"baz": {
"name": "Baz",
"description": "There... | Item |
python | tensorflow__tensorflow | tensorflow/python/framework/extension_type_test.py | {
"start": 5901,
"end": 6075
} | class ____(extension_type.ExtensionType):
x: tensor.Tensor = 5
y: tensor.Tensor = ['a', 'b', 'c']
@test_util.run_all_in_graph_and_eager_modes
| ExtensionTypeWithTensorDefault |
python | huggingface__transformers | tests/models/bit/test_modeling_bit.py | {
"start": 9358,
"end": 10331
} | class ____(unittest.TestCase):
@cached_property
def default_image_processor(self):
return BitImageProcessor.from_pretrained("google/bit-50") if is_vision_available() else None
@slow
def test_inference_image_classification_head(self):
model = BitForImageClassification.from_pretrained("go... | BitModelIntegrationTest |
python | tox-dev__tox | src/tox/config/types.py | {
"start": 220,
"end": 295
} | class ____(ValueError):
"""circular chain in config"""
| CircularChainError |
python | spyder-ide__spyder | spyder/widgets/tabs.py | {
"start": 15197,
"end": 22798
} | class ____(QTabWidget):
"""TabWidget with context menu and corner widgets"""
sig_close_tab = Signal(int)
def __init__(self, parent, actions=None, menu=None,
corner_widgets=None, menu_use_tooltips=False):
QTabWidget.__init__(self, parent)
self.setTabBar(TabBar(self, parent))... | BaseTabs |
python | openai__openai-python | src/openai/types/beta/realtime/conversation_item_retrieve_event_param.py | {
"start": 234,
"end": 579
} | class ____(TypedDict, total=False):
item_id: Required[str]
"""The ID of the item to retrieve."""
type: Required[Literal["conversation.item.retrieve"]]
"""The event type, must be `conversation.item.retrieve`."""
event_id: str
"""Optional client-generated ID used to identify this event."""
| ConversationItemRetrieveEventParam |
python | readthedocs__readthedocs.org | readthedocs/proxito/views/serve.py | {
"start": 15662,
"end": 25720
} | class ____(CDNCacheControlMixin, ServeRedirectMixin, ServeDocsMixin, View):
"""
Proxito handler for 404 pages.
This view is called by an internal nginx redirect when there is a 404.
"""
def get(self, request, proxito_path):
"""
Handler for 404 pages on subdomains.
This doe... | ServeError404Base |
python | celery__celery | t/unit/tasks/test_tasks.py | {
"start": 814,
"end": 997
} | class ____(Task):
abstract = True
applied = 0
def run(self, x, y):
return x * y
def apply_async(self, *args, **kwargs):
self.applied += 1
| MockApplyTask |
python | has2k1__plotnine | plotnine/scales/scale_shape.py | {
"start": 1045,
"end": 1512
} | class ____(scale_discrete):
"""
Scale for shapes
"""
_aesthetics = ["shape"]
unfilled: InitVar[bool] = False
"""
If `True`, then all shapes will have no interiors
that can be a filled.
"""
def __post_init__(self, unfilled):
from mizani.palettes import manual_pal
... | scale_shape |
python | ray-project__ray | python/ray/_private/worker.py | {
"start": 7008,
"end": 7823
} | class ____(HasOptions, Generic[R, T0, T1, T2, T3, T4, T5]):
def __init__(self, function: Callable[[T0, T1, T2, T3, T4, T5], R]) -> None:
pass
def remote(
self,
__arg0: "Union[T0, ObjectRef[T0]]",
__arg1: "Union[T1, ObjectRef[T1]]",
__arg2: "Union[T2, ObjectRef[T2]]",
... | RemoteFunction5 |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/psycopg2cffi.py | {
"start": 827,
"end": 1756
} | class ____(PGDialect_psycopg2):
driver = "psycopg2cffi"
supports_unicode_statements = True
supports_statement_cache = True
# psycopg2cffi's first release is 2.5.0, but reports
# __version__ as 2.4.4. Subsequent releases seem to have
# fixed this.
FEATURE_VERSION_MAP = dict(
native... | PGDialect_psycopg2cffi |
python | joke2k__faker | tests/providers/test_automotive.py | {
"start": 3209,
"end": 3379
} | class ____(_SimpleAutomotiveTestMixin):
"""Test el_GR automotive provider methods"""
license_plate_pattern = re.compile(r"^(?P<prefix>[A-Z]{2,3}) \d{4}$")
| TestElGr |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-cart/source_cart/source.py | {
"start": 1286,
"end": 3116
} | class ____(AbstractHeaderAuthenticator):
def __init__(self, user_name, user_secret, site_id):
self.auth_method = AuthMethod.CENTRAL_API_ROUTER
self.user_name = user_name
self.user_secret = user_secret
self.site_id = site_id
def get_auth_header(self) -> Mapping[str, Any]:
... | CentralAPIHeaderAuthenticator |
python | great-expectations__great_expectations | great_expectations/checkpoint/actions.py | {
"start": 9831,
"end": 10452
} | class ____(ValidationAction):
def _build_data_docs(
self,
site_names: list[str] | None = None,
resource_identifiers: list | None = None,
) -> dict:
return project_manager.build_data_docs(
site_names=site_names, resource_identifiers=resource_identifiers
)
... | DataDocsAction |
python | huggingface__transformers | tests/models/gemma3n/test_modeling_gemma3n.py | {
"start": 9594,
"end": 12394
} | class ____(CausalLMModelTester):
if is_torch_available():
base_model_class = Gemma3nTextModel
causal_lm_class = Gemma3nForCausalLM
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_ty... | Gemma3nTextModelTester |
python | sqlalchemy__sqlalchemy | examples/versioned_rows/versioned_rows_w_versionid.py | {
"start": 2717,
"end": 3263
} | class ____(Versioned, Base):
__tablename__ = "example"
data = Column(String)
Base.metadata.create_all(engine)
session = Session()
e1 = Example(id=1, data="e1")
session.add(e1)
session.commit()
e1.data = "e2"
session.commit()
assert session.query(
Example.id,
Example.version_id,
Example.is_curre... | Example |
python | pytorch__pytorch | torch/_inductor/codegen/triton.py | {
"start": 70815,
"end": 71006
} | class ____:
config: dict[str, int]
def __getitem__(self, item):
return self.config[item]
def __contains__(self, item):
return item in self.config
| FixedTritonConfig |
python | django__django | tests/gis_tests/test_geoforms.py | {
"start": 18299,
"end": 21048
} | class ____(SimpleTestCase):
def test_get_context_attrs(self):
# The Widget.get_context() attrs argument overrides self.attrs.
widget = BaseGeometryWidget(attrs={"geom_type": "POINT"})
context = widget.get_context("point", None, attrs={"geom_type": "POINT2"})
self.assertEqual(context[... | GeometryWidgetTests |
python | getsentry__sentry | src/sentry/hybridcloud/models/apitokenreplica.py | {
"start": 419,
"end": 2240
} | class ____(Model, HasApiScopes):
__relocation_scope__ = RelocationScope.Excluded
application_id = HybridCloudForeignKey("sentry.ApiApplication", null=True, on_delete="CASCADE")
organization = FlexibleForeignKey("sentry.Organization", null=True, on_delete=models.SET_NULL)
application_is_active = models.... | ApiTokenReplica |
python | huggingface__transformers | src/transformers/models/blip/modeling_blip.py | {
"start": 46840,
"end": 51136
} | class ____(BlipPreTrainedModel):
config: BlipConfig
def __init__(self, config: BlipConfig):
super().__init__(config)
self.vision_model = BlipVisionModel(config.vision_config)
self.text_encoder = BlipTextModel(config.text_config, add_pooling_layer=False)
# vision projection la... | BlipForImageTextRetrieval |
python | jd__tenacity | tests/test_asyncio.py | {
"start": 1620,
"end": 4547
} | class ____(unittest.TestCase):
@asynctest
async def test_retry(self):
thing = NoIOErrorAfterCount(5)
await _retryable_coroutine(thing)
assert thing.counter == thing.count
@asynctest
async def test_iscoroutinefunction(self):
assert asyncio.iscoroutinefunction(_retryable_c... | TestAsyncio |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-fauna/unit_tests/test_util.py | {
"start": 938,
"end": 1139
} | class ____:
def __init__(
self,
page_size=64,
deletions=DeletionsConfig.ignore(),
):
self.page_size = page_size
self.deletions = deletions
| CollectionConfig |
python | sqlalchemy__sqlalchemy | test/orm/test_session_state_change.py | {
"start": 208,
"end": 296
} | class ____(state_changes._StateChangeState):
a = 1
b = 2
c = 3
| StateTestChange |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI034.py | {
"start": 10300,
"end": 10543
} | class ____[T](list):
def __new__(cls: type[Generic1]) -> Generic1: ...
def __enter__(self: Generic1) -> Generic1: ...
### Correctness of typevar-likes are not verified.
T = TypeVar('T')
P = ParamSpec()
Ts = TypeVarTuple('foo')
| Generic1 |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/definitions/partitions/subset/all.py | {
"start": 554,
"end": 4766
} | class ____(PartitionsSubset):
"""This is an in-memory (i.e. not serializable) convenience class that represents all partitions
of a given PartitionsDefinition, allowing set operations to be taken without having to load
all partition keys immediately.
"""
def __init__(self, partitions_def: Partition... | AllPartitionsSubset |
python | scrapy__scrapy | tests/test_utils_defer.py | {
"start": 2241,
"end": 2948
} | class ____:
def test_iter_errback_good(self):
def itergood() -> Generator[int, None, None]:
yield from range(10)
errors = []
out = list(iter_errback(itergood(), errors.append))
assert out == list(range(10))
assert not errors
def test_iter_errback_bad(self):
... | TestIterErrback |
python | neetcode-gh__leetcode | python/0131-palindrome-partitioning.py | {
"start": 0,
"end": 593
} | class ____:
def partition(self, s: str) -> List[List[str]]:
res, part = [], []
def dfs(i):
if i >= len(s):
res.append(part.copy())
return
for j in range(i, len(s)):
if self.isPali(s, i, j):
part.append(s[i :... | Solution |
python | getsentry__sentry | src/sentry/models/authprovider.py | {
"start": 1326,
"end": 9641
} | class ____(ReplicatedControlModel):
__relocation_scope__ = RelocationScope.Global
category = OutboxCategory.AUTH_PROVIDER_UPDATE
organization_id = HybridCloudForeignKey("sentry.Organization", on_delete="cascade", unique=True)
provider = models.CharField(max_length=128)
config = models.JSONField(def... | AuthProvider |
python | getsentry__sentry | src/sentry/api/serializers/models/userrollback.py | {
"start": 78,
"end": 177
} | class ____(TypedDict):
id: int
name: str
slug: str
| RollbackOrganizationSerializerResponse |
python | pdm-project__pdm | src/pdm/installers/manager.py | {
"start": 417,
"end": 3079
} | class ____:
"""The manager that performs the installation and uninstallation actions."""
# The packages below are needed to load paths and thus should not be cached.
NO_CACHE_PACKAGES = ("editables",)
def __init__(
self, environment: BaseEnvironment, *, use_install_cache: bool = False, rename_... | InstallManager |
python | MongoEngine__mongoengine | tests/test_connection.py | {
"start": 864,
"end": 25843
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
disconnect_all()
@classmethod
def tearDownClass(cls):
disconnect_all()
def tearDown(self):
mongoengine.connection._connection_settings = {}
mongoengine.connection._connections = {}
mongoengine.... | ConnectionTest |
python | allegroai__clearml | clearml/backend_api/services/v2_13/projects.py | {
"start": 2047,
"end": 9823
} | class ____(NonStrictDataModel):
"""
:param id: Project id
:type id: str
:param name: Project name
:type name: str
:param description: Project description
:type description: str
:param user: Associated user id
:type user: str
:param company: Company id
:type company: str
:... | Project |
python | kamyu104__LeetCode-Solutions | Python/count-the-number-of-ideal-arrays.py | {
"start": 328,
"end": 2173
} | class ____(object):
def idealArrays(self, n, maxValue):
"""
:type n: int
:type maxValue: int
:rtype: int
"""
MOD = 10**9+7
fact, inv, inv_fact = [[1]*2 for _ in xrange(3)]
def nCr(n, k):
while len(inv) <= n: # lazy initialization
... | Solution |
python | openai__openai-python | src/openai/types/beta/thread_deleted.py | {
"start": 190,
"end": 292
} | class ____(BaseModel):
id: str
deleted: bool
object: Literal["thread.deleted"]
| ThreadDeleted |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/streams.py | {
"start": 73377,
"end": 76868
} | class ____(GithubStream):
"""
API docs: https://docs.github.com/en/rest/metrics/statistics?apiVersion=2022-11-28#get-all-contributor-commit-activity
"""
def path(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> str:
return f"repos/{stream_slice['repository']}/stats/contributors"
... | ContributorActivity |
python | pytorch__pytorch | torch/_inductor/ir.py | {
"start": 30537,
"end": 35156
} | class ____(IRNode):
device: torch.device
dtype: torch.dtype
inner_fn: Callable[..., Any]
ranges: Sequence[_IntLike]
@cache_on_self_and_args("Loops")
def get_free_symbol_uses(
self, unbacked_only: bool = False
) -> OrderedSet[sympy.Symbol]:
return OrderedSet().union(
... | Loops |
python | agronholm__apscheduler | src/apscheduler/eventbrokers/base.py | {
"start": 3309,
"end": 5808
} | class ____(BaseEventBroker, RetryMixin):
"""
Base class for event brokers that use an external service.
:param serializer: the serializer used to (de)serialize events for transport
"""
serializer: Serializer = attrs.field(factory=JSONSerializer)
def generate_notification(self, event: Event) -... | BaseExternalEventBroker |
python | sympy__sympy | sympy/logic/boolalg.py | {
"start": 36804,
"end": 39282
} | class ____(BooleanFunction):
r"""
Logical implication.
A implies B is equivalent to if A then B. Mathematically, it is written
as `A \Rightarrow B` and is equivalent to `\neg A \vee B` or ``~A | B``.
Accepts two Boolean arguments; A and B.
Returns False if A is True and B is False
Returns ... | Implies |
python | joke2k__faker | faker/providers/automotive/en_NZ/__init__.py | {
"start": 48,
"end": 640
} | class ____(AutomotiveProvider):
"""Implement automotive provider for ``en_NZ`` locale.
Sources:
- https://en.wikipedia.org/wiki/Vehicle_registration_plates_of_New_Zealand
"""
license_formats = (
# Old plates
"??%##",
"??%###",
"??%###",
# Three letters sinc... | Provider |
python | scipy__scipy | scipy/stats/_multivariate.py | {
"start": 200787,
"end": 211953
} | class ____(multi_rv_generic):
r"""Contingency tables from independent samples with fixed marginal sums.
This is the distribution of random tables with given row and column vector
sums. This distribution represents the set of random tables under the null
hypothesis that rows and columns are independent.... | random_table_gen |
python | apache__avro | lang/py/avro/datafile.py | {
"start": 2077,
"end": 2178
} | class ____(TypedDict):
magic: bytes
meta: MutableMapping[str, bytes]
sync: bytes
| HeaderType |
python | pandas-dev__pandas | pandas/tests/indexing/test_partial.py | {
"start": 8178,
"end": 24131
} | class ____:
def test_partial_setting(self):
# GH2578, allow ix and friends to partially set
# series
s_orig = Series([1, 2, 3])
s = s_orig.copy()
s[5] = 5
expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5])
tm.assert_series_equal(s, expected)
s = s_... | TestPartialSetting |
python | realpython__materials | python-protocol/birds_v1.py | {
"start": 0,
"end": 138
} | class ____:
def quack(self):
return "The duck is quacking!"
def make_it_quack(duck: Duck) -> str:
return duck.quack()
| Duck |
python | doocs__leetcode | solution/0300-0399/0315.Count of Smaller Numbers After Self/Solution2.py | {
"start": 1180,
"end": 1539
} | class ____:
def countSmaller(self, nums: List[int]) -> List[int]:
s = sorted(set(nums))
m = {v: i for i, v in enumerate(s, 1)}
tree = SegmentTree(len(s))
ans = []
for v in nums[::-1]:
x = m[v]
ans.append(tree.query(1, 1, x - 1))
tree.modify... | Solution |
python | getsentry__sentry | src/sentry/workflow_engine/endpoints/serializers/group_open_period_serializer.py | {
"start": 1333,
"end": 2682
} | class ____(Serializer):
def get_attrs(self, item_list, user, **kwargs):
result: defaultdict[GroupOpenPeriod, dict[str, list[GroupOpenPeriodActivityResponse]]] = (
defaultdict(dict)
)
activities = GroupOpenPeriodActivity.objects.filter(
group_open_period__in=item_list
... | GroupOpenPeriodSerializer |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_blank05.py | {
"start": 315,
"end": 1514
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_blank05.xlsx")
self.ignore_elements = {"xl/drawings/drawing1.xml": ["<xdr:ext"]}
def test_create_file(self):
"""Test the wor... | TestCompareXLSXFiles |
python | getlogbook__logbook | src/logbook/more.py | {
"start": 13937,
"end": 14822
} | class ____(Handler, StringFormatterHandlerMixin):
"""An exception handler which raises exceptions of the given `exc_type`.
This is especially useful if you set a specific error `level` e.g. to treat
warnings as exceptions::
from logbook.more import ExceptionHandler
class ApplicationWarnin... | ExceptionHandler |
python | PrefectHQ__prefect | tests/test_flows.py | {
"start": 147636,
"end": 148305
} | class ____:
"""
A mock storage class that simulates pulling code from a remote location.
"""
def __init__(self):
self._base_path = Path.cwd()
def set_base_path(self, path: Path):
self._base_path = path
@property
def destination(self):
return self._base_path
@p... | MockStorage |
python | cython__cython | Cython/Compiler/ExprNodes.py | {
"start": 442325,
"end": 443073
} | class ____(ExprNode):
# CyFunction's literal argument default value
#
# Evaluate literal only once.
subexprs = []
is_literal = True
is_temp = False
def __init__(self, pos, arg):
super().__init__(pos)
self.arg = arg
self.constant_result = arg.constant_result
... | DefaultLiteralArgNode |
python | django__django | tests/migrations/test_migrations_conflict/0002_conflicting_second.py | {
"start": 43,
"end": 316
} | class ____(migrations.Migration):
dependencies = [("migrations", "0001_initial")]
operations = [
migrations.CreateModel(
"Something",
[
("id", models.AutoField(primary_key=True)),
],
)
]
| Migration |
python | huggingface__transformers | src/transformers/models/prompt_depth_anything/configuration_prompt_depth_anything.py | {
"start": 1436,
"end": 8090
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`PromptDepthAnythingModel`]. It is used to instantiate a PromptDepthAnything
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults wi... | PromptDepthAnythingConfig |
python | pandas-dev__pandas | pandas/tseries/holiday.py | {
"start": 18885,
"end": 20445
} | class ____(AbstractHolidayCalendar):
"""
US Federal Government Holiday Calendar based on rules specified by:
https://www.opm.gov/policy-data-oversight/pay-leave/federal-holidays/
"""
rules = [
Holiday("New Year's Day", month=1, day=1, observance=nearest_workday),
USMartinLutherKingJ... | USFederalHolidayCalendar |
python | mlflow__mlflow | mlflow/types/responses_helpers.py | {
"start": 1400,
"end": 1499
} | class ____(BaseModel):
file_id: str
index: int
type: str = "file_path"
| AnnotationFilePath |
python | jazzband__django-polymorphic | src/polymorphic/showfields.py | {
"start": 5709,
"end": 5876
} | class ____(ShowFieldBase):
"""model mixin that shows the object's class, it's fields and field contents"""
polymorphic_showfield_content = True
| ShowFieldContent |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_indiana_zip.py | {
"start": 1743,
"end": 4078
} | class ____(ColumnMapExpectation):
"""Expect values in this column to be valid Indiana zipcodes.
See https://pypi.org/project/zipcodes/ for more information.
"""
# These examples will be shown in the public gallery.
# They will also be executed as unit tests for your Expectation.
examples = [
... | ExpectColumnValuesToBeValidIndianaZip |
python | openai__openai-python | src/openai/types/beta/thread_create_and_run_params.py | {
"start": 7071,
"end": 7355
} | class ____(TypedDict, total=False):
type: Required[Literal["file_search"]]
"""The type of tool being defined: `file_search`"""
ThreadMessageAttachmentTool: TypeAlias = Union[CodeInterpreterToolParam, ThreadMessageAttachmentToolFileSearch]
| ThreadMessageAttachmentToolFileSearch |
python | ansible__ansible | lib/ansible/plugins/httpapi/__init__.py | {
"start": 230,
"end": 3093
} | class ____(AnsiblePlugin):
def __init__(self, connection):
super(HttpApiBase, self).__init__()
self.connection = connection
self._become = False
self._become_pass = ''
def set_become(self, become_context):
self._become = become_context.become
self._become_pass =... | HttpApiBase |
python | wandb__wandb | wandb/vendor/pygments/lexers/j.py | {
"start": 415,
"end": 4525
} | class ____(RegexLexer):
"""
For `J <http://jsoftware.com/>`_ source code.
.. versionadded:: 2.1
"""
name = 'J'
aliases = ['j']
filenames = ['*.ijs']
mimetypes = ['text/x-j']
validName = r'\b[a-zA-Z]\w*'
tokens = {
'root': [
# Shebang script
(r'... | JLexer |
python | sqlalchemy__sqlalchemy | test/dialect/postgresql/test_types.py | {
"start": 119168,
"end": 121694
} | class ____(
fixtures.TestBase, AssertsCompiledSQL, AssertsExecutionResults
):
__only_on__ = "postgresql"
__backend__ = True
def test_timestamp(self, connection):
s = select(text("timestamp '2007-12-25'"))
result = connection.execute(s).first()
eq_(result[0], datetime.datetime(20... | TimestampTest |
python | python__mypy | mypy/main.py | {
"start": 13017,
"end": 14884
} | class ____(argparse.ArgumentParser):
"""Override ArgumentParser methods that use sys.stdout/sys.stderr directly.
This is needed because hijacking sys.std* is not thread-safe,
yet output must be captured to properly support mypy.api.run.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
... | CapturableArgumentParser |
python | great-expectations__great_expectations | great_expectations/metrics/column/values_match_regex_values.py | {
"start": 201,
"end": 418
} | class ____(ColumnMetric[ColumnValuesMatchRegexValuesResult]):
"""List of values in a column that match a regex"""
name = "column_values.match_regex"
regex: str
limit: int = 20
| ColumnValuesMatchRegexValues |
python | ansible__ansible | test/units/plugins/action/test_action.py | {
"start": 2720,
"end": 3019
} | class ____(ActionBase):
TRANSFERS_FILES = False
def run(self, tmp=None, task_vars=None):
# We're not testing the plugin run() method, just the helper
# methods ActionBase defines
return super(DerivedActionBase, self).run(tmp=tmp, task_vars=task_vars)
| DerivedActionBase |
python | tensorflow__tensorflow | tensorflow/python/keras/testing_utils.py | {
"start": 17149,
"end": 18712
} | class ____(models.Model):
"""A subclass model small MLP that uses a custom build method."""
def __init__(self, num_hidden, num_classes):
super(_SmallSubclassMLPCustomBuild, self).__init__()
self.layer_a = None
self.layer_b = None
self.num_hidden = num_hidden
self.num_classes = num_classes
de... | _SmallSubclassMLPCustomBuild |
python | django__django | tests/raw_query/models.py | {
"start": 1347,
"end": 1386
} | class ____(Author):
pass
| FriendlyAuthor |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.