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 | mahmoud__boltons | tests/test_iterutils.py | {
"start": 1701,
"end": 11672
} | class ____:
# TODO: test namedtuples and other immutable containers
def test_basic_clone(self):
orig = {"a": "b", "c": [1, 2]}
assert orig == remap(orig)
orig2 = [{1: 2}, {"a": "b", "c": [1, 2, {"cat": "dog"}]}]
assert orig2 == remap(orig2)
def test_empty(self):
as... | TestRemap |
python | ray-project__ray | python/ray/llm/_internal/batch/observability/usage_telemetry/usage.py | {
"start": 1605,
"end": 3871
} | class ____:
"""Named Actor to keep the state of all deployed models and record telemetry."""
def __init__(self):
self._tracking_telemetries: List[BatchModelTelemetry] = []
self._record_tag_func = record_extra_usage_tag
def _update_record_tag_func(self, record_tag_func: Callable) -> None:
... | _TelemetryAgent |
python | numba__numba | numba/cuda/tests/cudapy/test_ipc.py | {
"start": 8029,
"end": 10039
} | class ____(ContextResettingTestCase):
def test_staged(self):
# prepare data for IPC
arr = np.arange(10, dtype=np.intp)
devarr = cuda.to_device(arr)
# spawn new process for testing
mpctx = mp.get_context('spawn')
result_queue = mpctx.Queue()
# create IPC hand... | TestIpcStaged |
python | jazzband__django-polymorphic | src/polymorphic/tests/test_admin.py | {
"start": 548,
"end": 4678
} | class ____(AdminTestCase):
def test_admin_registration(self):
"""
Test how the registration works
"""
@self.register(Model2A)
class Model2Admin(PolymorphicParentModelAdmin):
base_model = Model2A
list_filter = (PolymorphicChildModelFilter,)
... | PolymorphicAdminTests |
python | spyder-ide__spyder | external-deps/spyder-remote-services/spyder_remote_services/services/environ/handler.py | {
"start": 188,
"end": 2130
} | class ____(JupyterHandler):
"""Handler for environment variables."""
auth_resource = "spyder-services"
def write_json(self, data, status=HTTPStatus.OK):
"""Write JSON response."""
self.set_status(status)
self.set_header("Content-Type", "application/json")
self.finish(orjson... | EnvVarsHandler |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 807274,
"end": 808109
} | class ____(sgqlc.types.Type, Node, UniformResourceLocatable):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"actor",
"commit",
"created_at",
"merge_ref",
"merge_ref_name",
"pull_request",
)
actor = sgql... | MergedEvent |
python | pyca__cryptography | tests/hazmat/primitives/test_aead.py | {
"start": 1560,
"end": 9601
} | class ____:
@pytest.mark.skipif(
sys.platform not in {"linux", "darwin"} or sys.maxsize < 2**31,
reason="mmap and 64-bit platform required",
)
def test_data_too_large(self):
key = ChaCha20Poly1305.generate_key()
chacha = ChaCha20Poly1305(key)
nonce = b"0" * 12
... | TestChaCha20Poly1305 |
python | getsentry__sentry | src/sentry/dynamic_sampling/rules/helpers/latest_releases.py | {
"start": 2264,
"end": 4442
} | class ____:
"""
Class that hides the complexity of extending boosted releases.
"""
boosted_releases: list[BoostedRelease] = field(default_factory=list)
def add_release(
self, cache_key: str, id: int, timestamp: float, environment: str | None
) -> None:
self.boosted_releases.app... | BoostedReleases |
python | streamlit__streamlit | lib/tests/streamlit/runtime/state/session_state_test.py | {
"start": 13116,
"end": 17890
} | class ____(DeltaGeneratorTestCase):
def test_widget_presence(self):
state = st.session_state
assert "foo" not in state
state.foo = "foo"
assert "foo" in state
assert state.foo == "foo"
def test_widget_outputs_dont_alias(self):
color = st.select_slider(
... | SessionStateTest |
python | huggingface__transformers | src/transformers/data/datasets/glue.py | {
"start": 1106,
"end": 2164
} | class ____:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify them on the command
line.
"""
task_name: str = field(metadata={"help": "The name of the task to... | GlueDataTrainingArguments |
python | huggingface__transformers | src/transformers/models/olmo2/modular_olmo2.py | {
"start": 12273,
"end": 14002
} | class ____(OlmoDecoderLayer):
def __init__(self, config: Olmo2Config, layer_idx: int):
super().__init__(config, layer_idx=layer_idx)
self.post_attention_layernorm = Olmo2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_feedforward_layernorm = Olmo2RMSNorm(config.hidden_size, ep... | Olmo2DecoderLayer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1050394,
"end": 1050867
} | class ____(sgqlc.types.Type):
"""Email attributes from External Identity"""
__schema__ = github_schema
__field_names__ = ("primary", "type", "value")
primary = sgqlc.types.Field(Boolean, graphql_name="primary")
"""Boolean to identify primary emails"""
type = sgqlc.types.Field(String, graphql_n... | UserEmailMetadata |
python | doocs__leetcode | lcci/17.25.Word Rectangle/Solution.py | {
"start": 356,
"end": 1697
} | class ____:
def maxRectangle(self, words: List[str]) -> List[str]:
def check(mat):
m, n = len(mat), len(mat[0])
ans = 1
for j in range(n):
node = trie
for i in range(m):
idx = ord(mat[i][j]) - ord("a")
... | Solution |
python | streamlit__streamlit | lib/tests/streamlit/runtime/uploaded_file_manager_test.py | {
"start": 1143,
"end": 4279
} | class ____(unittest.TestCase):
def setUp(self):
self.mgr = MemoryUploadedFileManager("/mock/upload")
def test_added_file_id(self):
"""Presigned file URL should have a unique ID."""
info1, info2 = self.mgr.get_upload_urls("session", ["name1", "name1"])
assert info1.file_id != inf... | UploadedFileManagerTest |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_emr.py | {
"start": 2059,
"end": 2827
} | class ____:
def test_serialization(self):
job_flow_id = "test_job_flow_id"
waiter_delay = 30
waiter_max_attempts = 60
aws_conn_id = "aws_default"
trigger = EmrCreateJobFlowTrigger(
job_flow_id=job_flow_id,
waiter_delay=waiter_delay,
waiter... | TestEmrCreateJobFlowTrigger |
python | django-guardian__django-guardian | guardian/backends.py | {
"start": 1914,
"end": 5792
} | class ____:
"""Django backend for checking object-level permissions."""
supports_object_permissions = True
supports_anonymous_user = True
supports_inactive_user = True
def authenticate(self, request: HttpRequest, username: Optional[str] = None, password: Optional[str] = None) -> Any:
retur... | ObjectPermissionBackend |
python | ray-project__ray | rllib/policy/torch_policy_v2.py | {
"start": 1890,
"end": 49486
} | class ____(Policy):
"""PyTorch specific Policy class to use with RLlib."""
def __init__(
self,
observation_space: gym.spaces.Space,
action_space: gym.spaces.Space,
config: AlgorithmConfigDict,
*,
max_seq_len: int = 20,
):
"""Initializes a TorchPolicy ... | TorchPolicyV2 |
python | django-compressor__django-compressor | compressor/tests/test_parsers.py | {
"start": 840,
"end": 3703
} | class ____(ParserTestCase, CompressorTestCase):
parser_cls = "compressor.parser.Html5LibParser"
# Special test variants required since xml.etree holds attributes
# as a plain dictionary, e.g. key order is unpredictable.
def test_css_split(self):
split = self.css_node.split_contents()
ou... | Html5LibParserTests |
python | pexpect__pexpect | examples/chess2.py | {
"start": 1251,
"end": 5021
} | class ____:
def __init__(self, engine = "/usr/local/bin/gnuchess -a -h 1"):
self.child = pexpect.spawn (engine)
self.term = ANSI.ANSI ()
#self.child.expect ('Chess')
#if self.child.after != 'Chess':
# raise IOError, 'incomp... | Chess |
python | facebookresearch__faiss | tests/test_build_blocks.py | {
"start": 12095,
"end": 13082
} | class ____(unittest.TestCase):
def test_keep_min(self):
self.run_test(False)
def test_keep_max(self):
self.run_test(True)
def run_test(self, keep_max):
nq = 100
nb = 1000
restab = faiss.rand((nq, nb), 123)
ids = faiss.randint((nq, nb), 1324, 10000)
... | TestResultHeap |
python | weaviate__weaviate-python-client | weaviate/collections/classes/generative.py | {
"start": 890,
"end": 1057
} | class ____:
return_metadata: bool = False
images: Optional[Iterable[str]] = None
image_properties: Optional[List[str]] = None
| _GenerativeConfigRuntimeOptions |
python | pytorch__pytorch | test/distributed/checkpoint/test_hf_safetensor_e2e.py | {
"start": 9584,
"end": 11927
} | class ____(DTensorTestBase):
@with_comms
@with_temp_dir
@skip_if_lt_x_gpu(2)
def test_consolidate_to_one_file(self) -> None:
if importlib.util.find_spec("safetensors") is None:
print("safetensors not installed")
return
import safetensors
global_tensor = ... | TestDistributedHFSafetensorsConsolidation |
python | plotly__plotly.py | plotly/graph_objs/scatter/marker/colorbar/_tickformatstop.py | {
"start": 233,
"end": 8549
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter.marker.colorbar"
_path_str = "scatter.marker.colorbar.tickformatstop"
_valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"}
@property
def dtickrange(self):
"""
range [*min*, *max*], where "m... | Tickformatstop |
python | huggingface__transformers | src/transformers/models/video_llama_3/video_processing_video_llama_3.py | {
"start": 3105,
"end": 17379
} | class ____(BaseVideoProcessor):
resample = PILImageResampling.BICUBIC
size = {"shortest_edge": 128 * 28 * 28, "longest_edge": 28 * 28 * 768}
image_mean = IMAGENET_STANDARD_MEAN
image_std = IMAGENET_STANDARD_STD
do_resize = True
do_rescale = True
do_normalize = True
do_convert_rgb = True
... | VideoLlama3VideoProcessor |
python | dask__distributed | distributed/spill.py | {
"start": 802,
"end": 1268
} | class ____(NamedTuple):
"""Size of a key/value pair when spilled to disk, in bytes"""
# output of sizeof()
memory: int
# pickled size
disk: int
def __add__(self, other: SpilledSize) -> SpilledSize: # type: ignore
return SpilledSize(self.memory + other.memory, self.disk + other.disk)
... | SpilledSize |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/vertex_ai/test_experiment_service.py | {
"start": 3726,
"end": 4839
} | class ____:
@mock.patch(VERTEX_AI_PATH.format("ExperimentRunHook"))
def test_execute(self, mock_hook):
op = CreateExperimentRunOperator(
task_id=TASK_ID,
project_id=GCP_PROJECT,
location=GCP_LOCATION,
experiment_name=TEST_EXPERIMENT_NAME,
exper... | TestVertexAICreateExperimentRunOperator |
python | django__django | django/db/backends/postgresql/introspection.py | {
"start": 582,
"end": 12739
} | class ____(BaseDatabaseIntrospection):
# Maps type codes to Django Field types.
data_types_reverse = {
16: "BooleanField",
17: "BinaryField",
20: "BigIntegerField",
21: "SmallIntegerField",
23: "IntegerField",
25: "TextField",
700: "FloatField",
70... | DatabaseIntrospection |
python | huggingface__transformers | src/transformers/models/colpali/modeling_colpali.py | {
"start": 2249,
"end": 4474
} | class ____(ModelOutput):
r"""
loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
Language modeling loss (for next-token prediction).
embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
The embeddings of the model.
... | ColPaliForRetrievalOutput |
python | getsentry__sentry | src/sentry/analytics/events/comment_webhooks.py | {
"start": 458,
"end": 630
} | class ____(CommentEvent):
pass
analytics.register(CommentCreatedEvent)
analytics.register(CommentUpdatedEvent)
analytics.register(CommentDeletedEvent)
| CommentDeletedEvent |
python | pytest-dev__pytest-asyncio | tests/async_fixtures/test_async_fixtures.py | {
"start": 531,
"end": 814
} | class ____:
is_same_instance = False
@pytest.fixture(autouse=True)
async def async_fixture_method(self):
self.is_same_instance = True
@pytest.mark.asyncio
async def test_async_fixture_method(self):
assert self.is_same_instance
| TestAsyncFixtureMethod |
python | pypa__warehouse | tests/unit/packaging/test_views.py | {
"start": 12256,
"end": 17114
} | class ____:
@pytest.fixture
def gitlab_attestation(self, gitlab_provenance):
return gitlab_provenance.attestation_bundles[0].attestations[0]
@pytest.fixture
def github_attestation(self, github_provenance):
return github_provenance.attestation_bundles[0].attestations[0]
def test_gi... | TestPEP740AttestationViewer |
python | pytorch__pytorch | torchgen/api/ufunc.py | {
"start": 3993,
"end": 6693
} | class ____:
ctor: list[Binding]
apply: list[Binding]
# ufunctors are a CUDA-only concept representing functors that take some of
# their arguments on a host-side constructor, and the rest in the device-side
# apply. E.g.,
#
# template <typename scalar_t>
# struct CUDAFunctorOnSelf_add {
# using opmath_t = ... | UfunctorBindings |
python | pennersr__django-allauth | tests/apps/socialaccount/providers/instagram/tests.py | {
"start": 246,
"end": 967
} | class ____(OAuth2TestsMixin, TestCase):
provider_id = InstagramProvider.id
def get_mocked_response(self):
return MockedResponse(
HTTPStatus.OK,
"""
{
"username": "georgewhewell",
"bio": "",
"website": "",
"profile_picture":... | InstagramTests |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/links/glue.py | {
"start": 914,
"end": 1229
} | class ____(BaseAwsLink):
"""Helper class for constructing AWS Glue Job Run Details Link."""
name = "AWS Glue Job Run Details"
key = "glue_job_run_details"
format_str = (
BASE_AWS_CONSOLE_LINK + "/gluestudio/home?region={region_name}#/job/{job_name}/run/{job_run_id}"
)
| GlueJobRunDetailsLink |
python | python-attrs__attrs | typing-examples/mypy.py | {
"start": 8131,
"end": 8241
} | class ____:
pass
def test(cls: type) -> None:
if attr.has(cls):
attr.resolve_types(cls)
| Hashable |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/spark_s3_datasource.py | {
"start": 1119,
"end": 5845
} | class ____(_SparkFilePathDatasource):
"""
SparkS3Datasource is a subclass of SparkDatasource which connects to
Amazon S3.
"""
# class attributes
data_connector_type: ClassVar[Type[S3DataConnector]] = S3DataConnector
# these fields should not be passed to the execution engine
_EXTRA_EXCL... | SparkS3Datasource |
python | numpy__numpy | numpy/_core/tests/test_array_coercion.py | {
"start": 18600,
"end": 22852
} | class ____:
def test_nested_simple(self):
initial = [1.2]
nested = initial
for i in range(ncu.MAXDIMS - 1):
nested = [nested]
arr = np.array(nested, dtype="float64")
assert arr.shape == (1,) * ncu.MAXDIMS
with pytest.raises(ValueError):
np.arr... | TestNested |
python | pytorch__pytorch | test/inductor/test_padding.py | {
"start": 8581,
"end": 13226
} | class ____(TestCaseBase):
@maybe_cprofile
def run_acc_and_perf_test(self, model, inputs, perf_inputs=None, tol=1e-3):
"""
Run accuracy test.
Also compare the perf with and without the comprehensive padding if
DO_PERF_TEST is true.
"""
if perf_inputs is None:
... | PerfTestWithAndWithoutPadding |
python | kamyu104__LeetCode-Solutions | Python/longest-substring-with-at-most-two-distinct-characters.py | {
"start": 724,
"end": 1264
} | class ____(object):
def lengthOfLongestSubstringTwoDistinct(self, s):
"""
:type s: str
:rtype: int
"""
counter = Counter()
left, max_length = 0, 0
for right, char in enumerate(s):
counter[char] += 1
while len(counter) > 2:
... | Solution2 |
python | MongoEngine__mongoengine | tests/fields/test_string_field.py | {
"start": 99,
"end": 1382
} | class ____(MongoDBTestCase):
def test_storage(self):
class Person(Document):
name = StringField()
Person.drop_collection()
person = Person(name="test123")
person.save()
assert get_as_pymongo(person) == {"_id": person.id, "name": "test123"}
def test_validatio... | TestStringField |
python | pydantic__pydantic | pydantic/v1/types.py | {
"start": 19299,
"end": 24335
} | class ____(Decimal, metaclass=ConstrainedNumberMeta):
gt: OptionalIntFloatDecimal = None
ge: OptionalIntFloatDecimal = None
lt: OptionalIntFloatDecimal = None
le: OptionalIntFloatDecimal = None
max_digits: OptionalInt = None
decimal_places: OptionalInt = None
multiple_of: OptionalIntFloatDec... | ConstrainedDecimal |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/hooks/test_sagemaker.py | {
"start": 8110,
"end": 37656
} | class ____:
@mock.patch.object(AwsLogsHook, "get_log_events")
def test_multi_stream_iter(self, mock_log_stream):
event = {"timestamp": 1}
mock_log_stream.side_effect = [iter([event]), iter([]), None]
hook = SageMakerHook()
event_iter = hook.multi_stream_iter("log", [None, None, N... | TestSageMakerHook |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 13722,
"end": 13861
} | class ____(Stmt):
"""A statement that evaluates an expression and discards the result."""
fields = ("node",)
node: Node
| ExprStmt |
python | doocs__leetcode | solution/2800-2899/2860.Happy Students/Solution.py | {
"start": 0,
"end": 322
} | class ____:
def countWays(self, nums: List[int]) -> int:
nums.sort()
n = len(nums)
ans = 0
for i in range(n + 1):
if i and nums[i - 1] >= i:
continue
if i < n and nums[i] <= i:
continue
ans += 1
return ans
| Solution |
python | dateutil__dateutil | tests/test_tz.py | {
"start": 22890,
"end": 24553
} | class ____(unittest.TestCase):
def testSingleton(self):
UTC_0 = tz.tzutc()
UTC_1 = tz.tzutc()
self.assertIs(UTC_0, UTC_1)
def testOffset(self):
ct = datetime(2009, 4, 1, 12, 11, 13, tzinfo=tz.tzutc())
self.assertEqual(ct.utcoffset(), timedelta(seconds=0))
def test... | TzUTCTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 969130,
"end": 969608
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of SetUserInteractionLimit"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "user")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the m... | SetUserInteractionLimitPayload |
python | run-llama__llama_index | llama-index-core/tests/evaluation/test_base.py | {
"start": 339,
"end": 1965
} | class ____(BaseEvaluator):
def __init__(
self,
mock_score: float = 1.0,
mock_passing: bool = True,
mock_feedback: str = "test feedback",
) -> None:
self._mock_score = mock_score
self._mock_passing = mock_passing
self._mock_feedback = mock_feedback
def... | MockEvaluator |
python | huggingface__transformers | src/transformers/models/glm4v_moe/modeling_glm4v_moe.py | {
"start": 41509,
"end": 46306
} | class ____(Glm4vMoePreTrainedModel):
config: Glm4vMoeVisionConfig
input_modalities = ("image", "video")
_no_split_modules = ["Glm4vMoeVisionBlock"]
def __init__(self, config) -> None:
super().__init__(config)
self.spatial_merge_size = config.spatial_merge_size
self.patch_size = ... | Glm4vMoeVisionModel |
python | sqlalchemy__sqlalchemy | test/ext/test_baked.py | {
"start": 3225,
"end": 9868
} | class ____(BakedTest):
@classmethod
def setup_mappers(cls):
User = cls.classes.User
cls.mapper_registry.map_imperatively(User, cls.tables.users)
def test_first_no_result(self):
User = self.classes.User
bq = self.bakery(lambda s: s.query(User))
bq += lambda q: q.fil... | LikeQueryTest |
python | pypa__warehouse | tests/unit/email/test_init.py | {
"start": 187645,
"end": 198119
} | class ____:
def test_send_removed_project_release_file_email_to_owner(
self, pyramid_request, pyramid_config, monkeypatch
):
stub_user = pretend.stub(
id="id_1",
username="username",
name="",
email="email@example.com",
primary_email=pre... | TestRemovedReleaseFileEmail |
python | fastai__fastai | fastai/layers.py | {
"start": 22171,
"end": 24086
} | class ____(Module):
"Applies `module` over `tdim` identically for each step, use `low_mem` to compute one at a time."
def __init__(self, module, low_mem=False, tdim=1):
store_attr()
def forward(self, *tensors, **kwargs):
"input x with shape:(bs,seq_len,channels,width,height)"
... | TimeDistributed |
python | apache__airflow | providers/amazon/tests/unit/amazon/aws/triggers/test_batch.py | {
"start": 896,
"end": 1571
} | class ____:
def test_serialization(self):
job_id = "test_job_id"
aws_conn_id = "aws_default"
region_name = "us-west-2"
trigger = BatchJobTrigger(
job_id=job_id,
aws_conn_id=aws_conn_id,
region_name=region_name,
)
classpath, kwargs... | TestBatchJobTrigger |
python | doocs__leetcode | solution/2800-2899/2846.Minimum Edge Weight Equilibrium Queries in a Tree/Solution.py | {
"start": 0,
"end": 1445
} | class ____:
def minOperationsQueries(
self, n: int, edges: List[List[int]], queries: List[List[int]]
) -> List[int]:
m = n.bit_length()
g = [[] for _ in range(n)]
f = [[0] * m for _ in range(n)]
p = [0] * n
cnt = [None] * n
depth = [0] * n
for u, v... | Solution |
python | huggingface__transformers | src/transformers/models/jamba/modular_jamba.py | {
"start": 27906,
"end": 29098
} | class ____(PreTrainedModel):
config: JambaConfig
base_model_prefix = "model"
supports_gradient_checkpointing = True
_no_split_modules = ["JambaAttentionDecoderLayer", "JambaMambaDecoderLayer"]
_skip_keys_device_placement = "past_key_values"
_supports_flash_attn = True
_supports_sdpa = True
... | JambaPreTrainedModel |
python | psf__requests | src/requests/sessions.py | {
"start": 13254,
"end": 30503
} | class ____(SessionRedirectMixin):
"""A Requests session.
Provides cookie persistence, connection-pooling, and configuration.
Basic Usage::
>>> import requests
>>> s = requests.Session()
>>> s.get('https://httpbin.org/get')
<Response [200]>
Or as a context manager::
>>>... | Session |
python | tensorflow__tensorflow | tensorflow/python/ops/nn_test.py | {
"start": 63070,
"end": 66828
} | class ____(test_lib.TestCase):
def test1DTensor(self):
x = array_ops.ones([3, 6, 5])
ksize = 2
strides = 2
y1 = nn_ops.max_pool_v2(x, ksize, strides, "SAME")
y2 = nn_ops.max_pool1d(x, ksize, strides, "SAME")
self.assertAllEqual(self.evaluate(y1), self.evaluate(y2))
def test1DNumpy(self):... | MaxPoolTest |
python | ApeWorX__ape | src/ape/plugins/compiler.py | {
"start": 147,
"end": 966
} | class ____(PluginType):
"""
A plugin that implements the :class:`ape.api.CompilerAPI`, such
as the `ape-solidity plugin <https://github.com/ApeWorX/ape-solidity>`__
or the `ape-vyper plugin <https://github.com/ApeWorX/ape-vyper>`__.
"""
@hookspec
def register_compiler( # type: ignore[empty... | CompilerPlugin |
python | getsentry__sentry | fixtures/page_objects/base.py | {
"start": 409,
"end": 494
} | class ____:
def __init__(self, element):
self.element = element
| BaseElement |
python | chroma-core__chroma | chromadb/db/impl/sqlite.py | {
"start": 1885,
"end": 9426
} | class ____(MigratableDB, SqlEmbeddingsQueue, SqlSysDB):
_conn_pool: Pool
_settings: Settings
_migration_imports: Sequence[Traversable]
_db_file: str
_tx_stack: local
_is_persistent: bool
def __init__(self, system: System):
self._settings = system.settings
self._migration_imp... | SqliteDB |
python | huggingface__transformers | tests/models/idefics/test_image_processing_idefics.py | {
"start": 4405,
"end": 7734
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = IdeficsImageProcessor if is_vision_available() else None
def setUp(self):
super().setUp()
self.image_processor_tester = IdeficsImageProcessingTester(self)
@property
def image_processor_dict(self):
... | IdeficsImageProcessingTest |
python | vyperlang__vyper | vyper/venom/analysis/mem_ssa.py | {
"start": 2590,
"end": 2997
} | class ____(MemoryAccess):
"""Represents a phi node for memory states"""
def __init__(self, id: int, block: IRBasicBlock):
super().__init__(id)
self.block = block
self.operands: list[tuple[MemoryPhiOperand, IRBasicBlock]] = []
# Type aliases for signatures in this module
MemoryDefOrUse... | MemoryPhi |
python | doocs__leetcode | solution/0700-0799/0764.Largest Plus Sign/Solution.py | {
"start": 0,
"end": 741
} | class ____:
def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:
dp = [[n] * n for _ in range(n)]
for x, y in mines:
dp[x][y] = 0
for i in range(n):
left = right = up = down = 0
for j, k in zip(range(n), reversed(range(n))):
... | Solution |
python | rapidsai__cudf | python/cudf_polars/cudf_polars/experimental/benchmarks/pdsds.py | {
"start": 1716,
"end": 1847
} | class ____(metaclass=PDSDSQueriesMeta):
"""Base class for query loading."""
q_impl: str
name: str = "pdsds"
| PDSDSQueries |
python | pytorch__pytorch | torch/_inductor/codegen/halide.py | {
"start": 61617,
"end": 63426
} | class ____(SIMDScheduling):
kernel_type = HalideKernel # type: ignore[arg-type,assignment]
@classmethod
def get_backend_features(cls, device: torch.device) -> OrderedSet[BackendFeature]:
result = OrderedSet(
[
BackendFeature.TUPLE_REDUCTION,
BackendFeatu... | HalideScheduling |
python | pydata__xarray | xarray/core/indexes.py | {
"start": 996,
"end": 22711
} | class ____:
"""
Base class inherited by all xarray-compatible indexes.
Do not use this class directly for creating index objects. Xarray indexes
are created exclusively from subclasses of ``Index``, mostly via Xarray's
public API like ``Dataset.set_xindex``.
Every subclass must at least implem... | Index |
python | getsentry__sentry | tests/sentry/features/test_manager.py | {
"start": 2031,
"end": 18305
} | class ____(TestCase):
def test_feature_registry(self) -> None:
manager = features.FeatureManager()
assert manager.all() == {}
manager.add("organizations:feature1", OrganizationFeature)
manager.add("projects:feature2", ProjectFeature)
manager.add("projects:feature3", ProjectF... | FeatureManagerTest |
python | dagster-io__dagster | python_modules/dagster-test/dagster_test/toys/longitudinal.py | {
"start": 1106,
"end": 3959
} | class ____(Exception):
"""To distinguish from other errors."""
def make_op(
name,
asset_key=None,
error_rate=None,
data_size_fn=None,
sleep_factor=None,
has_input=False,
):
@op(
name=name,
config_schema={"partition": str},
ins={"the_input": In(dagster_type=Nothi... | IntentionalRandomFailure |
python | huggingface__transformers | src/transformers/models/perceiver/modeling_perceiver.py | {
"start": 91107,
"end": 98417
} | class ____(PerceiverAbstractDecoder):
"""
Multimodal decoding by composing uni-modal decoders. The *modalities* argument of the constructor is a dictionary
mapping modality name to the decoder of that modality. That decoder will be used to construct queries for that
modality. Modality-specific queries a... | PerceiverMultimodalDecoder |
python | kamyu104__LeetCode-Solutions | Python/maximum-xor-product.py | {
"start": 38,
"end": 404
} | class ____(object):
def maximumXorProduct(self, a, b, n):
"""
:type a: int
:type b: int
:type n: int
:rtype: int
"""
MOD = 10**9+7
for i in reversed(xrange(n)):
base = 1<<i
if min(a, b)&base == 0:
a, b = a^base, ... | Solution |
python | pytorch__pytorch | test/dynamo/test_modules.py | {
"start": 31240,
"end": 54526
} | class ____(torch._dynamo.test_case.TestCase):
test_seq = make_test(Seq())
test_basicmodule1 = make_test(BasicModule())
test_basicmodule2 = make_test(BasicModule())
test_submodules1 = make_test(SubmoduleExample())
test_submodules2 = make_test(SubmoduleExample())
test_modulemethod1 = make_test(Mod... | NNModuleTests |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/fault_tolerance_test.py | {
"start": 1748,
"end": 2379
} | class ____(
fault_tolerance_test_base.BaseFaultToleranceTest, test.TestCase):
"""Single worker fault tolerance tests.
This covers the cases that ensure training can continue in a single-worker
cluster, even if the only worker can become unavailable at some point and
recovered (if there are multiple workers... | SingleWorkerFaultToleranceTest |
python | huggingface__transformers | src/transformers/models/voxtral/modular_voxtral.py | {
"start": 1341,
"end": 1397
} | class ____(Qwen2AudioAttention):
pass
| VoxtralAttention |
python | doocs__leetcode | solution/1500-1599/1522.Diameter of N-Ary Tree/Solution.py | {
"start": 184,
"end": 748
} | class ____:
def diameter(self, root: 'Node') -> int:
"""
:type root: 'Node'
:rtype: int
"""
def dfs(root):
if root is None:
return 0
nonlocal ans
m1 = m2 = 0
for child in root.children:
t = dfs(c... | Solution |
python | ray-project__ray | rllib/core/models/torch/utils.py | {
"start": 89,
"end": 2945
} | class ____(nn.Module):
"""A striding layer for doing torch Conv2DTranspose operations.
Using this layer before the 0-padding (on a 3D input "image") and before
the actual ConvTranspose2d allows for a padding="same" behavior that matches
100% that of a `tf.keras.layers.Conv2DTranspose` layer.
Examp... | Stride2D |
python | spyder-ide__spyder | spyder/plugins/console/widgets/internalshell.py | {
"start": 3470,
"end": 15996
} | class ____(PythonShellWidget):
"""Shell base widget: link between PythonShellWidget and Interpreter"""
# --- Signals
# This signal is emitted when the buffer is flushed
sig_refreshed = Signal()
# Request to show a status message on the main window
sig_show_status_requested = Signal(str)
... | InternalShell |
python | altair-viz__altair | altair/vegalite/v6/schema/channels.py | {
"start": 415431,
"end": 420788
} | class ____(
ValueChannelMixin, core.ValueDefWithConditionMarkPropFieldOrDatumDefnumber
):
"""
OpacityValue schema wrapper.
Parameters
----------
condition : dict, :class:`ConditionalValueDefnumberExprRef`, :class:`ConditionalMarkPropFieldOrDatumDef`, :class:`ConditionalParameterValueDefnumberEx... | OpacityValue |
python | kamyu104__LeetCode-Solutions | Python/largest-palindromic-number.py | {
"start": 71,
"end": 669
} | class ____(object):
def largestPalindromic(self, num):
"""
:type num: str
:rtype: str
"""
cnt = collections.Counter(num)
result = []
for i in reversed(xrange(10)):
if not cnt[str(i)]//2 or (i == 0 and not result):
continue
... | Solution |
python | cython__cython | Cython/Compiler/FlowControl.py | {
"start": 22569,
"end": 23006
} | class ____(TreeVisitor):
def __init__(self):
super().__init__()
self.assignments = []
def visit_Node(self):
self._visitchildren(self, None, None)
def visit_SingleAssignmentNode(self, node):
self.assignments.append((node.lhs, node.rhs))
def visit_CascadedAssignmentNode(... | AssignmentCollector |
python | tensorflow__tensorflow | tensorflow/python/ops/numpy_ops/np_array_ops_test.py | {
"start": 19785,
"end": 41797
} | class ____(test.TestCase):
def setUp(self):
super(ArrayMethodsTest, self).setUp()
set_up_virtual_devices()
self.array_transforms = [
lambda x: x,
ops.convert_to_tensor,
np.array,
np_array_ops.array,
]
def testAllAny(self):
def run_test(arr, *args, **kwargs):
... | ArrayMethodsTest |
python | scikit-learn__scikit-learn | sklearn/cluster/_birch.py | {
"start": 3685,
"end": 9566
} | class ____:
"""Each node in a CFTree is called a CFNode.
The CFNode can have a maximum of branching_factor
number of CFSubclusters.
Parameters
----------
threshold : float
Threshold needed for a new subcluster to enter a CFSubcluster.
branching_factor : int
Maximum number ... | _CFNode |
python | pyca__cryptography | src/cryptography/x509/name.py | {
"start": 490,
"end": 3536
} | class ____(utils.Enum):
BitString = 3
OctetString = 4
UTF8String = 12
NumericString = 18
PrintableString = 19
T61String = 20
IA5String = 22
UTCTime = 23
GeneralizedTime = 24
VisibleString = 26
UniversalString = 28
BMPString = 30
_ASN1_TYPE_TO_ENUM = {i.value: i for i in... | _ASN1Type |
python | cython__cython | tests/run/pep526_variable_annotations.py | {
"start": 2802,
"end": 7762
} | class ____(object):
pass
c = Cls()
c.x: int = 0 # Annotates c.x with int.
c.y: int # Annotates c.y with int.
d = {}
d['a']: int = 0 # Annotates d['a'] with int.
d['b']: int # Annotates d['b'] with int.
(x): int # Annotates x with int, (x) treated as expression by compiler.
(y): int = 0 # Same ... | Cls |
python | ray-project__ray | python/ray/data/_internal/datasource/parquet_datasource.py | {
"start": 38211,
"end": 46993
} | class ____:
# Estimated avg byte size of a row (in-memory)
avg_row_in_mem_bytes: Optional[int]
# Corresponding file metadata
metadata: "pyarrow._parquet.FileMetaData"
def estimate_in_memory_bytes(self) -> Optional[int]:
if self.avg_row_in_mem_bytes is None:
return None
... | _ParquetFileInfo |
python | nryoung__algorithms | tests/test_data_structures.py | {
"start": 20416,
"end": 20875
} | class ____(unittest.TestCase):
"""
Test Union Find Implementation
"""
def test_union_find(self):
self.uf = union_find.UnionFind(4)
self.uf.make_set(4)
self.uf.union(1, 0)
self.uf.union(3, 4)
self.assertEqual(self.uf.find(1), 0)
self.assertEqual(self.uf.fi... | TestUnionFind |
python | redis__redis-py | tests/test_scenario/fault_injector_client.py | {
"start": 393,
"end": 704
} | class ____(str, Enum):
DMC_RESTART = "dmc_restart"
FAILOVER = "failover"
RESHARD = "reshard"
SEQUENCE_OF_ACTIONS = "sequence_of_actions"
NETWORK_FAILURE = "network_failure"
EXECUTE_RLUTIL_COMMAND = "execute_rlutil_command"
EXECUTE_RLADMIN_COMMAND = "execute_rladmin_command"
| ActionType |
python | django__django | tests/queries/models.py | {
"start": 17129,
"end": 17391
} | class ____(models.Model):
modela_fk = models.ForeignKey(Ticket23605A, models.CASCADE)
modelc_fk = models.ForeignKey("Ticket23605C", models.CASCADE)
field_b0 = models.IntegerField(null=True)
field_b1 = models.BooleanField(default=False)
| Ticket23605B |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/check_ops_test.py | {
"start": 49422,
"end": 54908
} | class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes
def test_rank_zero_tensor_raises_if_rank_mismatch_static_rank(self):
tensor_rank0 = constant_op.constant(42, name="my_tensor")
with self.assertRaisesRegex(ValueError, "fail.*must have rank.*in.*1.*2"):
with ops.control_dependencies([
... | AssertRankInTest |
python | tiangolo__fastapi | docs_src/security/tutorial004.py | {
"start": 1121,
"end": 4172
} | class ____(User):
hashed_password: str
password_hash = PasswordHash.recommended()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
app = FastAPI()
def verify_password(plain_password, hashed_password):
return password_hash.verify(plain_password, hashed_password)
def get_password_hash(password):
... | UserInDB |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/language/ast.py | {
"start": 20960,
"end": 21015
} | class ____(TypeDefinition):
pass
| TypeSystemDefinition |
python | python-markdown__markdown | markdown/inlinepatterns.py | {
"start": 26829,
"end": 33159
} | class ____(InlineProcessor):
""" Return a link element from the given match. """
RE_LINK = re.compile(r'''\(\s*(?:(<[^<>]*>)\s*(?:('[^']*'|"[^"]*")\s*)?\))?''', re.DOTALL | re.UNICODE)
RE_TITLE_CLEAN = re.compile(r'\s')
def handleMatch(self, m: re.Match[str], data: str) -> tuple[etree.Element | None, i... | LinkInlineProcessor |
python | pandas-dev__pandas | pandas/tests/arrays/categorical/test_repr.py | {
"start": 204,
"end": 681
} | class ____:
def test_print(self, using_infer_string):
factor = Categorical(["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True)
dtype = "str" if using_infer_string else "object"
expected = [
"['a', 'b', 'b', 'a', 'a', 'c', 'c', 'c']",
f"Categories (3, {dtype}): ['a... | TestCategoricalReprWithFactor |
python | kamyu104__LeetCode-Solutions | Python/sum-of-nodes-with-even-valued-grandparent.py | {
"start": 191,
"end": 669
} | class ____(object):
def sumEvenGrandparent(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def sumEvenGrandparentHelper(root, p, gp):
return sumEvenGrandparentHelper(root.left, root.val, p) + \
sumEvenGrandparentHelper(root.right, root.val... | Solution |
python | streamlit__streamlit | lib/streamlit/runtime/credentials.py | {
"start": 1114,
"end": 3305
} | class ____(NamedTuple):
email: str | None # the user's email.
is_valid: bool # whether the email is valid.
def email_prompt() -> str:
# Emoji can cause encoding errors on non-UTF-8 terminals
# (See https://github.com/streamlit/streamlit/issues/2284.)
# WT_SESSION is a Windows Terminal specific e... | _Activation |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/callbackProtocol7.py | {
"start": 500,
"end": 664
} | class ____(Protocol):
def __call__(self, x: int, y: int = 2, /): ...
def test2(p1: P1, p2: P2, p3: P3, p4: P4):
x1: P1 = p2
x2: P1 = p3
x3: P1 = p4
| P4 |
python | zarr-developers__zarr-python | src/zarr/storage/_fsspec.py | {
"start": 2101,
"end": 14699
} | class ____(Store):
"""
Store for remote data based on FSSpec.
Parameters
----------
fs : AsyncFileSystem
The Async FSSpec filesystem to use with this store.
read_only : bool
Whether the store is read-only
path : str
The root path of the store. This should be a relati... | FsspecStore |
python | jina-ai__jina | jina/clients/base/stream_rpc.py | {
"start": 85,
"end": 2110
} | class ____:
"""Class that encapsulated the methods required to run a stream rpc call from the client. Instantiate a single class
for each client request.
"""
def __init__(
self,
channel,
continue_on_error,
metadata,
on_always,
on_done,
on_error,
... | StreamRpc |
python | pydantic__pydantic | pydantic/plugin/__init__.py | {
"start": 4969,
"end": 6291
} | class ____(BaseValidateHandlerProtocol, Protocol):
"""Event handler for `SchemaValidator.validate_json`."""
def on_enter(
self,
input: str | bytes | bytearray,
*,
strict: bool | None = None,
extra: ExtraValues | None = None,
context: Any | None = None,
se... | ValidateJsonHandlerProtocol |
python | huggingface__transformers | src/transformers/models/gemma2/modular_gemma2.py | {
"start": 18745,
"end": 18807
} | class ____(GemmaPreTrainedModel):
pass
| Gemma2PreTrainedModel |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/skill_list_params.py | {
"start": 331,
"end": 1099
} | class ____(TypedDict, total=False):
limit: int
"""Number of results to return per page.
Maximum value is 100. Defaults to 20.
"""
page: Optional[str]
"""Pagination token for fetching a specific page of results.
Pass the value from a previous response's `next_page` field to get the next pa... | SkillListParams |
python | PrefectHQ__prefect | src/prefect/cli/_prompts.py | {
"start": 10528,
"end": 10920
} | class ____(PromptBase[str]):
response_type: type[str] = str
validate_error_message = "[prompt.invalid]Please enter a valid RRule string"
def process_response(self, value: str) -> str:
try:
RRuleSchedule.validate_rrule_str(value)
return value
except ValueError:
... | RRuleStringPrompt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.