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 | facebookresearch__faiss | tests/test_contrib.py | {
"start": 23376,
"end": 25611
} | class ____(unittest.TestCase):
@contextmanager
def temp_directory(self):
temp_dir = tempfile.mkdtemp()
try:
yield temp_dir
finally:
shutil.rmtree(temp_dir)
def do_test_ondisk_merge(self, shift_ids=False):
with self.temp_directory() as tmpdir:
... | TestMerge |
python | huggingface__transformers | src/transformers/models/vitmatte/modeling_vitmatte.py | {
"start": 7560,
"end": 10713
} | class ____(VitMattePreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.config = config
self.backbone = load_backbone(config)
self.decoder = VitMatteDetailCaptureModule(config)
# Initialize weights and apply final processing
self.post_init()
... | VitMatteForImageMatting |
python | pytorch__pytorch | torch/distributions/transforms.py | {
"start": 18328,
"end": 18767
} | class ____(Transform):
r"""
Transform via the mapping :math:`y = \exp(x)`.
"""
domain = constraints.real
codomain = constraints.positive
bijective = True
sign = +1
def __eq__(self, other):
return isinstance(other, ExpTransform)
def _call(self, x):
return x.exp()
... | ExpTransform |
python | google__pytype | pytype/imports/typeshed.py | {
"start": 5167,
"end": 15506
} | class ____:
"""A typeshed installation.
The location is either retrieved from the environment variable
"TYPESHED_HOME" (if set) or otherwise assumed to be directly under
pytype (i.e., /{some_path}/pytype/typeshed).
"""
# Text file of typeshed entries that will not be loaded.
# The path is relative to ty... | Typeshed |
python | celery__celery | celery/fixups/django.py | {
"start": 1833,
"end": 3664
} | class ____:
"""Fixup installed when using Django."""
def __init__(self, app: "Celery"):
self.app = app
if _state.default_app is None:
self.app.set_default()
self._worker_fixup: Optional["DjangoWorkerFixup"] = None
def install(self) -> "DjangoFixup":
# Need to ad... | DjangoFixup |
python | scipy__scipy | scipy/sparse/linalg/_interface.py | {
"start": 27501,
"end": 29583
} | class ____(LinearOperator):
def __init__(self, shape, dtype=None):
super().__init__(dtype, shape)
def _matvec(self, x):
return x
def _rmatvec(self, x):
return x
def _rmatmat(self, x):
return x
def _matmat(self, x):
return x
def _adjoint(self):
... | IdentityOperator |
python | pytorch__pytorch | torch/distributed/tensor/parallel/style.py | {
"start": 13153,
"end": 18353
} | class ____(ParallelStyle):
"""
SequenceParallel replicates a compatible ``nn.Module`` parameters and runs the sharded computation with
input sharded on the sequence dimension. This currently supports ``nn.LayerNorm``, ``nn.Dropout``, and the
`RMSNorm python implementation <https://github.com/facebookres... | SequenceParallel |
python | Pylons__pyramid | src/pyramid/scripts/ptweens.py | {
"start": 331,
"end": 3997
} | class ____:
description = """\
Print all implicit and explicit tween objects used by a Pyramid
application. The handler output includes whether the system is using an
explicit tweens ordering (will be true when the "pyramid.tweens"
deployment setting is used) or an implicit tweens ordering (will be... | PTweensCommand |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/memberAccess4.py | {
"start": 395,
"end": 622
} | class ____(Mixin1):
pass
A1().do_stuff()
# This should generate an error because B1 doesn't
# match the protocol.
B1().do_stuff()
# This should generate an error because C1 doesn't
# match the protocol.
C1().do_stuff()
| C1 |
python | python-poetry__poetry | src/poetry/console/commands/new.py | {
"start": 334,
"end": 2864
} | class ____(InitCommand):
name = "new"
description = "Creates a new Python project at <path>."
arguments: ClassVar[list[Argument]] = [
argument("path", "The path to create the project at.")
]
options: ClassVar[list[Option]] = [
option(
"interactive",
"i",
... | NewCommand |
python | huggingface__transformers | src/transformers/models/focalnet/modeling_focalnet.py | {
"start": 23414,
"end": 24187
} | class ____(PreTrainedModel):
config: FocalNetConfig
base_model_prefix = "focalnet"
main_input_name = "pixel_values"
supports_gradient_checkpointing = True
_no_split_modules = ["FocalNetStage"]
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights"""
sup... | FocalNetPreTrainedModel |
python | wandb__wandb | wandb/vendor/pygments/styles/xcode.py | {
"start": 384,
"end": 1501
} | class ____(Style):
"""
Style similar to the Xcode default colouring theme.
"""
default_style = ''
styles = {
Comment: '#177500',
Comment.Preproc: '#633820',
String: '#C41A16',
String.Char: '#2300CE',
Operato... | XcodeStyle |
python | neetcode-gh__leetcode | python/0452-minimum-number-of-arrows-to-burst-balloons.py | {
"start": 0,
"end": 418
} | class ____:
def findMinArrowShots(self, points: List[List[int]]) -> int:
points.sort()
res = len(points)
prev = points[0]
for i in range(1, len(points)):
curr = points[i]
if curr[0] <= prev[1]:
res -= 1
prev = [curr[0], min(cur... | Solution |
python | doocs__leetcode | lcof/面试题57 - II. 和为s的连续正数序列/Solution.py | {
"start": 0,
"end": 400
} | class ____:
def findContinuousSequence(self, target: int) -> List[List[int]]:
l, r = 1, 2
ans = []
while l < r:
s = (l + r) * (r - l + 1) // 2
if s == target:
ans.append(list(range(l, r + 1)))
l += 1
elif s < target:
... | Solution |
python | fastapi__sqlmodel | docs_src/tutorial/fastapi/relationships/tutorial001_py39.py | {
"start": 257,
"end": 419
} | class ____(TeamBase, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
heroes: list["Hero"] = Relationship(back_populates="team")
| Team |
python | python__mypy | mypyc/ir/ops.py | {
"start": 36327,
"end": 37555
} | class ____(RegisterOp):
"""Raise built-in exception with an optional error string.
We have a separate opcode for this for convenience and to
generate smaller, more idiomatic C code.
"""
# TODO: Make it more explicit at IR level that this always raises
error_kind = ERR_FALSE
VALUE_ERROR: ... | RaiseStandardError |
python | openai__openai-python | tests/api_resources/conversations/test_items.py | {
"start": 531,
"end": 9575
} | class ____:
parametrize = pytest.mark.parametrize("client", [False, True], indirect=True, ids=["loose", "strict"])
@parametrize
def test_method_create(self, client: OpenAI) -> None:
item = client.conversations.items.create(
conversation_id="conv_123",
items=[
... | TestItems |
python | python__mypy | mypy/types.py | {
"start": 130823,
"end": 134770
} | class ____(ProperType):
"""Temporary, yet-unknown type during semantic analysis.
This is needed when there's a reference to a type before the real symbol
table entry of the target type is available (specifically, we use a
temporary PlaceholderNode symbol node). Consider this example:
class str(S... | PlaceholderType |
python | django__django | tests/model_fields/test_integerfield.py | {
"start": 9093,
"end": 9284
} | class ____(IntegerFieldTests):
model = BigIntegerModel
documented_range = (-9223372036854775808, 9223372036854775807)
rel_db_type_class = models.BigIntegerField
| BigIntegerFieldTests |
python | huggingface__transformers | src/transformers/trainer_utils.py | {
"start": 29465,
"end": 29723
} | class ____(ExplicitEnum):
FULL_SHARD = "full_shard"
SHARD_GRAD_OP = "shard_grad_op"
NO_SHARD = "no_shard"
HYBRID_SHARD = "hybrid_shard"
HYBRID_SHARD_ZERO2 = "hybrid_shard_zero2"
OFFLOAD = "offload"
AUTO_WRAP = "auto_wrap"
| FSDPOption |
python | pytorch__pytorch | benchmarks/tensorexpr/reduction.py | {
"start": 2325,
"end": 2587
} | class ____(ReduceBench):
def __init__(self, mode, device, dtype, M, N, K, skip_input_transform):
super().__init__(mode, device, dtype, "row", M, N, K, skip_input_transform)
@staticmethod
def module():
return "reduce_row"
| ReduceRowBench |
python | ray-project__ray | rllib/examples/_old_api_stack/models/parametric_actions_model.py | {
"start": 4315,
"end": 7332
} | class ____(DistributionalQTFModel):
"""Same as the above ParametricActionsModel.
However, this version also learns the action embeddings.
"""
def __init__(
self,
obs_space,
action_space,
num_outputs,
model_config,
name,
true_obs_shape=(4,),
... | ParametricActionsModelThatLearnsEmbeddings |
python | streamlit__streamlit | lib/tests/streamlit/runtime/state/widgets_test.py | {
"start": 2002,
"end": 12236
} | class ____(unittest.TestCase):
def test_get(self):
states = WidgetStates()
_create_widget("trigger", states).trigger_value = True
_create_widget("bool", states).bool_value = True
_create_widget("float", states).double_value = 0.5
_create_widget("int", states).int_value = 123... | WidgetManagerTests |
python | pytorch__pytorch | test/onnx/torchlib/ops_test_data.py | {
"start": 2306,
"end": 24119
} | class ____:
"""A dataclass to store the information to test an torchlib op."""
# The name of the op_info, e.g. "add"
op_info_name: str
# The torchlib ONNX Function to test
op: Callable[..., Any]
# The input wrangler function to adjust the input to fit the aten signature
input_wrangler: Opti... | TorchLibOpInfo |
python | bokeh__bokeh | src/bokeh/events.py | {
"start": 10004,
"end": 10535
} | class ____(ModelEvent):
''' Announce a value being submitted on a text input widget.
'''
event_name = 'value_submit'
value: str
def __init__(self, model: TextInput | None, value: str) -> None:
from .models.widgets import TextInput
if model is not None and not isinstance(model, Tex... | ValueSubmit |
python | huggingface__transformers | src/transformers/models/glm46v/modeling_glm46v.py | {
"start": 2247,
"end": 3199
} | class ____(ModelOutput):
r"""
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-... | Glm46VModelOutputWithPast |
python | django-guardian__django-guardian | guardian/testapp/tests/test_admin.py | {
"start": 1433,
"end": 13146
} | class ____(TestCase):
def setUp(self):
self.admin = User.objects.create_superuser("admin", "admin@example.com", "admin")
self.user = User.objects.create_user("joe", "joe@example.com", "joe")
self.group = Group.objects.create(name="group")
self.client = Client()
self.obj = Con... | AdminTests |
python | scrapy__scrapy | scrapy/spiders/sitemap.py | {
"start": 772,
"end": 5741
} | class ____(Spider):
sitemap_urls: Sequence[str] = ()
sitemap_rules: Sequence[tuple[re.Pattern[str] | str, str | CallbackT]] = [
("", "parse")
]
sitemap_follow: Sequence[re.Pattern[str] | str] = [""]
sitemap_alternate_links: bool = False
_max_size: int
_warn_size: int
@classmetho... | SitemapSpider |
python | huggingface__transformers | src/transformers/models/ernie/modeling_ernie.py | {
"start": 46085,
"end": 46521
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.seq_relationship = nn.Linear(config.hidden_size, 2)
def forward(self, pooled_output):
seq_relationship_score = self.seq_relationship(pooled_output)
return seq_relationship_score
@auto_docstring(
cus... | ErnieOnlyNSPHead |
python | RaRe-Technologies__gensim | gensim/topic_coherence/text_analysis.py | {
"start": 6930,
"end": 8211
} | class ____(BaseAnalyzer):
"""Analyzer that builds up an inverted index to accumulate stats."""
def __init__(self, *args):
"""
Parameters
----------
args : dict
Look at :class:`~gensim.topic_coherence.text_analysis.BaseAnalyzer`
Examples
--------
... | InvertedIndexBased |
python | euske__pdfminer | pdfminer/pdfdocument.py | {
"start": 4174,
"end": 5969
} | class ____(PDFXRef):
def __repr__(self):
return '<PDFXRefFallback: offsets=%r>' % (self.offsets.keys())
PDFOBJ_CUE = re.compile(br'^(\d+)\s+(\d+)\s+obj\b')
def load(self, parser):
parser.seek(0)
while 1:
try:
(pos, line) = parser.nextline()
... | PDFXRefFallback |
python | numba__numba | numba/cuda/simulator/cudadrv/devices.py | {
"start": 324,
"end": 1691
} | class ____:
'''
This stub implements functionality only for simulating a single GPU
at the moment.
'''
def __init__(self, device_id):
self._device_id = device_id
self._device = FakeCUDADevice()
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):... | FakeCUDAContext |
python | PyCQA__pylint | tests/functional/a/access/access_to_protected_members.py | {
"start": 746,
"end": 1138
} | class ____(MyClass):
"""Subclass with protected members."""
def __init__(self):
MyClass._protected = 5
super()._private_method()
INST = Subclass()
INST.attr = 1
print(INST.attr)
INST._protected = 2 # [protected-access]
print(INST._protected) # [protected-access]
INST._cls_protected = 3 # [p... | Subclass |
python | huggingface__transformers | src/transformers/models/roformer/modeling_roformer.py | {
"start": 27581,
"end": 27922
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.predictions = RoFormerLMPredictionHead(config)
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
prediction_scores = self.predictions(sequence_output)
return prediction_scores
@auto_docs... | RoFormerOnlyMLMHead |
python | graphql-python__graphene | graphene/tests/issues/test_313.py | {
"start": 366,
"end": 634
} | class ____(graphene.Mutation):
class Arguments:
text = graphene.String(required=True)
result = graphene.Field(CreatePostResult)
def mutate(self, info, text):
result = Success(yeah="yeah")
return CreatePost(result=result)
| CreatePost |
python | pytorch__pytorch | test/distributed/elastic/rendezvous/dynamic_rendezvous_test.py | {
"start": 62559,
"end": 63401
} | class ____(RendezvousBackend):
def __init__(self) -> None:
self._lock = threading.Lock()
self._state = None
self._token = None
@property
def name(self):
return "_in_memory_backend"
def get_state(self):
with self._lock:
if self._state is None:
... | _InMemoryRendezvousBackend |
python | PrefectHQ__prefect | src/prefect/client/orchestration/_artifacts/client.py | {
"start": 9725,
"end": 11056
} | class ____(BaseAsyncClient):
async def read_latest_artifacts(
self, **kwargs: Unpack["ArtifactCollectionReadParams"]
) -> list["ArtifactCollection"]:
response = await self.request(
"POST",
"/artifacts/latest/filter",
json={
"artifacts": (
... | ArtifactCollectionAsyncClient |
python | PyCQA__bandit | bandit/core/node_visitor.py | {
"start": 299,
"end": 10830
} | class ____:
def __init__(
self, fname, fdata, metaast, testset, debug, nosec_lines, metrics
):
self.debug = debug
self.nosec_lines = nosec_lines
self.scores = {
"SEVERITY": [0] * len(constants.RANKING),
"CONFIDENCE": [0] * len(constants.RANKING),
}... | BanditNodeVisitor |
python | kamyu104__LeetCode-Solutions | Python/maximum-elegance-of-a-k-length-subsequence.py | {
"start": 116,
"end": 1220
} | class ____(object):
def findMaximumElegance(self, items, k):
"""
:type items: List[List[int]]
:type k: int
:rtype: int
"""
curr = 0
lookup = set()
stk = []
for p, c in heapq.nlargest(k, items):
if c in lookup:
stk.ap... | Solution |
python | getsentry__sentry | src/sentry/snuba/utils.py | {
"start": 3214,
"end": 4818
} | class ____:
query_string: str
query_extra: str
query: str
def build_query_strings(
subscription: QuerySubscription | None, snuba_query: SnubaQuery
) -> QueryStrings:
"""
Constructs a QueryStrings dataclass given a QuerySubscription and SnubaQuery.
query_string value is derived from the snu... | QueryStrings |
python | django__django | tests/postgres_tests/models.py | {
"start": 1842,
"end": 2406
} | class ____(PostgreSQLModel):
ips = ArrayField(models.GenericIPAddressField(), default=list)
uuids = ArrayField(models.UUIDField(), default=list)
decimals = ArrayField(
models.DecimalField(max_digits=5, decimal_places=2), default=list
)
tags = ArrayField(TagField(), blank=True, null=True)
... | OtherTypesArrayModel |
python | huggingface__transformers | src/transformers/models/vivit/configuration_vivit.py | {
"start": 782,
"end": 5142
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`VivitModel`]. It is used to instantiate a ViViT
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configura... | VivitConfig |
python | pytorch__pytorch | test/inductor/test_aot_inductor.py | {
"start": 288075,
"end": 288569
} | class ____(TestCase):
device = "cpu"
device_type = "cpu"
check_model = check_model
check_model_with_multiple_inputs = check_model_with_multiple_inputs
code_check_count = code_check_count
allow_stack_allocation = False
use_minimal_arrayref_interface = False
copy_tests(
AOTInductorTestsT... | AOTInductorTestABICompatibleCpu |
python | tensorflow__tensorflow | tensorflow/python/util/object_identity.py | {
"start": 6429,
"end": 6992
} | class ____(ObjectIdentitySet):
"""Like weakref.WeakSet, but compares objects with "is"."""
__slots__ = ()
def _wrap_key(self, key):
return _WeakObjectIdentityWrapper(key)
def __len__(self):
# Iterate, discarding old weak refs
return len([_ for _ in self])
def __iter__(self):
keys = list(se... | ObjectIdentityWeakSet |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/eq_without_hash.py | {
"start": 343,
"end": 435
} | class ____:
if ...:
...
else:
def __eq__(self, other): ...
| MaybeEqElse |
python | keras-team__keras | guides/making_new_layers_and_models_via_subclassing.py | {
"start": 5430,
"end": 6901
} | class ____(keras.layers.Layer):
def __init__(self):
super().__init__()
self.linear_1 = Linear(32)
self.linear_2 = Linear(32)
self.linear_3 = Linear(1)
def call(self, inputs):
x = self.linear_1(inputs)
x = keras.activations.relu(x)
x = self.linear_2(x)
... | MLPBlock |
python | sphinx-doc__sphinx | tests/test_ext_napoleon/test_ext_napoleon_docstring.py | {
"start": 3517,
"end": 33308
} | class ____:
docstrings = [
(
"""Single line summary""",
"""Single line summary""",
),
(
"""
Single line summary
Extended description
""",
"""
Single line summary
Extended description
""",
... | TestGoogleDocstring |
python | django__django | tests/m2m_signals/models.py | {
"start": 31,
"end": 148
} | class ____(models.Model):
name = models.CharField(max_length=20)
class Meta:
ordering = ("name",)
| Part |
python | getsentry__sentry | src/sentry/migrations/0918_sentry_release_arrayfield.py | {
"start": 193,
"end": 1600
} | 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 | Textualize__textual | tests/option_list/test_option_list_movement.py | {
"start": 226,
"end": 4734
} | class ____(App[None]):
"""Test option list application."""
def compose(self) -> ComposeResult:
yield OptionList("1", "2", "3", None, "4", "5", "6")
async def test_initial_highlight() -> None:
"""The highlight should start on the first item."""
async with OptionListApp().run_test() as pilot:
... | OptionListApp |
python | wandb__wandb | wandb/apis/public/registries/registries_search.py | {
"start": 8054,
"end": 11514
} | class ____(RelayPaginator["ArtifactMembershipFragment", "Artifact"]):
"""An lazy iterator of `Artifact` objects in a Registry."""
QUERY: Document # Must be set per-instance
last_response: ArtifactMembershipConnection | None
def __init__(
self,
client: RetryingClient,
organizat... | Versions |
python | doocs__leetcode | solution/1100-1199/1114.Print in Order/Solution.py | {
"start": 0,
"end": 519
} | class ____:
def __init__(self):
self.l2 = threading.Lock()
self.l3 = threading.Lock()
self.l2.acquire()
self.l3.acquire()
def first(self, printFirst: 'Callable[[], None]') -> None:
printFirst()
self.l2.release()
def second(self, printSecond: 'Callable[[], No... | Foo |
python | mlflow__mlflow | mlflow/tensorflow/autologging.py | {
"start": 193,
"end": 6716
} | class ____(TensorBoard, metaclass=ExceptionSafeClass):
pass
def _extract_input_example_from_tensor_or_ndarray(
input_features: tensorflow.Tensor | np.ndarray,
) -> np.ndarray:
"""
Extracts first `INPUT_EXAMPLE_SAMPLE_ROWS` from the next_input, which can either be of
numpy array or tensor type.
... | _TensorBoard |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-hubspot/unit_tests/integrations/test_leads.py | {
"start": 344,
"end": 5390
} | class ____(HubspotCRMSearchStream):
SCOPES = ["crm.objects.leads.read"]
CURSOR_FIELD = "updatedAt"
STREAM_NAME = "leads"
OBJECT_TYPE = "leads"
ASSOCIATIONS = ["companies", "contacts"]
OBJECT_ID = "12345"
@HttpMocker()
def test_given_records_when_read_extract_desired_records(self, http_m... | TestLeadsStream |
python | protocolbuffers__protobuf | python/google/protobuf/internal/type_checkers.py | {
"start": 7502,
"end": 8724
} | class ____(object):
"""Checker used for string fields.
Always returns a unicode value, even if the input is of type str.
"""
def CheckValue(self, proposed_value):
if not isinstance(proposed_value, (bytes, str)):
message = ('%.1024r has type %s, but expected one of: %s' %
(proposed_... | UnicodeValueChecker |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1565867,
"end": 1567405
} | class ____(
MarkPropDefnumberArray, NumericArrayMarkPropDef
):
"""
ValueDefWithConditionMarkPropFieldOrDatumDefnumberArray schema wrapper.
Parameters
----------
condition : dict, :class:`ConditionalMarkPropFieldOrDatumDef`, :class:`ConditionalValueDefnumberArrayExprRef`, :class:`ConditionalPara... | ValueDefWithConditionMarkPropFieldOrDatumDefnumberArray |
python | pypa__pip | src/pip/_vendor/distlib/util.py | {
"start": 52967,
"end": 54173
} | class ____(xmlrpclib.ServerProxy):
def __init__(self, uri, **kwargs):
self.timeout = timeout = kwargs.pop('timeout', None)
# The above classes only come into play if a timeout
# is specified
if timeout is not None:
# scheme = splittype(uri) # deprecated as of Python 3.8... | ServerProxy |
python | jazzband__django-model-utils | tests/models.py | {
"start": 10991,
"end": 11142
} | class ____(SoftDeletableQuerySet[ModelT]):
def only_read(self) -> QuerySet[ModelT]:
return self.filter(is_read=True)
| CustomSoftDeleteQuerySet |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pep8_naming/N804.py | {
"start": 1163,
"end": 1348
} | class ____(ABCMeta):
def bad_method(this):
this = this
this
def bad_method(this):
self = this
def func(x):
return x
foo = {}
| RenamingInMethodBodyClass |
python | doocs__leetcode | solution/0800-0899/0872.Leaf-Similar Trees/Solution.py | {
"start": 192,
"end": 689
} | class ____:
def leafSimilar(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> bool:
def dfs(root: Optional[TreeNode], nums: List[int]) -> None:
if root.left == root.right:
nums.append(root.val)
return
if root.left:
dfs(root... | Solution |
python | PyCQA__pylint | tests/functional/ext/no_self_use/no_self_use.py | {
"start": 205,
"end": 908
} | class ____:
"""Something inconsequential for the test."""
def __init__(self):
self.aaa = 2
def regular_method(self):
"""this method is a real method since it access to self"""
self.function_method()
def function_method(self): # [no-self-use]
"""this method isn' a real... | Toto |
python | Pylons__pyramid | tests/pkgs/eventonly/__init__.py | {
"start": 587,
"end": 667
} | class ____:
def __init__(self, response):
self.response = response
| Foo |
python | simonw__sqlite-utils | sqlite_utils/utils.py | {
"start": 5667,
"end": 5724
} | class ____(RowsFromFileError):
pass
| RowsFromFileBadJSON |
python | allegroai__clearml | clearml/binding/gradio_bind.py | {
"start": 269,
"end": 4543
} | class ____:
_current_task = None
__patched = False
_default_gradio_address = "0.0.0.0"
_default_gradio_port = 7860
_root_path_format = "/service/{}/"
__server_config_warning = set()
@classmethod
def update_current_task(cls, task: Optional[Any] = None) -> None:
cls._current_task... | PatchGradio |
python | apache__airflow | airflow-core/src/airflow/models/callback.py | {
"start": 6873,
"end": 8606
} | class ____(Callback):
"""Callbacks that run on the Triggerer (must be async)."""
__mapper_args__ = {"polymorphic_identity": CallbackType.TRIGGERER}
def __init__(self, callback_def: ImportPathCallbackDefProtocol, **kwargs):
"""
Initialize a TriggererCallback from a callback definition.
... | TriggererCallback |
python | celery__celery | t/unit/contrib/test_worker.py | {
"start": 289,
"end": 1972
} | class ____:
def setup_method(self):
self.app = Celery('celerytest', backend='cache+memory://', broker='memory://', )
@self.app.task
def add(x, y):
return x + y
self.add = add
@self.app.task
def error_task():
raise NotImplementedError()
... | test_worker |
python | huggingface__transformers | src/transformers/models/olmo/modeling_olmo.py | {
"start": 13271,
"end": 15000
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: OlmoConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = OlmoAttention(config=config, layer_idx=layer_idx)
self.mlp = OlmoMLP(config)
self.input_layernorm = OlmoL... | OlmoDecoderLayer |
python | realpython__materials | hashtable/01_hashtable_prototype/09_report_the_hash_tables_length/hashtable.py | {
"start": 107,
"end": 1447
} | class ____:
def __init__(self, capacity):
if capacity < 1:
raise ValueError("Capacity must be a positive number")
self._slots = capacity * [None]
def __len__(self):
return len(self.pairs)
def __delitem__(self, key):
if key in self:
self._slots[self._... | HashTable |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1234639,
"end": 1235767
} | class ____(sgqlc.types.Type, Node, UniformResourceLocatable):
"""Represents a 'merged' event on a given pull request."""
__schema__ = github_schema
__field_names__ = ("actor", "commit", "created_at", "merge_ref", "merge_ref_name", "pull_request")
actor = sgqlc.types.Field(Actor, graphql_name="actor")
... | MergedEvent |
python | astropy__astropy | astropy/utils/metadata/merge.py | {
"start": 459,
"end": 3633
} | class ____:
"""
Base class for defining a strategy for merging metadata from two
sources, left and right, into a single output.
The primary functionality for the class is the ``merge(cls, left, right)``
class method. This takes ``left`` and ``right`` side arguments and
returns a single merged ... | MergeStrategy |
python | huggingface__transformers | src/transformers/utils/deprecation.py | {
"start": 934,
"end": 8031
} | class ____(ExplicitEnum):
NONE = "none"
NOTIFY = "notify"
NOTIFY_ALWAYS = "notify_always"
RAISE = "raise"
def deprecate_kwarg(
old_name: str,
version: str,
new_name: str | None = None,
warn_if_greater_or_equal_version: bool = False,
raise_if_greater_or_equal_version: bool = False,
... | Action |
python | google__pytype | pytype/rewrite/convert_test.py | {
"start": 137,
"end": 304
} | class ____(test_utils.PytdTestBase, test_utils.ContextfulTestBase):
def setUp(self):
super().setUp()
self.conv = self.ctx.abstract_converter
| ConverterTestBase |
python | huggingface__transformers | tests/pipelines/test_pipelines_zero_shot.py | {
"start": 1145,
"end": 12626
} | class ____(unittest.TestCase):
model_mapping = MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
if not hasattr(model_mapping, "is_dummy"):
model_mapping = {config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
def get_test_pipeline(
self,
model,
... | ZeroShotClassificationPipelineTests |
python | pyqtgraph__pyqtgraph | pyqtgraph/dockarea/DockArea.py | {
"start": 14234,
"end": 15329
} | class ____(QtWidgets.QWidget):
def __init__(self, area, **kwargs):
QtWidgets.QWidget.__init__(self, **kwargs)
self.layout = QtWidgets.QGridLayout()
self.setLayout(self.layout)
self.layout.setContentsMargins(0, 0, 0, 0)
self.dockarea = area
self.layout.addWidget(area)
... | TempAreaWindow |
python | tiangolo__fastapi | tests/test_jsonable_encoder.py | {
"start": 669,
"end": 712
} | class ____:
name: str
count: int
| Item |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/decorator_location.py | {
"start": 1196,
"end": 2520
} | class ____:
def __call__(self, f: Callable[[int], None]) -> Callable[[int], None]:
return f
@with_logging
@with_logging2
def decorated_logging_logging2(x: int) -> None:
_test_sink(x)
@skip_this_decorator
def decorated_skip_this_decorator(x: int) -> None:
_test_sink(x)
@with_logging2
@skip_this... | ignore_this_decorator_class |
python | kamyu104__LeetCode-Solutions | Python/sender-with-largest-word-count.py | {
"start": 84,
"end": 473
} | class ____(object):
def largestWordCount(self, messages, senders):
"""
:type messages: List[str]
:type senders: List[str]
:rtype: str
"""
cnt = collections.Counter()
for m, s in itertools.izip(messages, senders):
cnt[s] += m.count(' ')+1
re... | Solution |
python | tensorflow__tensorflow | tensorflow/python/ops/ragged/ragged_boolean_mask_op_test.py | {
"start": 1223,
"end": 13079
} | class ____(test_util.TensorFlowTestCase,
parameterized.TestCase):
# Define short constants for true & false, so the data & mask can be lined
# up in the examples below. This makes it easier to read the examples, to
# see which values should be kept vs. masked.
T = True
F = False... | RaggedBooleanMaskOpTest |
python | graphql-python__graphene | examples/simple_example.py | {
"start": 18,
"end": 132
} | class ____(graphene.ObjectType):
id = graphene.ID()
name = graphene.String()
age = graphene.Int()
| Patron |
python | pypa__installer | tests/test_utils.py | {
"start": 4061,
"end": 5376
} | class ____:
@pytest.mark.parametrize(
("data", "expected"),
[
pytest.param(
b"#!python\ntest",
b"#!/my/python\ntest",
id="python",
),
pytest.param(
b"#!pythonw\ntest",
b"#!/my/python\n... | TestScript |
python | gevent__gevent | src/gevent/tests/test__server.py | {
"start": 10605,
"end": 15880
} | class ____(TestCase):
def get_spawn(self):
return gevent.spawn
def _test_server_start_stop(self, restartable):
self.report_netstat('before start')
self.start_server()
self.report_netstat('after start')
if restartable and self.Settings.restartable:
self.serve... | TestDefaultSpawn |
python | walkccc__LeetCode | solutions/743. Network Delay Time/743.py | {
"start": 0,
"end": 708
} | class ____:
def networkDelayTime(self, times: list[list[int]], n: int, k: int) -> int:
graph = [[] for _ in range(n)]
for u, v, w in times:
graph[u - 1].append((v - 1, w))
return self._dijkstra(graph, k - 1)
def _dijkstra(self, graph: list[list[tuple[int, int]]], src: int) -> int:
dist = [m... | Solution |
python | getsentry__sentry | src/sentry/integrations/github/integration.py | {
"start": 7534,
"end": 9203
} | class ____(TypedDict):
installation_id: str
github_account: str
avatar_url: str
def build_repository_query(metadata: Mapping[str, Any], name: str, query: str) -> bytes:
"""
Builds a query for the GitHub Search API. Always includes both forks and original repositories.
Test out your query updat... | GithubInstallationInfo |
python | MongoEngine__mongoengine | tests/fields/test_boolean_field.py | {
"start": 99,
"end": 1719
} | class ____(MongoDBTestCase):
def test_storage(self):
class Person(Document):
admin = BooleanField()
person = Person(admin=True)
person.save()
assert get_as_pymongo(person) == {"_id": person.id, "admin": True}
def test_construction_does_not_fail_uncastable_value(self... | TestBooleanField |
python | PrefectHQ__prefect | src/integrations/prefect-databricks/prefect_databricks/models/jobs.py | {
"start": 57558,
"end": 57844
} | class ____(BaseModel):
"""
See source code for the fields' description.
"""
model_config = ConfigDict(extra="allow", frozen=True)
lookup_key: Optional[str] = Field(
None, description="A key that can be used to look up query details."
)
| SqlStatementOutput |
python | doocs__leetcode | solution/1500-1599/1550.Three Consecutive Odds/Solution.py | {
"start": 0,
"end": 285
} | class ____:
def threeConsecutiveOdds(self, arr: List[int]) -> bool:
cnt = 0
for x in arr:
if x & 1:
cnt += 1
if cnt == 3:
return True
else:
cnt = 0
return False
| Solution |
python | pytorch__pytorch | test/mobile/test_bytecode.py | {
"start": 4149,
"end": 14640
} | class ____(TestCase):
def test_get_model_bytecode_version(self):
def check_model_version(model_path, expect_version):
actual_version = _get_model_bytecode_version(model_path)
assert actual_version == expect_version
for version, model_info in SCRIPT_MODULE_BYTECODE_PKL.items(... | testVariousModelVersions |
python | doocs__leetcode | solution/2300-2399/2392.Build a Matrix With Conditions/Solution.py | {
"start": 0,
"end": 1091
} | class ____:
def buildMatrix(
self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]
) -> List[List[int]]:
def f(cond):
g = defaultdict(list)
indeg = [0] * (k + 1)
for a, b in cond:
g[a].append(b)
indeg[b] +... | Solution |
python | django-import-export__django-import-export | import_export/admin.py | {
"start": 32473,
"end": 32619
} | class ____(ImportExportMixin, admin.ModelAdmin):
"""
Subclass of ModelAdmin with import/export functionality.
"""
| ImportExportModelAdmin |
python | pytorch__pytorch | test/jit/fixtures_srcs/fixtures_src.py | {
"start": 1202,
"end": 1310
} | class ____(torch.nn.Module):
def forward(self, x):
return torch._C._nn.gelu(x)
| TestVersionedGeluV9 |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/asset_selections.py | {
"start": 778,
"end": 3675
} | class ____(graphene.ObjectType):
assetSelectionString = graphene.String()
assetKeys = non_null_list(GrapheneAssetKey)
assetChecks = non_null_list(GrapheneAssetCheckHandle)
assets = non_null_list("dagster_graphql.schema.pipelines.pipeline.GrapheneAsset")
assetsOrError = graphene.NonNull("dagster_grap... | GrapheneAssetSelection |
python | Netflix__metaflow | metaflow/_vendor/packaging/_manylinux.py | {
"start": 2024,
"end": 8813
} | class ____(NamedTuple):
major: int
minor: int
def _glibc_version_string_confstr() -> Optional[str]:
"""
Primary implementation of glibc_version_string using os.confstr.
"""
# os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
# to be broken or missing. This strategy is... | _GLibCVersion |
python | sympy__sympy | sympy/functions/elementary/trigonometric.py | {
"start": 93459,
"end": 100804
} | class ____(InverseTrigonometricFunction):
r"""
The inverse cotangent function.
Returns the arc cotangent of x (measured in radians).
Explanation
===========
``acot(x)`` will evaluate automatically in the cases
$x \in \{\infty, -\infty, \tilde{\infty}, 0, 1, -1\}$
and for some instance... | acot |
python | pytorch__pytorch | torch/_inductor/comm_analysis.py | {
"start": 3390,
"end": 3444
} | class ____(IntEnum):
TREE = 0
RING = 1
| NCCL_ALGO |
python | scrapy__scrapy | scrapy/extensions/httpcache.py | {
"start": 12093,
"end": 16577
} | class ____:
def __init__(self, settings: BaseSettings):
self.cachedir: str = data_path(settings["HTTPCACHE_DIR"])
self.expiration_secs: int = settings.getint("HTTPCACHE_EXPIRATION_SECS")
self.use_gzip: bool = settings.getbool("HTTPCACHE_GZIP")
# https://github.com/python/mypy/issues/... | FilesystemCacheStorage |
python | realpython__materials | python-313/typing/deprecations.py | {
"start": 1706,
"end": 2036
} | class ____:
def __init__(self, major: int, minor: int = 0, patch: int = 0) -> None:
self.major = major
self.minor = minor
self.patch = patch
concatenate("three", "thirteen")
add(3, 13)
VersionType(3, 13)
version = Version(3, 13)
version.increase("patch")
print(version)
print(version.bugfi... | VersionType |
python | realpython__materials | django-diary/source_code_final/entries/views.py | {
"start": 1094,
"end": 1439
} | class ____(LockedView, SuccessMessageMixin, DeleteView):
model = Entry
success_url = reverse_lazy("entry-list")
success_message = "Your entry was deleted!"
def delete(self, request, *args, **kwargs):
messages.success(self.request, self.success_message)
return super().delete(request, *ar... | EntryDeleteView |
python | pandas-dev__pandas | pandas/tests/indexing/test_iloc.py | {
"start": 49022,
"end": 51669
} | class ____:
def test_frame_iloc_getitem_callable(self):
# GH#11485
df = DataFrame({"X": [1, 2, 3, 4], "Y": list("aabb")}, index=list("ABCD"))
# return location
res = df.iloc[lambda x: [1, 3]]
tm.assert_frame_equal(res, df.iloc[[1, 3]])
res = df.iloc[lambda x: [1, 3]... | TestILocCallable |
python | kamyu104__LeetCode-Solutions | Python/powerful-integers.py | {
"start": 95,
"end": 759
} | class ____(object):
def powerfulIntegers(self, x, y, bound):
"""
:type x: int
:type y: int
:type bound: int
:rtype: List[int]
"""
result = set()
log_x = int(math.floor(math.log(bound) / math.log(x)))+1 if x != 1 else 1
log_y = int(math.floor(ma... | Solution |
python | pytorch__pytorch | test/dynamo/test_model_output.py | {
"start": 1871,
"end": 8767
} | class ____(torch._dynamo.test_case.TestCase):
@maybe_skip
def test_mo_create(self):
def fn(a, b):
tmp = BaseModelOutput(a + 1, attentions=b + 3)
return tmp
torch._dynamo.testing.standard_test(self, fn=fn, nargs=2, expected_ops=2)
@maybe_skip
def test_mo_assign(s... | TestModelOutput |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.