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 | kamyu104__LeetCode-Solutions | Python/path-with-minimum-effort.py | {
"start": 4747,
"end": 6045
} | class ____(object):
def minimumEffortPath(self, heights):
"""
:type heights: List[List[int]]
:rtype: int
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def check(heights, x):
lookup = [[False]*len(heights[0]) for _ in xrange(len(heights))]
... | Solution4 |
python | pytorch__pytorch | test/inductor/test_aot_inductor_arrayref.py | {
"start": 10097,
"end": 10587
} | 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 = True
use_minimal_arrayref_interface = False
copy_tests(
AOTInductorTestsTe... | AOTInductorTestABICompatibleCpuWithStackAllocation |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-snowflake-cortex/unit_tests/destination_test.py | {
"start": 393,
"end": 3166
} | class ____(unittest.TestCase):
def setUp(self):
self.config = {
"processing": {"text_fields": ["str_col"], "metadata_fields": [], "chunk_size": 1000},
"embedding": {"mode": "openai", "openai_key": "mykey"},
"indexing": {
"host": "MYACCOUNT",
... | TestDestinationSnowflakeCortex |
python | pypa__virtualenv | src/virtualenv/create/via_global_ref/builtin/pypy/pypy3.py | {
"start": 259,
"end": 481
} | class ____(PyPy, Python3Supports, abc.ABC):
@classmethod
def exe_stem(cls):
return "pypy3"
@classmethod
def exe_names(cls, interpreter):
return super().exe_names(interpreter) | {"pypy"}
| PyPy3 |
python | prabhupant__python-ds | data_structures/bst/duplicate_keys.py | {
"start": 267,
"end": 2069
} | class ____():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.count = 1
def inorder(root):
if not root:
return None
stack = []
while True:
if root:
stack.append(root)
root = root.left
else:... | Node |
python | pypa__warehouse | tests/unit/manage/views/test_organizations.py | {
"start": 107343,
"end": 112811
} | class ____:
@pytest.mark.usefixtures("_enable_organizations")
@pytest.mark.parametrize("orgtype", list(OrganizationType))
def test_change_role(self, db_request, orgtype, monkeypatch):
organization = OrganizationFactory.create(name="foobar", orgtype=orgtype)
user = UserFactory.create(username... | TestChangeOrganizationRole |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 49728,
"end": 50398
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = (
"project_id",
"title",
"body",
"assignee_ids",
"client_mutation_id",
)
project_id = sgqlc.types.Field(ID, graphql_name="projectId")
... | AddProjectDraftIssueInput |
python | fluentpython__example-code-2e | 21-async/mojifinder/bottle.py | {
"start": 133006,
"end": 135823
} | class ____(BaseTemplate):
def prepare(self, escape_func=html_escape, noescape=False, syntax=None, **ka):
self.cache = {}
enc = self.encoding
self._str = lambda x: touni(x, enc)
self._escape = lambda x: escape_func(touni(x, enc))
self.syntax = syntax
if noescape:
... | SimpleTemplate |
python | keras-team__keras | keras/src/utils/dataset_utils_test.py | {
"start": 403,
"end": 2207
} | class ____(TorchDataset):
def __init__(self, x, y=None):
# Convert NumPy → Torch tensors if needed
def to_tensor(v):
if isinstance(v, torch.Tensor):
return v
if hasattr(v, "shape"):
return torch.as_tensor(v, dtype=torch.float32)
ret... | MyTorchDataset |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/data_asset/path/spark/orc_asset.py | {
"start": 540,
"end": 1313
} | class ____(_SparkGenericFilePathAssetMixin):
# The options below are available as of spark v3.4.0
# See https://spark.apache.org/docs/latest/sql-data-sources-orc.html for more info.
merge_schema: Optional[Union[bool, str]] = Field(False, alias="mergeSchema")
class Config:
extra = "forbid"
... | ORCAssetBase |
python | kubernetes-client__python | kubernetes/client/models/v1_pod_disruption_budget.py | {
"start": 383,
"end": 7466
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1PodDisruptionBudget |
python | getsentry__sentry | src/sentry/api/serializers/models/userreport.py | {
"start": 914,
"end": 1012
} | class ____(TypedDict):
event_user: EventUser | dict[None, None]
@register(UserReport)
| _EventUser |
python | django__django | tests/admin_docs/test_views.py | {
"start": 24907,
"end": 29071
} | class ____(SimpleTestCase):
def test_simplify_regex(self):
tests = (
# Named and unnamed groups.
(r"^(?P<a>\w+)/b/(?P<c>\w+)/$", "/<a>/b/<c>/"),
(r"^(?P<a>\w+)/b/(?P<c>\w+)$", "/<a>/b/<c>"),
(r"^(?P<a>\w+)/b/(?P<c>\w+)", "/<a>/b/<c>"),
(r"^(?P<a>\w... | AdminDocViewFunctionsTests |
python | ipython__ipython | tests/test_guarded_eval.py | {
"start": 7506,
"end": 7877
} | class ____:
def heap(self) -> "HeapType":
return HeapType()
def copy(self) -> "StringAnnotation":
return StringAnnotation()
CustomIntType = NewType("CustomIntType", int)
CustomHeapType = NewType("CustomHeapType", HeapType)
IntTypeAlias = TypeAliasType("IntTypeAlias", int)
HeapTypeAlias = Type... | StringAnnotation |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/oracle/base.py | {
"start": 45966,
"end": 65049
} | class ____(compiler.SQLCompiler):
"""Oracle compiler modifies the lexical structure of Select
statements to work under non-ANSI configured Oracle databases, if
the use_ansi flag is False.
"""
compound_keywords = util.update_copy(
compiler.SQLCompiler.compound_keywords,
{expression.C... | OracleCompiler |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_speech_to_text.py | {
"start": 1415,
"end": 4358
} | class ____:
@patch("airflow.providers.google.cloud.operators.speech_to_text.CloudSpeechToTextHook")
def test_recognize_speech_green_path(self, mock_hook):
mock_hook.return_value.recognize_speech.return_value = RecognizeResponse()
CloudSpeechToTextRecognizeSpeechOperator(
project_id=... | TestCloudSpeechToTextRecognizeSpeechOperator |
python | google__pytype | pytype/typegraph/cfg_utils.py | {
"start": 10569,
"end": 12001
} | class ____(Protocol):
incoming: "Iterable[SuccessorNode]"
_SuccessorNode = TypeVar("_SuccessorNode", bound=SuccessorNode)
def topological_sort(
nodes: Iterable[_SuccessorNode],
) -> Generator[_SuccessorNode, None, None]:
"""Sort a list of nodes topologically.
This will order the nodes so that any node th... | SuccessorNode |
python | has2k1__plotnine | plotnine/scales/scale_manual.py | {
"start": 1834,
"end": 1967
} | class ____(scale_color_manual):
"""
Custom discrete fill scale
"""
_aesthetics = ["fill"]
@dataclass
| scale_fill_manual |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 47396,
"end": 47849
} | class ____(VOWarning, ValueError):
"""
The ``type`` attribute of the ``RESOURCE`` element must be one of
"results" or "meta".
**References**: `1.1
<http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
`1.2
<http://www.ivoa.net/documents/VOTable/20091130/RE... | E18 |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclass11.py | {
"start": 271,
"end": 356
} | class ____(Generic[Key0, Value]):
key: Key0
value: Value
@dataclass
| MapTreeLeaf |
python | getsentry__sentry | src/sentry/apidocs/examples/environment_examples.py | {
"start": 51,
"end": 1077
} | class ____:
EXAMPLE_ORG_ENVIRONMENTS = [
{"id": "1", "name": "Production"},
{"id": "2", "name": "Staging"},
]
GET_ORGANIZATION_ENVIRONMENTS = [
OpenApiExample(
"List an Organization's Environments",
value=EXAMPLE_ORG_ENVIRONMENTS,
status_codes=["20... | EnvironmentExamples |
python | gevent__gevent | src/gevent/tests/test__pywsgi.py | {
"start": 61538,
"end": 62362
} | class ____(TestCase):
validator = None
# check that WSGIServer does not insert any default values for CONTENT_LENGTH
def application(self, environ, start_response):
for key, value in environ.items():
if key in ('CONTENT_LENGTH', 'CONTENT_TYPE') or key.startswith('HTTP_'):
... | TestInvalidEnviron |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType28.py | {
"start": 1517,
"end": 1562
} | class ____(Generic[T_co, T_contra]): ...
| Class6 |
python | tensorflow__tensorflow | tensorflow/python/kernel_tests/array_ops/unique_op_test.py | {
"start": 991,
"end": 6481
} | class ____(test.TestCase):
def testInt32(self):
x = np.random.randint(2, high=10, size=7000)
y, idx = array_ops.unique(x)
tf_y, tf_idx = self.evaluate([y, idx])
self.assertEqual(len(x), len(tf_idx))
self.assertEqual(len(tf_y), len(np.unique(x)))
for i in range(len(x)):
self.assertEqual... | UniqueTest |
python | walkccc__LeetCode | solutions/3154. Find Number of Ways to Reach the K-th Stair/3154.py | {
"start": 0,
"end": 750
} | class ____:
def waysToReachStair(self, k: int) -> int:
# Let's say we have `down` operation 1 and `jump` operation 2.
# The final stair is 1 + (2^0 + 2^1 + ... + 2^(jump - 1)) - down = k.
# => 1 + (2^jump - 1) - down = k.
# => down = 2^jump - k.
# Since `down` operations cannot be used consecutive... | Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 516,
"end": 756
} | class ____(sgqlc.types.Enum):
"""The actor's type.
Enumeration Choices:
* `TEAM`: Indicates a team actor.
* `USER`: Indicates a user actor.
"""
__schema__ = github_schema
__choices__ = ("TEAM", "USER")
| ActorType |
python | getsentry__sentry | tests/sentry/workflow_engine/processors/test_action.py | {
"start": 11602,
"end": 13148
} | class ____(BaseWorkflowTest):
@patch("sentry.workflow_engine.processors.action._get_integration_features")
def test_basic(self, mock_get_features: MagicMock) -> None:
org = self.create_organization()
# Test non-integration actions (should always be permitted)
assert is_action_permitted(... | TestIsActionPermitted |
python | pandas-dev__pandas | pandas/tests/tseries/offsets/test_offsets.py | {
"start": 29869,
"end": 41255
} | class ____:
def test_str_for_named_is_name(self):
# look at all the amazing combinations!
month_prefixes = [
"YE",
"YS",
"BYE",
"BYS",
"QE",
"BQE",
"BQS",
"QS",
"HYE",
"HYS",
... | TestReprNames |
python | doocs__leetcode | solution/0900-0999/0904.Fruit Into Baskets/Solution2.py | {
"start": 0,
"end": 359
} | class ____:
def totalFruit(self, fruits: List[int]) -> int:
cnt = Counter()
j = 0
for x in fruits:
cnt[x] += 1
if len(cnt) > 2:
y = fruits[j]
cnt[y] -= 1
if cnt[y] == 0:
cnt.pop(y)
j +... | Solution |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 119754,
"end": 120085
} | class ____(sgqlc.types.Input):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("field", "direction")
field = sgqlc.types.Field(PackageVersionOrderField, graphql_name="field")
direction = sgqlc.types.Field(OrderDirection, graphql_name="direction")
| PackageVersionOrder |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataproc.py | {
"start": 3138,
"end": 3850
} | class ____:
"""
Defines machines types and a rank to which the machines types belong.
Representation for
google.cloud.dataproc.v1#google.cloud.dataproc.v1.InstanceFlexibilityPolicy.InstanceSelection.
:param machine_types: Full machine-type names, e.g. "n1-standard-16".
:param rank: Preference ... | InstanceSelection |
python | getsentry__sentry | src/sentry/integrations/slack/message_builder/notifications/digest.py | {
"start": 545,
"end": 3139
} | class ____(SlackNotificationsMessageBuilder):
def __init__(
self,
notification: DigestNotification,
context: Mapping[str, Any],
recipient: Actor,
) -> None:
super().__init__(notification, context, recipient)
self.notification: DigestNotification = notification
... | DigestNotificationMessageBuilder |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/publish/pipeline.py | {
"start": 13001,
"end": 16549
} | class ____(Step):
context: PublishConnectorContext
title = "Upload connector spec to spec cache bucket"
default_spec_file_name = "spec.json"
cloud_spec_file_name = "spec.cloud.json"
@property
def spec_key_prefix(self) -> str:
return "specs/" + self.context.docker_image.replace(":", "/")... | UploadSpecToCache |
python | python__mypy | mypyc/ir/rtypes.py | {
"start": 28570,
"end": 30201
} | class ____(RType):
"""C struct type"""
def __init__(self, name: str, names: list[str], types: list[RType]) -> None:
self.name = name
self.names = names
self.types = types
# generate dummy names
if len(self.names) < len(self.types):
for i in range(len(self.typ... | RStruct |
python | google__pytype | pytype/pyi/definitions.py | {
"start": 6833,
"end": 7194
} | class ____(visitors.Visitor):
"""Visitor for inserting TypeParameter instances."""
def __init__(self, type_params):
super().__init__()
self.type_params = {p.name: p for p in type_params}
def VisitNamedType(self, node):
if node.name in self.type_params:
return self.type_params[node.name]
el... | _InsertTypeParameters |
python | django-haystack__django-haystack | haystack/inputs.py | {
"start": 767,
"end": 933
} | class ____(BaseInput):
"""
Represents a bare Python non-string type.
Largely only for internal use.
"""
input_type_name = "python_data"
| PythonData |
python | run-llama__llama_index | llama-index-integrations/callbacks/llama-index-callbacks-uptrain/llama_index/callbacks/uptrain/base.py | {
"start": 1319,
"end": 13144
} | class ____(BaseCallbackHandler):
"""
UpTrain callback handler.
This class is responsible for handling the UpTrain API and logging events to UpTrain.
"""
def __init__(
self,
api_key: str,
key_type: Literal["uptrain", "openai"],
project_name: str = "uptrain_llamainde... | UpTrainCallbackHandler |
python | pytorch__pytorch | test/fx/test_fx_node_hook.py | {
"start": 136,
"end": 3373
} | class ____(TestCase):
def test_hooks_for_node_update(self):
global create_node_hook1_called
global create_node_hook2_called
global erase_node_hook1_called
global erase_node_hook2_called
global replace_node_hook1_called
global replace_node_hook2_called
create_n... | TestFXNodeHook |
python | ray-project__ray | python/ray/data/_internal/issue_detection/detectors/hash_shuffle_detector.py | {
"start": 589,
"end": 783
} | class ____:
"""Configuration for HashShuffleAggregatorIssueDetector."""
detection_time_interval_s: float = 30.0
min_wait_time_s: float = 300.0
| HashShuffleAggregatorIssueDetectorConfig |
python | google__jax | tests/pallas/tpu_fusible_matmul_test.py | {
"start": 6054,
"end": 30776
} | class ____(jtu.JaxTestCase):
def setUp(self):
if not jtu.is_device_tpu_at_least(4):
self.skipTest('Only works with TPU v4+')
super().setUp()
@parameterized.parameters('float32', 'bfloat16')
def test_matmul(self, dtype):
k0, k1 = jax.random.split(jax.random.key(0))
x = jax.random.normal(k0,... | FusibleMatmulTest |
python | mlflow__mlflow | mlflow/utils/_capture_transformers_modules.py | {
"start": 378,
"end": 2584
} | class ____(_CaptureImportedModules):
"""
A context manager to capture imported modules by temporarily applying a patch to
`builtins.__import__` and `importlib.import_module`.
Used for 'transformers' flavor only.
"""
def __init__(self, module_to_throw, record_full_module=False):
super().... | _CaptureImportedModulesForHF |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 214557,
"end": 214878
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("score", "vector_string")
score = sgqlc.types.Field(sgqlc.types.non_null(Float), graphql_name="score")
vector_string = sgqlc.types.Field(String, graphql_name="vectorString")
... | CVSS |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config.py | {
"start": 62077,
"end": 62810
} | class ____(_ConfigBase):
multi_vector: Optional[_MultiVectorConfig]
quantizer: Optional[Union[PQConfig, BQConfig, SQConfig, RQConfig]]
def to_dict(self) -> Dict[str, Any]:
out = super().to_dict()
if isinstance(self.quantizer, _PQConfig):
out["pq"] = {**out.pop("quantizer"), "ena... | _VectorIndexConfig |
python | altair-viz__altair | altair/expr/core.py | {
"start": 7463,
"end": 7694
} | class ____(Expression):
def __init__(self, op, lhs, rhs) -> None:
super().__init__(op=op, lhs=lhs, rhs=rhs)
def __repr__(self):
return f"({_js_repr(self.lhs)} {self.op} {_js_repr(self.rhs)})"
| BinaryExpression |
python | pypa__warehouse | warehouse/manage/forms.py | {
"start": 1832,
"end": 3567
} | class ____(
RoleNameMixin,
TeamProjectRoleNameMixin,
wtforms.Form,
):
is_team = wtforms.RadioField(
"Team or member?",
choices=[("true", "Team"), ("false", "Member")],
coerce=lambda string: True if string == "true" else False,
default="true",
validators=[wtforms.v... | CreateInternalRoleForm |
python | getsentry__sentry | tests/sentry/conduit/test_tasks.py | {
"start": 2108,
"end": 2759
} | class ____(TestCase):
@freeze_time("2025-01-01T12:00:00Z")
def test_get_timestamp_uses_current_time(self):
"""Test that get_timestamp generates a valid timestamp."""
timestamp = get_timestamp()
dt = timestamp.ToDatetime()
expected = datetime.datetime(2025, 1, 1, 12, 0, 0)
... | GetTimestampTest |
python | mlflow__mlflow | mlflow/types/utils.py | {
"start": 851,
"end": 3543
} | class ____(MlflowException):
def __init__(self, msg):
super().__init__(f"Multidimensional arrays (aka tensors) are not supported. {msg}")
def _get_tensor_shape(data, variable_dimension: int | None = 0) -> tuple[int, ...]:
"""Infer the shape of the inputted data.
This method creates the shape of t... | TensorsNotSupportedException |
python | numba__numba | numba/core/errors.py | {
"start": 17733,
"end": 17845
} | class ____(UnsupportedError):
"""UnsupportedError from rewrite passes
"""
pass
| UnsupportedRewriteError |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI013.py | {
"start": 288,
"end": 346
} | class ____(Exception):
...
value: int
| NonEmptyChild2 |
python | scikit-learn__scikit-learn | sklearn/calibration.py | {
"start": 37869,
"end": 39182
} | class ____(RegressorMixin, BaseEstimator):
"""Sigmoid regression model.
Attributes
----------
a_ : float
The slope.
b_ : float
The intercept.
"""
def fit(self, X, y, sample_weight=None):
"""Fit the model using X, y as training data.
Parameters
----... | _SigmoidCalibration |
python | walkccc__LeetCode | solutions/3391. Design a 3D Binary Matrix with Efficient Layer Tracking/3391.py | {
"start": 0,
"end": 844
} | class ____:
def __init__(self, n: int):
self.isSet = set()
# count[x] := the number of set cells in the x-th layer
self.count = collections.Counter()
# (count[x], x)
self.pairs: SortedList = SortedList(key=lambda x: (-x[0], -x[1]))
self.pairs.update((0, x) for x in range(n))
def setCell(sel... | Matrix3D |
python | cython__cython | Cython/Compiler/Symtab.py | {
"start": 103681,
"end": 105611
} | class ____(ClassScope):
# Namespace of a Python class.
#
# class_obj_cname string C variable holding class object
is_py_class_scope = 1
namespace_cname_is_type = False
def declare_var(self, name, type, pos,
cname=None, visibility='private',
api=F... | PyClassScope |
python | keras-team__keras | guides/training_with_built_in_methods.py | {
"start": 12066,
"end": 13200
} | class ____(layers.Layer):
def call(self, inputs):
self.add_loss(ops.sum(inputs) * 0.1)
return inputs # Pass-through layer.
inputs = keras.Input(shape=(784,), name="digits")
x = layers.Dense(64, activation="relu", name="dense_1")(inputs)
# Insert activity regularization as a layer
x = ActivityReg... | ActivityRegularizationLayer |
python | redis__redis-py | redis/maint_notifications.py | {
"start": 5794,
"end": 7448
} | class ____(MaintenanceNotification):
"""
Notification for when a Redis cluster node is in the process of migrating slots.
This notification is received when a node starts migrating its slots to another node
during cluster rebalancing or maintenance operations.
Args:
id (int): Unique identi... | NodeMigratingNotification |
python | pexpect__pexpect | tests/test_pxssh.py | {
"start": 194,
"end": 882
} | class ____(PexpectTestCase):
def setUp(self):
super(SSHTestBase, self).setUp()
self.tempdir = tempfile.mkdtemp()
self.orig_path = os.environ.get('PATH')
os.symlink(self.PYTHONBIN, os.path.join(self.tempdir, 'python'))
fakessh_dir = os.path.abspath(os.path.join(os.path.dirname... | SSHTestBase |
python | django-compressor__django-compressor | compressor/parser/html5lib.py | {
"start": 242,
"end": 1850
} | class ____(ParserBase):
def __init__(self, content):
super().__init__(content)
import html5lib
self.html5lib = html5lib
def _serialize(self, elem):
return self.html5lib.serialize(
elem,
tree="etree",
quote_attr_values="always",
om... | Html5LibParser |
python | django__django | tests/select_related_regress/models.py | {
"start": 970,
"end": 1065
} | class ____(models.Model):
user = models.ForeignKey(TUser, models.CASCADE, unique=True)
| Person |
python | langchain-ai__langchain | libs/core/langchain_core/output_parsers/openai_functions.py | {
"start": 618,
"end": 1857
} | class ____(BaseGenerationOutputParser[Any]):
"""Parse an output that is one of sets of values."""
args_only: bool = True
"""Whether to only return the arguments to the function call."""
@override
def parse_result(self, result: list[Generation], *, partial: bool = False) -> Any:
"""Parse th... | OutputFunctionsParser |
python | faif__python-patterns | patterns/behavioral/specification.py | {
"start": 1431,
"end": 1837
} | class ____(CompositeSpecification):
def __init__(self, one: "Specification", other: "Specification") -> None:
self._one: Specification = one
self._other: Specification = other
def is_satisfied_by(self, candidate: Union["User", str]):
return bool(
self._one.is_satisfied_by(ca... | OrSpecification |
python | apache__airflow | providers/google/tests/unit/google/cloud/sensors/test_gcs.py | {
"start": 20462,
"end": 22041
} | class ____:
OPERATOR = GCSUploadSessionCompleteSensor(
task_id="gcs-obj-session",
bucket=TEST_BUCKET,
google_cloud_conn_id=TEST_GCP_CONN_ID,
prefix=TEST_OBJECT,
inactivity_period=TEST_INACTIVITY_PERIOD,
min_objects=TEST_MIN_OBJECTS,
deferrable=True,
)
... | TestGCSUploadSessionCompleteAsyncSensor |
python | tiangolo__fastapi | fastapi/security/base.py | {
"start": 71,
"end": 141
} | class ____:
model: SecurityBaseModel
scheme_name: str
| SecurityBase |
python | pytorch__pytorch | test/nn/test_module_hooks.py | {
"start": 4615,
"end": 19335
} | class ____(TestCase):
@parametrize_test("named_tuple", (True, False))
def test_forward_hooks(self, named_tuple):
fired_hooks: list[int] = []
model = ToyModel(named_tuple)
x = torch.randn(10, 10)
hook = partial(forward_hook, self, fired_hooks, model.net1.seq2)
model.net1.s... | TestModuleHooks |
python | spyder-ide__spyder | external-deps/python-lsp-server/pylsp/workspace.py | {
"start": 821,
"end": 12398
} | class ____:
M_PUBLISH_DIAGNOSTICS = "textDocument/publishDiagnostics"
M_PROGRESS = "$/progress"
M_INITIALIZE_PROGRESS = "window/workDoneProgress/create"
M_APPLY_EDIT = "workspace/applyEdit"
M_SHOW_MESSAGE = "window/showMessage"
M_LOG_MESSAGE = "window/logMessage"
def __init__(self, root_uri... | Workspace |
python | donnemartin__interactive-coding-challenges | linked_lists/find_loop_start/test_find_loop_start.py | {
"start": 18,
"end": 1440
} | class ____(unittest.TestCase):
def test_find_loop_start(self):
print('Test: Empty list')
linked_list = MyLinkedList()
self.assertEqual(linked_list.find_loop_start(), None)
print('Test: Not a circular linked list: One element')
head = Node(1)
linked_list = MyLinkedLi... | TestFindLoopStart |
python | anthropics__anthropic-sdk-python | src/anthropic/types/beta/beta_document_block.py | {
"start": 577,
"end": 834
} | class ____(BaseModel):
citations: Optional[BetaCitationConfig] = None
"""Citation configuration for the document"""
source: Source
title: Optional[str] = None
"""The title of the document"""
type: Literal["document"]
| BetaDocumentBlock |
python | encode__django-rest-framework | tests/test_versioning.py | {
"start": 1387,
"end": 1673
} | class ____(RequestVersionView):
def determine_version(self, request, *args, **kwargs):
scheme = self.versioning_class()
scheme.allowed_versions = ('v1', 'v2', None)
return (scheme.determine_version(request, *args, **kwargs), scheme)
| AllowedWithNoneVersionsView |
python | django__django | tests/aggregation_regress/tests.py | {
"start": 70015,
"end": 71422
} | class ____(TestCase):
def test_ticket_21150(self):
b = Bravo.objects.create()
c = Charlie.objects.create(bravo=b)
qs = Charlie.objects.select_related("alfa").annotate(Count("bravo__charlie"))
self.assertSequenceEqual(qs, [c])
self.assertIs(qs[0].alfa, None)
a = Alfa.o... | JoinPromotionTests |
python | kamyu104__LeetCode-Solutions | Python/rearrange-spaces-between-words.py | {
"start": 48,
"end": 1500
} | class ____(object):
def reorderSpaces(self, text):
"""
:type text: str
:rtype: str
"""
text = list(text)
# count the spaces and words
space_count, word_count = 0, 0
for i, c in enumerate(text):
if c == ' ':
space_count += 1
... | Solution |
python | mahmoud__boltons | tests/test_ioutils.py | {
"start": 17654,
"end": 19502
} | class ____(TestCase):
def test_read_seek_bytes(self):
r = ioutils.MultiFileReader(io.BytesIO(b'narf'), io.BytesIO(b'troz'))
self.assertEqual([b'nar', b'ftr', b'oz'],
list(iter(lambda: r.read(3), b'')))
r.seek(0)
self.assertEqual(b'narftroz', r.read())
de... | TestMultiFileReader |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 162882,
"end": 163116
} | class ____(SendrecvmsgDgramFlagsBase,
SendrecvmsgConnectionlessBase,
ThreadedSocketTestMixin, UDPTestBase):
pass
@requireAttrs(socket.socket, "sendmsg")
| SendrecvmsgUDPTestBase |
python | scipy__scipy | scipy/cluster/tests/test_hierarchy.py | {
"start": 27905,
"end": 30028
} | class ____:
def test_correspond_empty(self, xp):
# Tests correspond(Z, y) with empty linkage and condensed distance matrix.
y = xp.zeros((0,), dtype=xp.float64)
Z = xp.zeros((0,4), dtype=xp.float64)
assert_raises(ValueError, correspond, Z, y)
def test_correspond_2_and_up(self, ... | TestCorrespond |
python | pytorch__pytorch | benchmarks/inductor_backends/cutlass.py | {
"start": 2921,
"end": 3409
} | class ____(ExperimentConfig):
enable_persistent_tma_matmul: bool = False
def name(self) -> str:
if self.enable_persistent_tma_matmul:
return "triton_persistent_tma"
else:
return "triton"
def to_options(self) -> dict[str, Any]:
return {
**super().... | TritonExperimentConfig |
python | django-extensions__django-extensions | django_extensions/management/commands/sqldiff.py | {
"start": 65626,
"end": 71086
} | class ____(BaseCommand):
help = """Prints the (approximated) difference between models and fields in the database for the given app name(s).
It indicates how columns in the database are different from the sql that would
be generated by Django. This command is not a database migration tool. (Though
it can certainly... | Command |
python | pydata__xarray | xarray/tests/test_datatree.py | {
"start": 65573,
"end": 69790
} | class ____:
def test_isomorphic(self):
tree = DataTree.from_dict({"/a": None, "/a/b": None, "/c": None})
diff_data = DataTree.from_dict(
{"/a": None, "/a/b": None, "/c": xr.Dataset({"foo": 1})}
)
assert tree.isomorphic(diff_data)
diff_order = DataTree.from_dict(... | TestIsomorphicEqualsAndIdentical |
python | ray-project__ray | python/ray/_private/worker.py | {
"start": 6287,
"end": 7008
} | class ____(HasOptions, Generic[R, T0, T1, T2, T3, T4]):
def __init__(self, function: Callable[[T0, T1, T2, T3, T4], R]) -> None:
pass
def remote(
self,
__arg0: "Union[T0, ObjectRef[T0]]",
__arg1: "Union[T1, ObjectRef[T1]]",
__arg2: "Union[T2, ObjectRef[T2]]",
__a... | RemoteFunction4 |
python | cherrypy__cherrypy | cherrypy/_cpreqbody.py | {
"start": 21733,
"end": 27650
} | class ____(Entity):
"""A MIME part entity, part of a multipart entity."""
# "The default character set, which must be assumed in the absence of a
# charset parameter, is US-ASCII."
attempt_charsets = ['us-ascii', 'utf-8']
r"""A list of strings, each of which should be a known encoding.
When th... | Part |
python | pennersr__django-allauth | allauth/socialaccount/providers/tiktok/scope.py | {
"start": 24,
"end": 133
} | class ____(Enum):
user_info_basic = "user.info.basic"
user_info_profile = "user.info.profile"
| TikTokScope |
python | sanic-org__sanic | sanic/exceptions.py | {
"start": 4095,
"end": 5130
} | class ____(HTTPException):
"""A base class for other exceptions and should not be called directly.
Args:
message (Optional[Union[str, bytes]], optional): The message to be sent to the client. If `None`,
then the appropriate HTTP response status message will be used instead. Defaults to `Non... | NotFound |
python | huggingface__transformers | src/transformers/models/flava/modeling_flava.py | {
"start": 43840,
"end": 56419
} | class ____(FlavaPreTrainedModel):
config: FlavaConfig
def __init__(self, config: FlavaConfig):
super().__init__(config)
if not isinstance(config.text_config, FlavaTextConfig):
raise TypeError(
"config.text_config is expected to be of type FlavaTextConfig but is of t... | FlavaModel |
python | run-llama__llama_index | llama-index-integrations/program/llama-index-program-evaporate/llama_index/program/evaporate/df.py | {
"start": 1498,
"end": 2182
} | class ____(BaseModel):
"""Data-frame with rows. Assume column names are already known beforehand."""
rows: List[DataFrameRow] = Field(..., description="""List of row objects.""")
def to_df(self, existing_df: Optional[pd.DataFrame] = None) -> pd.DataFrame:
"""To dataframe."""
if existing_df... | DataFrameRowsOnly |
python | getsentry__sentry | src/sentry/backup/comparators.py | {
"start": 21713,
"end": 23234
} | class ____(JSONScrubbingComparator, ABC):
"""Comparator that ensures that both sides match a certain regex."""
def __init__(self, regex: re.Pattern, *fields: str):
self.regex = regex
super().__init__(*fields)
def compare(self, on: InstanceID, left: Any, right: Any) -> list[ComparatorFindin... | RegexComparator |
python | getsentry__sentry-python | sentry_sdk/_log_batcher.py | {
"start": 321,
"end": 6018
} | class ____:
MAX_LOGS_BEFORE_FLUSH = 100
MAX_LOGS_BEFORE_DROP = 1_000
FLUSH_WAIT_TIME = 5.0
def __init__(
self,
capture_func, # type: Callable[[Envelope], None]
record_lost_func, # type: Callable[..., None]
):
# type: (...) -> None
self._log_buffer = [] # t... | LogBatcher |
python | django__django | tests/extra_regress/tests.py | {
"start": 154,
"end": 16177
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.u = User.objects.create_user(
username="fred", password="secret", email="fred@example.com"
)
def test_regression_7314_7372(self):
"""
Regression tests for #7314 and #7372
"""
rm = Revi... | ExtraRegressTests |
python | getsentry__sentry | src/sentry/auth/access.py | {
"start": 26786,
"end": 28729
} | class ____(Access):
auth_state: RpcAuthState
@cached_property
def permissions(self) -> frozenset[str]:
return frozenset(self.auth_state.permissions)
def has_team_access(self, team: Team) -> bool:
return False
def has_project_access(self, project: Project) -> bool:
return F... | OrganizationlessAccess |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/ruff/RUF009_attrs_auto_attribs.py | {
"start": 1208,
"end": 1318
} | class ____:
a: str = 0
b = field()
c: int = foo()
d = list()
@attr.s() # auto_attribs = False
| C |
python | pytorch__pytorch | test/ao/sparsity/test_sparsifier.py | {
"start": 481,
"end": 9461
} | class ____(TestCase):
def test_constructor(self):
# Cannot instantiate the abstract base
self.assertRaises(TypeError, BaseSparsifier)
# Can instantiate the model with no configs
model = SimpleLinear()
sparsifier = ImplementedSparsifier(test=3)
sparsifier.prepare(model... | TestBaseSparsifier |
python | psf__black | tests/data/cases/dummy_implementations.py | {
"start": 3036,
"end": 3128
} | class ____:
def f(self): # Comment 1
... # Comment 2
# Comment 3
| ClassD |
python | matplotlib__matplotlib | lib/matplotlib/widgets.py | {
"start": 65105,
"end": 68077
} | class ____(Widget):
"""
A tool to adjust the subplot params of a `.Figure`.
"""
def __init__(self, targetfig, toolfig):
"""
Parameters
----------
targetfig : `~matplotlib.figure.Figure`
The figure instance to adjust.
toolfig : `~matplotlib.figure.Figu... | SubplotTool |
python | numba__numba | numba/core/typeconv/castgraph.py | {
"start": 956,
"end": 1828
} | class ____(object):
"""A set of casting rules.
There is at most one rule per target type.
"""
def __init__(self):
self._rels = {}
def insert(self, to, rel):
old = self.get(to)
setrel = min(rel, old)
self._rels[to] = setrel
return old != setrel
def item... | CastSet |
python | django-compressor__django-compressor | compressor/filters/css_default.py | {
"start": 608,
"end": 4502
} | class ____(FilterBase):
run_with_compression_disabled = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.root = settings.COMPRESS_ROOT
self.url = settings.COMPRESS_URL.rstrip("/")
self.url_path = self.url
self.has_scheme = False
def ... | CssAbsoluteFilter |
python | weaviate__weaviate-python-client | weaviate/collections/classes/config_vector_index.py | {
"start": 6113,
"end": 6286
} | class ____(_ConfigCreateModel):
type_: Optional[PQEncoderType] = Field(serialization_alias="type")
distribution: Optional[PQEncoderDistribution]
| _PQEncoderConfigCreate |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1385515,
"end": 1386296
} | class ____(sgqlc.types.Type, Node):
"""A Git push."""
__schema__ = github_schema
__field_names__ = ("next_sha", "permalink", "previous_sha", "pusher", "repository")
next_sha = sgqlc.types.Field(GitObjectID, graphql_name="nextSha")
"""The SHA after the push"""
permalink = sgqlc.types.Field(sgql... | Push |
python | huggingface__transformers | tests/models/lfm2_vl/test_processing_lfm2_vl.py | {
"start": 1013,
"end": 21562
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = Lfm2VlProcessor
@classmethod
def _setup_image_processor(cls):
image_processor_class = cls._get_component_class_from_processor("image_processor")
return image_processor_class(
tile_size=14,
min_ima... | Lfm2VlProcessorTest |
python | numba__numba | numba/core/typeinfer.py | {
"start": 16214,
"end": 16868
} | class ____(object):
def __init__(self, target, pair, loc):
self.target = target
self.pair = pair
self.loc = loc
def __call__(self, typeinfer):
with new_error_context("typing of pair-second at {loc}",
loc=self.loc):
typevars = typeinfer.... | PairSecondConstraint |
python | PrefectHQ__prefect | src/prefect/events/schemas/automations.py | {
"start": 7662,
"end": 7755
} | class ____(Enum):
LT = "<"
LTE = "<="
GT = ">"
GTE = ">="
| MetricTriggerOperator |
python | numpy__numpy | numpy/typing/tests/test_runtime.py | {
"start": 2746,
"end": 3076
} | class ____:
def test_isinstance(self, cls: type[Any], obj: object) -> None:
assert isinstance(obj, cls)
assert not isinstance(None, cls)
def test_issubclass(self, cls: type[Any], obj: object) -> None:
assert issubclass(type(obj), cls)
assert not issubclass(type(None), cls)
| TestRuntimeProtocol |
python | gevent__gevent | src/gevent/tests/test__example_udp_server.py | {
"start": 81,
"end": 513
} | class ____(util.TestServer):
example = 'udp_server.py'
def _run_all_tests(self):
sock = socket.socket(type=socket.SOCK_DGRAM)
try:
sock.connect(('127.0.0.1', 9000))
sock.send(b'Test udp_server')
data, _address = sock.recvfrom(8192)
self.assertEqua... | Test |
python | PrefectHQ__prefect | tests/blocks/test_core.py | {
"start": 87804,
"end": 87851
} | class ____(BaseBlock):
a: int = 1
| AChildBlock |
python | walkccc__LeetCode | solutions/853. Car Fleet/853.py | {
"start": 0,
"end": 508
} | class ____:
def carFleet(self, target: int, position: list[int], speed: list[int]) -> int:
ans = 0
times = [
float(target - p) / s for p, s in sorted(zip(position, speed),
reverse=True)]
maxTime = 0 # the time of the slowest car to reach the target... | Solution |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_django/DJ008.py | {
"start": 3286,
"end": 3362
} | class ____(TestModel4):
pass
# Subclass without __str__
| SubclassTestModel2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.