language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | django__django | tests/template_tests/filter_tests/test_title.py | {
"start": 117,
"end": 573
} | class ____(SimpleTestCase):
@setup({"title1": "{{ a|title }}"})
def test_title1(self):
output = self.engine.render_to_string("title1", {"a": "JOE'S CRAB SHACK"})
self.assertEqual(output, "Joe's Crab Shack")
@setup({"title2": "{{ a|title }}"})
def test_title2(self):
output =... | TitleTests |
python | huggingface__transformers | src/transformers/models/qwen2_5_omni/modeling_qwen2_5_omni.py | {
"start": 69017,
"end": 72948
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: Qwen2_5OmniTextConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
if config.use_sliding_window and config._attn_implementation != "flash_attention_2":
logger.warning_once(
... | Qwen2_5OmniDecoderLayer |
python | weaviate__weaviate-python-client | weaviate/cluster/async_.py | {
"start": 218,
"end": 420
} | class ____(_ClusterExecutor[ConnectionAsync]):
def __init__(self, connection: ConnectionAsync):
super().__init__(connection)
self.replications = _ReplicateAsync(connection)
| _ClusterAsync |
python | Netflix__metaflow | metaflow/plugins/cards/card_modules/test_cards.py | {
"start": 1019,
"end": 1349
} | class ____(MetaflowCard):
type = "test_editable_card_2"
separator = "$&#!!@*"
ALLOW_USER_COMPONENTS = True
def __init__(self, components=[], **kwargs):
self._components = components
def render(self, task):
return self.separator.join([str(comp) for comp in self._components])
| TestEditableCard2 |
python | aimacode__aima-python | planning.py | {
"start": 21509,
"end": 23120
} | class ____(search.Problem):
"""
[Section 10.2.1]
Forward state-space search
"""
def __init__(self, planning_problem):
super().__init__(associate('&', planning_problem.initial), associate('&', planning_problem.goals))
self.planning_problem = planning_problem
self.expanded_act... | ForwardPlan |
python | spack__spack | lib/spack/spack/cmd/style.py | {
"start": 2102,
"end": 17117
} | class ____:
def __init__(self, name: str, required: bool = False, external: bool = True) -> None:
self.name = name
self.external = external
self.required = required
def __call__(self, fun):
self.fun = fun
tools[self.name] = self
return fun
@property
def ... | tool |
python | google__pytype | pytype/rewrite/frame_test.py | {
"start": 5477,
"end": 16079
} | class ____(FrameTestBase):
def test_run_no_crash(self):
block = [
opcodes.LOAD_CONST(0, 0, 0, 0, 0, 0, None),
opcodes.RETURN_VALUE(1, 0),
]
code = test_utils.FakeOrderedCode([block], [None])
frame = frame_lib.Frame(self.ctx, 'test', code.Seal())
frame.run()
def test_typing(self... | FrameTest |
python | PyCQA__pylint | doc/data/messages/t/too-many-locals/good.py | {
"start": 68,
"end": 1464
} | class ____(NamedTuple):
number_of_sweets: int
number_of_sweet_per_child: int
number_of_children: int
@property
def sweets_given(self):
return self.number_of_sweet_per_child * self.number_of_children
def handle_sweets(infos):
children = [Child(info) for info in infos]
characteristi... | SweetDistrubutionCharacteristics |
python | astropy__astropy | astropy/utils/masked/tests/test_function_helpers.py | {
"start": 51060,
"end": 54734
} | class ____:
def setup_class(self):
self.a = np.array(
[
[np.nan, np.nan, 3.0],
[4.0, 5.0, 6.0],
]
)
self.mask_a = np.array(
[
[True, False, False],
[False, True, False],
]
... | TestNaNFunctions |
python | apache__thrift | test/py/SerializationTest.py | {
"start": 15239,
"end": 17481
} | class ____(unittest.TestCase):
def testSerializeThenDeserialize(self):
obj = Xtruct2(i32_thing=1,
struct_thing=Xtruct(string_thing="foo"))
s1 = serialize(obj)
for i in range(10):
self.assertEqual(s1, serialize(obj))
objcopy = Xtruct2()
... | SerializersTest |
python | pytorch__pytorch | test/test_mps.py | {
"start": 371983,
"end": 380014
} | class ____(TestCaseMPS):
def test_nll_loss_mismatched_batch(self, device='mps'):
x = torch.randn((10, 3), requires_grad=True, device=device)
# t should have size (10,)
t = torch.zeros((3,), dtype=torch.int64, device=device)
with self.assertRaisesRegex(ValueError, 'Expected.*batch_siz... | TestNLLLoss |
python | allegroai__clearml | clearml/backend_api/services/v2_9/events.py | {
"start": 97919,
"end": 99006
} | class ____(Response):
"""
Response of events.scalar_metrics_iter_histogram endpoint.
:param images:
:type images: Sequence[dict]
"""
_service = "events"
_action = "scalar_metrics_iter_histogram"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {"images"... | ScalarMetricsIterHistogramResponse |
python | eventlet__eventlet | tests/debug_test.py | {
"start": 90,
"end": 2860
} | class ____(tests.LimitedTestCase):
def setUp(self):
self.orig_trace = sys.settrace
sys.settrace = self._settrace
self.tracer = None
def tearDown(self):
sys.settrace = self.orig_trace
sys.stdout = sys.__stdout__
def _settrace(self, cb):
self.tracer = cb
... | TestSpew |
python | ray-project__ray | python/ray/llm/_internal/serve/engines/vllm/vllm_models.py | {
"start": 2080,
"end": 12325
} | class ____(BaseModelExtended):
model_config = ConfigDict(
use_enum_values=True,
)
model_id: str = Field(
description="The identifier for the model. This is the id that will be used to query the model.",
)
hf_model_id: Optional[str] = Field(
None, description="The Hugging Fac... | VLLMEngineConfig |
python | getsentry__sentry | src/sentry/data_export/processors/issues_by_tag.py | {
"start": 327,
"end": 431
} | class ____(NamedTuple):
value: GroupTagValue
eventuser: EventUser | None
| GroupTagValueAndEventUser |
python | kubernetes-client__python | kubernetes/client/api/scheduling_v1_api.py | {
"start": 543,
"end": 95824
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
... | SchedulingV1Api |
python | pytorch__pytorch | torch/cuda/memory.py | {
"start": 1658,
"end": 48588
} | class ____(TypedDict):
"""Memory snapshot structure."""
segments: list[_Segment]
device_traces: NotRequired[list[list[_TraceEntry]]]
__all__ = [
"caching_allocator_alloc",
"caching_allocator_delete",
"caching_allocator_enable",
"get_per_process_memory_fraction",
"set_per_process_memor... | _Snapshot |
python | scipy__scipy | scipy/optimize/_optimize.py | {
"start": 140160,
"end": 149745
} | class ____:
"""
Object to wrap user cost function for optimize.brute, allowing picklability
"""
def __init__(self, f, args):
self.f = f
self.args = [] if args is None else args
def __call__(self, x):
# flatten needed for one dimensional case.
return self.f(np.asarra... | _Brute_Wrapper |
python | pydata__xarray | xarray/tests/test_plot.py | {
"start": 99643,
"end": 102518
} | class ____(PlotTestCase):
@pytest.fixture(autouse=True)
def setUp(self) -> None:
das = [
DataArray(
np.random.randn(3, 3, 4, 4),
dims=["x", "y", "row", "col"],
coords=[range(k) for k in [3, 3, 4, 4]],
)
for _ in [1, 2]
... | TestDatasetQuiverPlots |
python | coleifer__peewee | tests/pool.py | {
"start": 941,
"end": 1394
} | class ____(SqliteDatabase):
def __init__(self, *args, **kwargs):
self.counter = self.closed_counter = kwargs.pop('counter', 0)
self.transaction_history = []
super(FakeDatabase, self).__init__(*args, **kwargs)
def _connect(self):
self.counter += 1
return self.counter
... | FakeDatabase |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classVar3.py | {
"start": 398,
"end": 1582
} | class ____(Generic[T]):
x: ClassVar[int] = 3
# This should generate an error.
y: Final[ClassVar[int]] = 3
# This should generate an error.
z: list[ClassVar[int]] = []
# This should generate an error because TypeVars cannot
# be used in a ClassVar.
illegal1: ClassVar[list[T]]
# Th... | Foo |
python | doocs__leetcode | solution/2900-2999/2926.Maximum Balanced Subsequence Sum/Solution.py | {
"start": 0,
"end": 394
} | class ____:
def __init__(self, n: int):
self.n = n
self.c = [-inf] * (n + 1)
def update(self, x: int, v: int):
while x <= self.n:
self.c[x] = max(self.c[x], v)
x += x & -x
def query(self, x: int) -> int:
mx = -inf
while x:
mx = ma... | BinaryIndexedTree |
python | huggingface__transformers | src/transformers/models/olmoe/modular_olmoe.py | {
"start": 10069,
"end": 11686
} | class ____(MixtralForCausalLM, GenerationMixin):
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
def __init__(self, config):
super().__init__(config)
self.model = OlmoeModel(config)
self.num_experts = config.num_experts
def forward(self, **super_kwargs):
... | OlmoeForCausalLM |
python | readthedocs__readthedocs.org | readthedocs/doc_builder/environments.py | {
"start": 17163,
"end": 22839
} | class ____:
"""
Base build environment.
Base class for wrapping command execution for build steps. This class is in
charge of raising ``BuildAppError`` for internal application errors that
should be communicated to the user as a general unknown error and
``BuildUserError`` that will be exposed ... | BaseBuildEnvironment |
python | numba__numba | numba/cuda/cudadecl.py | {
"start": 8616,
"end": 15292
} | class ____(AbstractTemplate):
def generic(self, args, kws):
assert not kws
[arg] = args
if arg == types.float16:
return signature(arg, arg)
def _genfp16_binary_comparison(l_key):
@register
class Cuda_fp16_cmp(ConcreteTemplate):
key = l_key
cases = [
... | Float |
python | huggingface__transformers | src/transformers/models/granite_speech/processing_granite_speech.py | {
"start": 1024,
"end": 3732
} | class ____(ProcessorMixin):
def __init__(
self,
audio_processor,
tokenizer,
audio_token="<|audio|>",
chat_template=None,
):
self.audio_token = tokenizer.audio_token if hasattr(tokenizer, "audio_token") else audio_token
super().__init__(audio_processor, tok... | GraniteSpeechProcessor |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/variables.py | {
"start": 1153,
"end": 1861
} | class ____(BaseModel):
"""Variable serializer for responses."""
key: str
val: str = Field(alias="value")
description: str | None
is_encrypted: bool
team_id: UUID | None
@model_validator(mode="after")
def redact_val(self) -> Self:
if self.val is None:
return self
... | VariableResponse |
python | Textualize__textual | src/textual/widgets/_tree.py | {
"start": 1671,
"end": 1795
} | class ____(Exception):
"""Exception raised when there is an error with a request to add a node."""
@dataclass
| AddNodeError |
python | pyca__cryptography | tests/x509/verification/test_verification.py | {
"start": 946,
"end": 3914
} | class ____:
def test_time_already_set(self):
with pytest.raises(ValueError):
PolicyBuilder().time(datetime.datetime.now()).time(
datetime.datetime.now()
)
def test_store_already_set(self):
with pytest.raises(ValueError):
PolicyBuilder().store(... | TestPolicyBuilder |
python | huggingface__transformers | src/transformers/models/mlcd/modeling_mlcd.py | {
"start": 13189,
"end": 15160
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: MLCDVisionConfig):
super().__init__()
self.embed_dim = config.hidden_size
self.self_attn = MLCDAttention(config)
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
self.mlp = MLCDMLP(co... | MLCDEncoderLayer |
python | pypa__pip | src/pip/_vendor/rich/jupyter.py | {
"start": 514,
"end": 1094
} | class ____:
"""A shim to write html to Jupyter notebook."""
def __init__(self, html: str, text: str) -> None:
self.html = html
self.text = text
def _repr_mimebundle_(
self, include: Sequence[str], exclude: Sequence[str], **kwargs: Any
) -> Dict[str, str]:
data = {"text/... | JupyterRenderable |
python | huggingface__transformers | src/transformers/models/modernbert/configuration_modernbert.py | {
"start": 1362,
"end": 13682
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`ModernBertModel`]. It is used to instantiate an ModernBert
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a simila... | ModernBertConfig |
python | django__django | tests/admin_inlines/admin.py | {
"start": 1290,
"end": 1411
} | class ____(admin.TabularInline):
model = NonAutoPKBookChild
classes = ("collapse",)
| NonAutoPKBookChildTabularInline |
python | ipython__ipython | IPython/core/ultratb.py | {
"start": 16211,
"end": 37808
} | class ____(TBTools):
"""A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
of HTML. Requires inspect and pydoc. Crazy, man.
Modified version which optionally strips the topmost entries from the
traceback, to be used with alternate interpreters (because their own code
would ap... | VerboseTB |
python | numba__numba | numba/tests/test_ufuncs.py | {
"start": 69898,
"end": 71073
} | class ____(TestCase):
def test_cpu_get_ufunc_info(self):
# The CPU context defines get_ufunc_info that is the same as
# ufunc_db.get_ufunc_info.
targetctx = cpu_target.target_context
# Check: get_ufunc_info returns a dict
add_info = targetctx.get_ufunc_info(np.add)
se... | TestUfuncOnContext |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/operators/appflow.py | {
"start": 11167,
"end": 13551
} | class ____(AppflowBaseOperator):
"""
Execute an AppFlow run after updating the filters to select only future data.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:AppflowRunAfterOperator`
:param source: The source name (Supp... | AppflowRunAfterOperator |
python | pytorch__pytorch | test/functorch/test_ac_logging.py | {
"start": 438,
"end": 6506
} | class ____(TestCase):
def setUp(self) -> None:
super().setUp()
self.graph: MagicMock = MagicMock(spec=Graph)
self.node1: MagicMock = MagicMock(spec=Node)
self.node2: MagicMock = MagicMock(spec=Node)
self.node1.name = "node1"
self.node1.target = "target1"
self... | TestAcLogging |
python | huggingface__transformers | src/transformers/models/kyutai_speech_to_text/modeling_kyutai_speech_to_text.py | {
"start": 23488,
"end": 29839
} | class ____(KyutaiSpeechToTextAttention):
"""
KyutaiSpeechToText flash attention module. This module inherits from `KyutaiSpeechToTextAttention` as the weights of the module stays
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
flash att... | KyutaiSpeechToTextFlashAttention2 |
python | wandb__wandb | wandb/vendor/pygments/lexers/robotframework.py | {
"start": 10131,
"end": 10198
} | class ____(Tokenizer):
_tokens = (ARGUMENT,)
| TemplatedKeywordCall |
python | huggingface__transformers | src/transformers/models/chameleon/modeling_chameleon.py | {
"start": 26544,
"end": 28247
} | class ____(nn.Module):
def __init__(self, in_channels):
super().__init__()
self.in_channels = in_channels
self.norm = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, paddin... | ChameleonVQVAEEncoderAttnBlock |
python | python-attrs__attrs | tests/test_cmp.py | {
"start": 1304,
"end": 8878
} | class ____:
"""
Tests for eq and order related methods.
"""
#########
# eq
#########
@pytest.mark.parametrize(
("cls", "requires_same_type"), cmp_data, ids=cmp_ids
)
def test_equal_same_type(self, cls, requires_same_type):
"""
Equal objects are detected as eq... | TestEqOrder |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/fmt_skip/type_params.py | {
"start": 226,
"end": 616
} | class ____[
T
] ( # trailing arguments open parenthesis comment
# leading argument comment
A # trailing argument comment
# trailing argument own line comment
): # fmt: skip
pass
def test [
# comment
A,
# another
B,
] (): # fmt: skip
...
def test [
# comment
A,
... | TestTrailingComment4 |
python | ray-project__ray | python/ray/_private/state_api_test_utils.py | {
"start": 953,
"end": 1079
} | class ____:
api: Callable
verify_cb: Callable
kwargs: Dict = field(default_factory=dict)
@dataclass
| StateAPICallSpec |
python | google__flatbuffers | tests/service_test_grpc.fb.py | {
"start": 1364,
"end": 3331
} | class ____(object):
"""Interface exported by the server."""
def Hello(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def StreamClient(self, request_iterator, context):
co... | HelloServiceServicer |
python | huggingface__transformers | src/transformers/models/parakeet/processing_parakeet.py | {
"start": 1321,
"end": 3175
} | class ____(ProcessorMixin):
def __init__(self, feature_extractor, tokenizer):
super().__init__(feature_extractor, tokenizer)
def __call__(
self,
audio: AudioInput,
text: Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput], None] = None,
sampling_... | ParakeetProcessor |
python | kamyu104__LeetCode-Solutions | Python/closest-prime-numbers-in-range.py | {
"start": 232,
"end": 1843
} | class ____(object):
def __init__(self, N, build_fn, query_fn):
self.tree = [None]*(2*2**((N-1).bit_length()))
self.base = len(self.tree)//2
self.query_fn = query_fn
for i in xrange(self.base, self.base+N):
self.tree[i] = build_fn(i-self.base)
for i in reversed(xra... | SegmentTree |
python | doocs__leetcode | lcof2/剑指 Offer II 024. 反转链表/Solution.py | {
"start": 136,
"end": 357
} | class ____:
def reverseList(self, head: ListNode) -> ListNode:
pre, p = None, head
while p:
q = p.next
p.next = pre
pre = p
p = q
return pre
| Solution |
python | getsentry__sentry | src/sentry/pipeline/types.py | {
"start": 236,
"end": 472
} | class ____[M: Model, S: PipelineSessionStore]:
"""Initial pipeline attributes from a request."""
state: S
provider_model: M | None
organization: RpcOrganization | None
provider_key: str
@dataclass
| PipelineRequestState |
python | pytorch__pytorch | torch/optim/optimizer.py | {
"start": 1526,
"end": 13661
} | class ____:
"""Singleton class representing a required parameter for an Optimizer."""
def __repr__(self) -> str:
return "<required parameter>"
required = _RequiredParameter()
def _use_grad_for_differentiable(func: Callable[_P, _T]) -> Callable[_P, _T]:
def _use_grad(*args: _P.args, **kwargs: _P... | _RequiredParameter |
python | facelessuser__pymdown-extensions | tests/test_extensions/test_superfences.py | {
"start": 50068,
"end": 54280
} | class ____(util.MdCase):
"""Test relaxed header cases."""
extension = ['pymdownx.highlight', 'pymdownx.superfences', 'attr_list']
extension_configs = {
'pymdownx.superfences': {
'relaxed_headers': True,
'custom_fences': [
{
'name': 'test',... | TestHighlightRelaxedHeaders |
python | getsentry__sentry | src/sentry/sentry_metrics/querying/data/mapping/base.py | {
"start": 116,
"end": 660
} | class ____(abc.ABC):
from_key: str = ""
to_key: str = ""
applied_on_groupby: bool = False
def __init__(self):
# This exists to satisfy mypy, which complains otherwise
self.map: dict[Any, Any] = {}
def __hash__(self):
return hash((self.from_key, self.to_key))
@abc.abstr... | Mapper |
python | django__django | tests/delete_regress/models.py | {
"start": 3793,
"end": 4054
} | class ____(models.Model):
best_toy = models.ForeignKey(
Toy, default=get_best_toy, on_delete=models.SET_DEFAULT, related_name="toys"
)
worst_toy = models.ForeignKey(
Toy, models.SET(get_worst_toy), related_name="bad_toys"
)
| Collector |
python | sympy__sympy | sympy/functions/combinatorial/numbers.py | {
"start": 74821,
"end": 93635
} | class ____(tuple):
__slots__ = ()
_N = -1
_ITEMS = -2
_M = slice(None, _ITEMS)
def _multiset_histogram(n):
"""Return tuple used in permutation and combination counting. Input
is a dictionary giving items with counts as values or a sequence of
items (which need not be sorted).
The data is stored... | _MultisetHistogram |
python | Lightning-AI__lightning | tests/tests_pytorch/strategies/test_single_device.py | {
"start": 3073,
"end": 4681
} | class ____(BoringModel):
def train_dataloader(self):
raise NotImplementedError
def val_dataloader(self):
raise NotImplementedError
def test_dataloader(self):
raise NotImplementedError
def predict_dataloader(self):
raise NotImplementedError
_loader = DataLoader(Random... | BoringModelNoDataloaders |
python | django__django | tests/admin_widgets/tests.py | {
"start": 10521,
"end": 10892
} | class ____(TestDataMixin, TestCase):
def setUp(self):
self.client.force_login(self.superuser)
def test_changelist_ForeignKey(self):
response = self.client.get(reverse("admin:admin_widgets_car_changelist"))
self.assertContains(response, "/auth/user/add/")
@override_settings(ROOT_URLCON... | AdminForeignKeyWidgetChangeList |
python | getsentry__sentry | tests/sentry/sentry_apps/api/serializers/test_sentry_app.py | {
"start": 3783,
"end": 4467
} | class ____(TestCase):
def test_hidden_client_secret(self) -> None:
sentry_app = self.create_sentry_app(
name="Tesla App", organization=self.organization, published=True, scopes=("org:write",)
)
acc = access.from_user(self.user, self.organization)
result = serialize(sentr... | SentryAppHiddenClientSecretSerializerTest |
python | spack__spack | lib/spack/spack/llnl/util/argparsewriter.py | {
"start": 1694,
"end": 6926
} | class ____(argparse.HelpFormatter, abc.ABC):
"""Analyze an argparse ArgumentParser for easy generation of help."""
def __init__(self, prog: str, out: IO = sys.stdout, aliases: bool = False) -> None:
"""Initialize a new ArgparseWriter instance.
Args:
prog: Program name.
... | ArgparseWriter |
python | wandb__wandb | wandb/filesync/stats.py | {
"start": 225,
"end": 322
} | class ____(NamedTuple):
uploaded_bytes: int
total_bytes: int
deduped_bytes: int
| Summary |
python | getsentry__sentry | src/sentry/snuba/models.py | {
"start": 1210,
"end": 1748
} | class ____(Enum):
UNKNOWN = 0
NONE = 1
CLIENT_AND_SERVER_WEIGHTED = 2
SERVER_WEIGHTED = 3
@classmethod
def as_choices(cls):
return tuple((mode.value, mode.name.lower()) for mode in cls)
@classmethod
def as_text_choices(cls):
return tuple((mode.name.lower(), mode.value) ... | ExtrapolationMode |
python | pennersr__django-allauth | allauth/headless/mfa/inputs.py | {
"start": 785,
"end": 857
} | class ____(SignupWebAuthnForm, inputs.Input):
pass
| CreateWebAuthnInput |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 2034,
"end": 2309
} | class ____(sgqlc.types.Enum):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__choices__ = (
"COMPLETED",
"IN_PROGRESS",
"PENDING",
"QUEUED",
"REQUESTED",
"WAITING",
)
| CheckStatusState |
python | crytic__slither | slither/__main__.py | {
"start": 23127,
"end": 23561
} | class ____(argparse.Action): # pylint: disable=too-few-public-methods
def __call__(
self,
parser: Any,
args: Any,
values: Optional[Union[str, Sequence[Any]]],
option_string: Any = None,
) -> None:
detectors, printers = get_detectors_and_printers()
assert ... | OutputMarkdown |
python | falconry__falcon | falcon/errors.py | {
"start": 45520,
"end": 48792
} | class ____(HTTPError):
"""416 Range Not Satisfiable.
None of the ranges in the request's Range header field overlap the
current extent of the selected resource or that the set of ranges
requested has been rejected due to invalid ranges or an excessive
request of small or overlapping ranges.
Fo... | HTTPRangeNotSatisfiable |
python | django__django | tests/migrations/test_migrations_squashed_partially_applied/0004_remove_mymodel1_field_1_mymodel1_field_3_and_more.py | {
"start": 43,
"end": 595
} | class ____(migrations.Migration):
dependencies = [("migrations", "0003_alter_mymodel2_unique_together")]
operations = [
migrations.RemoveField(
model_name="mymodel1",
name="field_1",
),
migrations.AddField(
model_name="mymodel1",
name="fie... | Migration |
python | huggingface__transformers | src/transformers/models/xlm_roberta/modeling_xlm_roberta.py | {
"start": 3406,
"end": 6543
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a mu... | XLMRobertaSelfAttention |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVarDefaultClass3.py | {
"start": 2162,
"end": 2516
} | class ____[T1 = str, **P4 = [int, T1]]: ...
pc1 = ClassPC()
reveal_type(pc1, expected_text="ClassPC[str, (int, str)]")
pc2 = ClassPC[float]()
reveal_type(pc2, expected_text="ClassPC[float, (int, float)]")
pc3 = ClassPC[float, ...]()
reveal_type(pc3, expected_text="ClassPC[float, ...]")
# This should generate an e... | ClassPC |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/compiler.py | {
"start": 10642,
"end": 11070
} | class ____(Protocol):
def __call__(
self,
keyname: str,
name: str,
objects: Sequence[Any],
type_: TypeEngine[Any],
) -> None: ...
# integer indexes into ResultColumnsEntry used by cursor.py.
# some profiling showed integer access faster than named tuple
RM_RENDERED_NAME... | _ResultMapAppender |
python | langchain-ai__langchain | libs/core/langchain_core/prompts/image.py | {
"start": 403,
"end": 4780
} | class ____(BasePromptTemplate[ImageURL]):
"""Image prompt template for a multimodal model."""
template: dict = Field(default_factory=dict)
"""Template for the prompt."""
template_format: PromptTemplateFormat = "f-string"
"""The format of the prompt template.
Options are: 'f-string', 'mustache',... | ImagePromptTemplate |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeAlias18.py | {
"start": 512,
"end": 614
} | class ____(A_Alias_1[T2]): ...
# This should generate an error because the variance is incompatible.
| A_1 |
python | ray-project__ray | python/ray/serve/tests/test_record_routing_stats.py | {
"start": 516,
"end": 5406
} | class ____:
def __init__(self):
self.routing_stats: Dict[str, Any] = {}
self.should_hang: Optional[asyncio.Event] = None
self.should_fail: bool = False
context = _get_internal_replica_context()
self.replica_id: ReplicaID = context.replica_id
async def record_routing_stat... | Patient |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/constructor6.py | {
"start": 294,
"end": 1002
} | class ____(Generic[_T]):
@overload
def __init__(self: "TextField[str]", *, null: Literal[False] = ...) -> None: ...
@overload
def __init__(
self: "TextField[Optional[str]]",
*,
null: Literal[True] = ...,
) -> None: ...
@overload
def __init__(self, *, null: bool = ..... | TextField |
python | getsentry__sentry | src/sentry/integrations/bitbucket_server/integration.py | {
"start": 9315,
"end": 13181
} | class ____(RepositoryIntegration):
"""
IntegrationInstallation implementation for Bitbucket Server
"""
codeowners_locations = [".bitbucket/CODEOWNERS"]
@property
def integration_name(self) -> str:
return IntegrationProviderSlug.BITBUCKET_SERVER.value
def get_client(self) -> Bitbuc... | BitbucketServerIntegration |
python | tensorflow__tensorflow | tensorflow/python/framework/auto_control_deps.py | {
"start": 6331,
"end": 7161
} | class ____(enum.Enum):
READ_ONLY = "read-only"
READ_WRITE = "read-write"
def collective_manager_ids_from_op(op):
"""Returns CollectiveManager ID from the op if one exists, else None.
CollectiveManager adds collective and no_op operations tagged with an ID,
unique to the manager object. This function extrac... | ResourceType |
python | PyCQA__pyflakes | pyflakes/test/test_dict.py | {
"start": 138,
"end": 5271
} | class ____(TestCase):
def test_duplicate_keys(self):
self.flakes(
"{'yes': 1, 'yes': 2}",
m.MultiValueRepeatedKeyLiteral,
m.MultiValueRepeatedKeyLiteral,
)
def test_duplicate_keys_bytes_vs_unicode_py3(self):
self.flakes("{b'a': 1, u'a': 2}")
def... | Test |
python | sqlalchemy__sqlalchemy | test/ext/test_mutable.py | {
"start": 40221,
"end": 40361
} | class ____(MutableCompositesUnpickleTest):
@classmethod
def _type_fixture(cls):
return DCPoint
| MutableDCCompositesUnpickleTest |
python | django__django | tests/generic_relations/models.py | {
"start": 3705,
"end": 3823
} | class ____(models.Model):
bases = GenericRelation(ForProxyModelModel, for_concrete_model=False)
| ConcreteRelatedModel |
python | doocs__leetcode | solution/3300-3399/3378.Count Connected Components in LCM Graph/Solution.py | {
"start": 0,
"end": 636
} | class ____:
def __init__(self, n):
self.parent = {i: i for i in range(n)}
self.rank = {i: 0 for i in range(n)}
def make_set(self, v):
self.parent[v] = v
self.rank[v] = 1
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x]... | DSU |
python | huggingface__transformers | src/transformers/models/wav2vec2/modeling_wav2vec2.py | {
"start": 75980,
"end": 80889
} | class ____(Wav2Vec2PreTrainedModel):
def __init__(self, config):
super().__init__(config)
if hasattr(config, "add_adapter") and config.add_adapter:
raise ValueError(
"Sequence classification does not support the use of Wav2Vec2 adapters (config.add_adapter=True)"
... | Wav2Vec2ForSequenceClassification |
python | numba__numba | numba/tests/test_array_attr.py | {
"start": 1539,
"end": 4531
} | class ____(MemoryLeakMixin, TestCase):
def setUp(self):
super(TestArrayAttr, self).setUp()
self.a = np.arange(20, dtype=np.int32).reshape(4, 5)
def check_unary(self, pyfunc, arr):
aryty = typeof(arr)
cfunc = self.get_cfunc(pyfunc, (aryty,))
expected = pyfunc(arr)
... | TestArrayAttr |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/methodOverride6.py | {
"start": 1895,
"end": 2946
} | class ____(Generic[_T]):
@overload
def method1(self: "Parent2[int]", x: list[int]) -> list[int]: ...
@overload
def method1(self, x: str) -> dict[str, str]: ...
def method1(self, x: Any) -> Any: ...
@overload
def method2(self: "Parent2[int]", x: list[int]) -> list[int]: ...
@overload
... | Parent2 |
python | bokeh__bokeh | tests/unit/bokeh/embed/test_server__embed.py | {
"start": 11262,
"end": 11939
} | class ____:
def test_bad_input(self) -> None:
with pytest.raises(ValueError):
bes._process_resources("foo")
def test_None(self) -> None:
assert bes._process_resources(None) == "&resources=none"
def test_default(self) -> None:
assert bes._process_resources("default") == ... | Test__process_resources |
python | openai__gym | gym/envs/registration.py | {
"start": 2901,
"end": 26208
} | class ____:
"""A specification for creating environments with `gym.make`.
* id: The string used to create the environment with `gym.make`
* entry_point: The location of the environment to create from
* reward_threshold: The reward threshold for completing the environment.
* nondeterministic: If the... | EnvSpec |
python | walkccc__LeetCode | solutions/1131. Maximum of Absolute Value Expression/1131.py | {
"start": 0,
"end": 363
} | class ____:
def maxAbsValExpr(self, arr1: list[int], arr2: list[int]) -> int:
n = len(arr1)
a = [arr1[i] + arr2[i] + i for i in range(n)]
b = [arr1[i] + arr2[i] - i for i in range(n)]
c = [arr1[i] - arr2[i] + i for i in range(n)]
d = [arr1[i] - arr2[i] - i for i in range(n)]
return max(map(lam... | Solution |
python | django__django | django/contrib/auth/hashers.py | {
"start": 16778,
"end": 19378
} | class ____(BasePasswordHasher):
"""
Secure password hashing using the bcrypt algorithm (recommended)
This is considered by many to be the most secure algorithm but you
must first install the bcrypt library. Please be warned that
this library depends on native C code and might cause portability
... | BCryptSHA256PasswordHasher |
python | instagram__MonkeyType | tests/test_util.py | {
"start": 2667,
"end": 2738
} | class ____(Dummy):
def an_instance_method(self):
pass
| Derived |
python | tox-dev__tox | src/tox/execute/stream.py | {
"start": 472,
"end": 3691
} | class ____:
"""
Make sure data collected is synced in-memory and to the target stream on every newline and time period.
Used to propagate executed commands output to the standard output/error streams visible to the user.
"""
REFRESH_RATE = 0.1
def __init__(self, name: str, target: IO[bytes] |... | SyncWrite |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/layout/containers.py | {
"start": 4918,
"end": 5064
} | class ____(Enum):
"Alignment for `VSplit`."
LEFT = "LEFT"
CENTER = "CENTER"
RIGHT = "RIGHT"
JUSTIFY = "JUSTIFY"
| HorizontalAlign |
python | altair-viz__altair | altair/vegalite/v6/schema/core.py | {
"start": 1124648,
"end": 1124867
} | class ____(VegaLiteSchema):
"""ScaleInterpolateEnum schema wrapper."""
_schema = {"$ref": "#/definitions/ScaleInterpolateEnum"}
def __init__(self, *args):
super().__init__(*args)
| ScaleInterpolateEnum |
python | run-llama__llama_index | llama-index-integrations/retrievers/llama-index-retrievers-mongodb-atlas-bm25-retriever/llama_index/retrievers/mongodb_atlas_bm25_retriever/base.py | {
"start": 394,
"end": 4055
} | class ____(BaseRetriever):
def __init__(
self,
mongodb_client: Optional[Any] = None,
db_name: str = "default_db",
collection_name: str = "default_collection",
index_name: str = "default",
text_key: str = "text",
metadata_key: str = "metadata",
similari... | MongoDBAtlasBM25Retriever |
python | readthedocs__readthedocs.org | readthedocs/api/v2/views/integrations.py | {
"start": 13135,
"end": 21450
} | class ____(WebhookMixin, APIView):
"""
Webhook consumer for GitHub.
Accepts webhook events from GitHub, 'push' and 'pull_request' events trigger builds.
Expects the webhook event type will be included in HTTP header ``X-GitHub-Event``,
and we will have a JSON payload.
Expects the following JSO... | GitHubWebhookView |
python | getsentry__sentry | tests/sentry/core/endpoints/test_organization_environments.py | {
"start": 225,
"end": 2849
} | class ____(APITestCase):
endpoint = "sentry-api-0-organization-environments"
def setUp(self) -> None:
self.login_as(user=self.user)
@cached_property
def project(self) -> Project:
return self.create_project()
def test_simple(self) -> None:
Environment.objects.create(organiz... | OrganizationEnvironmentsTest |
python | pypa__warehouse | tests/unit/admin/views/test_organizations.py | {
"start": 20953,
"end": 23577
} | class ____:
@pytest.mark.usefixtures("_enable_organizations")
def test_rename_not_found(self, db_request):
admin = UserFactory.create()
db_request.matchdict = {
"organization_id": "deadbeef-dead-beef-dead-beefdeadbeef"
}
db_request.params = {
"new_organiz... | TestOrganizationActions |
python | getsentry__sentry | tests/sentry/api/endpoints/test_organization_sdk_deprecations.py | {
"start": 191,
"end": 4927
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
self.url = reverse(
"sentry-api-0-organization-sdk-deprecations",
kwargs={"organization_id_or_slug": self.organization.slug},
)
def test_no_event_type(self) -... | TestOrganizationSdkDeprecations |
python | html5lib__html5lib-python | doc/conf.py | {
"start": 3404,
"end": 4162
} | class ____(object):
"""Required for autodoc on readthedocs.org where you cannot build C extensions."""
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return CExtMock()
@classmethod
def __getattr__(cls, name):
if name in ('__file__', '__path__... | CExtMock |
python | pola-rs__polars | py-polars/src/polars/interchange/protocol.py | {
"start": 7346,
"end": 8799
} | class ____:
"""Data structure compatibility level."""
_version: int
def __init__(self) -> None:
msg = "it is not allowed to create a CompatLevel object"
raise TypeError(msg)
@staticmethod
def _with_version(version: int) -> CompatLevel:
compat_level = CompatLevel.__new__(Co... | CompatLevel |
python | numba__llvmlite | llvmlite/ir/values.py | {
"start": 10507,
"end": 12672
} | class ____(_StrCaching, _StringReferenceCaching, _ConstOpMixin, Value):
"""
A constant LLVM value.
"""
def __init__(self, typ, constant):
assert isinstance(typ, types.Type)
assert not isinstance(typ, types.VoidType)
self.type = typ
constant = typ.wrap_constant_value(cons... | Constant |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_contain_valid_email.py | {
"start": 1622,
"end": 11478
} | class ____(ColumnMapExpectation):
"""Expect values in given column to be valid email addresses."""
# These examples will be shown in the public gallery, and also executed as unit tests for your Expectation
examples = [
{
"data": {
"fail_case_1": ["a123@something", "a123@... | ExpectColumnValuesToContainValidEmail |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_event_details.py | {
"start": 480,
"end": 11518
} | class ____(APITestCase, SnubaTestCase, OccurrenceTestMixin):
def setUp(self) -> None:
super().setUp()
min_ago = before_now(minutes=1).isoformat()
two_min_ago = before_now(minutes=2).isoformat()
three_min_ago = before_now(minutes=3).isoformat()
self.login_as(user=self.user)
... | OrganizationEventDetailsEndpointTest |
python | sympy__sympy | sympy/tensor/array/expressions/from_array_to_indexed.py | {
"start": 581,
"end": 3936
} | class ____:
def __init__(self):
self.count_dummies = 0
def do_convert(self, expr, indices):
if isinstance(expr, ArrayTensorProduct):
cumul = list(accumulate([0] + [get_rank(arg) for arg in expr.args]))
indices_grp = [indices[cumul[i]:cumul[i+1]] for i in range(len(expr.... | _ConvertArrayToIndexed |
python | getsentry__sentry | src/sentry/identity/base.py | {
"start": 362,
"end": 2325
} | class ____(PipelineProvider["IdentityPipeline"], abc.ABC):
"""
A provider indicates how identity authenticate should happen for a given service.
"""
def __init__(self, **config):
super().__init__()
self.config = config
self.logger = logging.getLogger(f"sentry.identity.{self.key}... | Provider |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.