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/model_fields/test_integerfield.py | {
"start": 10375,
"end": 13108
} | class ____(SimpleTestCase):
class Choices(models.IntegerChoices):
A = 1
def test_integerfield_cleans_valid_string(self):
f = models.IntegerField()
self.assertEqual(f.clean("2", None), 2)
def test_integerfield_raises_error_on_invalid_intput(self):
f = models.IntegerField()
... | ValidationTests |
python | keras-team__keras | keras/src/trainers/data_adapters/tf_dataset_adapter_test.py | {
"start": 297,
"end": 13691
} | class ____(testing.TestCase):
def test_basic_flow(self):
x = tf.random.normal((34, 4))
y = tf.random.normal((34, 2))
base_ds = tf.data.Dataset.from_tensor_slices((x, y)).batch(16)
adapter = tf_dataset_adapter.TFDatasetAdapter(base_ds)
self.assertEqual(adapter.num_batches, 3)... | TestTFDatasetAdapter |
python | huggingface__transformers | src/transformers/models/mobilenet_v1/image_processing_mobilenet_v1.py | {
"start": 1428,
"end": 15150
} | class ____(BaseImageProcessor):
r"""
Constructs a MobileNetV1 image processor.
Args:
do_resize (`bool`, *optional*, defaults to `True`):
Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
`do_resize` in the `preprocess` met... | MobileNetV1ImageProcessor |
python | django__django | tests/migrations/models.py | {
"start": 126,
"end": 205
} | class ____(models.Model, metaclass=CustomModelBase):
pass
| ModelWithCustomBase |
python | scipy__scipy | scipy/special/tests/test_kolmogorov.py | {
"start": 15773,
"end": 18502
} | class ____:
def test_nan(self):
assert_(np.isnan(kolmogi(np.nan)))
def test_basic(self):
dataset = [(1.0, 0),
(0.96394524366487511, 0.5),
(0.9, 0.571173265106),
(0.5000000000000000, 0.8275735551899077),
(0.2699996716773... | TestKolmogi |
python | pytorch__pytorch | torch/fx/passes/graph_transform_observer.py | {
"start": 448,
"end": 7785
} | class ____:
__pass_count = 0
def __init__(
self,
gm: GraphModule,
passname: str,
subsystem: Optional[str] = None,
log_url: Optional[str] = None,
):
"""
log_url is inferred to be torch._inductor.config.trace.log_url_for_graph_xform unless otherwise spe... | GraphTransformObserver |
python | plotly__plotly.py | plotly/graph_objs/isosurface/colorbar/title/_font.py | {
"start": 233,
"end": 9929
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "isosurface.colorbar.title"
_path_str = "isosurface.colorbar.title.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weig... | Font |
python | astropy__astropy | astropy/modeling/tests/test_mappings.py | {
"start": 3980,
"end": 5905
} | class ____:
def test___init__(self):
# Set values
model = UnitsMapping(
((u.m, None),),
input_units_equivalencies="test_eqiv",
input_units_allow_dimensionless=True,
name="test",
)
assert model._mapping == ((u.m, None),)
assert m... | TestUnitsMapping |
python | prompt-toolkit__python-prompt-toolkit | src/prompt_toolkit/buffer.py | {
"start": 1349,
"end": 1523
} | class ____(Enum):
"The validation state of a buffer. This is set after the validation."
VALID = "VALID"
INVALID = "INVALID"
UNKNOWN = "UNKNOWN"
| ValidationState |
python | Farama-Foundation__Gymnasium | gymnasium/envs/toy_text/cliffwalking.py | {
"start": 406,
"end": 13343
} | class ____(Env):
"""
Cliff walking involves crossing a gridworld from start to goal while avoiding falling off a cliff.
## Description
The game starts with the player at location [3, 0] of the 4x12 grid world with the
goal located at [3, 11]. If the player reaches the goal the episode ends.
A ... | CliffWalkingEnv |
python | pytorch__pytorch | torch/distributed/checkpoint/staging.py | {
"start": 13956,
"end": 19299
} | class ____(AsyncStager):
"""
An AsyncStager implementation that replicates state_dict across training ranks
using PGTransport.
Args:
pg: ProcessGroup for distributed communication
timeout: Timeout for communication operations
device: Device to use for tensor operations
s... | _ReplicationStager |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/compiler.py | {
"start": 28970,
"end": 29771
} | class ____(util.EnsureKWArg):
"""Produces DDL specification for TypeEngine objects."""
ensure_kwarg = r"visit_\w+"
def __init__(self, dialect: Dialect):
self.dialect = dialect
def process(self, type_: TypeEngine[Any], **kw: Any) -> str:
if (
type_._variant_mapping
... | TypeCompiler |
python | django__django | tests/test_runner/tests.py | {
"start": 18825,
"end": 20297
} | class ____(AdminScriptTestCase):
"""
Custom runners can add command line arguments. The runner is specified
through a settings file.
"""
def setUp(self):
super().setUp()
settings = {
"TEST_RUNNER": "'test_runner.runner.CustomOptionsTestRunner'",
}
self.wr... | CustomTestRunnerOptionsSettingsTests |
python | PrefectHQ__prefect | src/prefect/server/schemas/internal.py | {
"start": 234,
"end": 356
} | class ____(actions.WorkPoolUpdate):
status: Optional[statuses.WorkPoolStatus] = Field(default=None)
| InternalWorkPoolUpdate |
python | doocs__leetcode | solution/2300-2399/2373.Largest Local Values in a Matrix/Solution.py | {
"start": 0,
"end": 377
} | class ____:
def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:
n = len(grid)
ans = [[0] * (n - 2) for _ in range(n - 2)]
for i in range(n - 2):
for j in range(n - 2):
ans[i][j] = max(
grid[x][y] for x in range(i, i + 3) for y in ... | Solution |
python | huggingface__transformers | src/transformers/models/depth_anything/modeling_depth_anything.py | {
"start": 3755,
"end": 4936
} | class ____(nn.Module):
"""
ResidualConvUnit, pre-activate residual unit.
Args:
config (`[DepthAnythingConfig]`):
Model configuration class defining the model architecture.
"""
def __init__(self, config):
super().__init__()
self.activation1 = nn.ReLU()
s... | DepthAnythingPreActResidualLayer |
python | getsentry__sentry | src/sentry/seer/similarity/utils.py | {
"start": 2214,
"end": 3338
} | class ____:
"""
Lazy-loaded singleton for the tokenizer to avoid expensive initialization at module load time.
"""
def __init__(self) -> None:
self._tokenizer: Tokenizer | None = None
self._lock = threading.RLock()
def get_tokenizer(self) -> Tokenizer:
"""Get the tokenizer ... | TokenizerWrapper |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType27.py | {
"start": 157,
"end": 356
} | class ____: ...
T = TypeVar("T", bound=ClassA)
def func1(cls: type[T]) -> list[type[T]]:
result = [cls]
for c in cls.__subclasses__():
result.extend(func1(c))
return result
| ClassA |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/todo.py | {
"start": 905,
"end": 6320
} | class ____(AgentState):
"""State schema for the todo middleware."""
todos: Annotated[NotRequired[list[Todo]], OmitFromInput]
"""List of todo items for tracking task progress."""
WRITE_TODOS_TOOL_DESCRIPTION = """Use this tool to create and manage a structured task list for your current work session. This... | PlanningState |
python | pandas-dev__pandas | pandas/tests/frame/indexing/test_getitem.py | {
"start": 14437,
"end": 14844
} | class ____:
@pytest.mark.parametrize("key", [{"a", "b"}, {"a": "a"}])
def test_getitem_dict_and_set_deprecated(self, key):
# GH#42825 enforced in 2.0
df = DataFrame(
[[1, 2], [3, 4]], columns=MultiIndex.from_tuples([("a", 1), ("b", 2)])
)
with pytest.raises(TypeError,... | TestGetitemDeprecatedIndexers |
python | python-pillow__Pillow | src/PIL/Image.py | {
"start": 4012,
"end": 4186
} | class ____(IntEnum):
NONE = 0
ORDERED = 1 # Not yet implemented
RASTERIZE = 2 # Not yet implemented
FLOYDSTEINBERG = 3 # default
# palettes/quantizers
| Dither |
python | keras-team__keras | keras/src/wrappers/sklearn_wrapper.py | {
"start": 6443,
"end": 10743
} | class ____(ClassifierMixin, SKLBase):
"""scikit-learn compatible classifier wrapper for Keras models.
Note that there are sources of randomness in model initialization and
training. Refer to [Reproducibility in Keras Models](
https://keras.io/examples/keras_recipes/reproducibility_recipes/) on how to
... | SKLearnClassifier |
python | huggingface__transformers | src/transformers/models/nemotron/modeling_nemotron.py | {
"start": 43653,
"end": 43961
} | class ____(GenericForTokenClassification, NemotronPreTrainedModel): ...
__all__ = [
"NemotronForQuestionAnswering",
"NemotronForCausalLM",
"NemotronModel",
"NemotronPreTrainedModel",
"NemotronForSequenceClassification",
"NemotronForTokenClassification",
]
| NemotronForTokenClassification |
python | tensorflow__tensorflow | tensorflow/python/framework/convert_to_constants.py | {
"start": 2414,
"end": 2624
} | class ____(collections.namedtuple("_EndPoint", ["convertible", "index"])):
"""An endpoint in a graph."""
__slots__ = ()
def __str__(self):
return "{}[{}]".format(self.convertible, self.index)
| _EndPoint |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_cloud_storage_transfer_service.py | {
"start": 6254,
"end": 9118
} | class ____:
def test_should_do_nothing_on_empty(self):
body = {}
TransferJobPreprocessor(body=body).process_body()
assert body == {}
@pytest.mark.skipif(boto3 is None, reason="Skipping test because boto3 is not available")
@mock.patch("airflow.providers.google.cloud.operators.cloud_... | TestTransferJobPreprocessor |
python | getsentry__sentry | src/sentry/interfaces/exception.py | {
"start": 3238,
"end": 7195
} | class ____(Interface):
"""
an optional field residing in the exception interface. It carries additional
information about the way the exception was created on the target system.
This includes general exception values obtained from operating system or
runtime APIs, as well as mechanism-specific value... | Mechanism |
python | psf__black | src/blib2to3/pytree.py | {
"start": 18335,
"end": 19863
} | class ____(BasePattern):
def __init__(
self,
type: int | None = None,
content: str | None = None,
name: str | None = None,
) -> None:
"""
Initializer. Takes optional type, content, and name.
The type, if given must be a token type (< 256). If not given,... | LeafPattern |
python | nedbat__coveragepy | tests/test_coverage.py | {
"start": 35245,
"end": 38936
} | class ____(CoverageTest):
"""Tests of the exclusion feature to mark lines as not covered."""
def test_default(self) -> None:
# A number of forms of pragma comment are accepted.
self.check_coverage(
"""\
a = 1
b = 2 # pragma: no cover
c = 3
... | ExcludeTest |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/settings.py | {
"start": 4130,
"end": 4487
} | class ____:
demo_path: str
steps: int = 0
strength: float = 1.0
samples_per_update: int = 0
# Setting either of these to None will allow the Optimizer
# to decide these parameters, based on Trainer hyperparams
num_epoch: Optional[int] = None
batch_size: Optional[int] = None
@attr.s(aut... | BehavioralCloningSettings |
python | walkccc__LeetCode | solutions/1957. Delete Characters to Make Fancy String/1957.py | {
"start": 0,
"end": 190
} | class ____:
def makeFancyString(self, s: str) -> str:
ans = []
for c in s:
if len(ans) < 2 or ans[-1] != c or ans[-2] != c:
ans.append(c)
return ''.join(ans)
| Solution |
python | Pylons__pyramid | tests/test_renderers.py | {
"start": 114,
"end": 3387
} | class ____(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
testing.tearDown()
def _makeOne(self, **kw):
from pyramid.renderers import JSON
return JSON(**kw)
def test_it(self):
renderer = self._makeOne()(None)
resu... | TestJSON |
python | realpython__materials | python-with-statement/site_checker_v2.py | {
"start": 33,
"end": 732
} | class ____:
def __init__(self, url):
self._url = url
async def __aenter__(self):
self.session = aiohttp.ClientSession()
response = await self.session.get(self._url)
return response
async def __aexit__(self, *_):
await self.session.close()
async def main():
awa... | AsyncSession |
python | google__jax | jax/experimental/jax2tf/examples/tf_js/quickdraw/quickdraw.py | {
"start": 1436,
"end": 4894
} | class ____(nn.Module):
@nn.compact
def __call__(self, x):
x = nn.Conv(features=16, kernel_size=(3, 3), padding='SAME')(x)
x = nn.relu(x)
x = nn.max_pool(x, window_shape=(2, 2), strides=(2, 2))
x = nn.Conv(features=32, kernel_size=(3, 3), padding='SAME')(x)
x = nn.relu(x)
x = nn.max_pool(x, ... | QuickDraw |
python | viewflow__viewflow | viewflow/workflow/migrations/0010_viewflow20.py | {
"start": 155,
"end": 2683
} | class ____(migrations.Migration):
dependencies = [
("viewflow", "0009_merge"),
]
operations = [
migrations.RemoveField(
model_name="task",
name="comments",
),
migrations.AddField(
model_name="process",
name="parent_task",
... | Migration |
python | pypa__warehouse | tests/unit/ip_addresses/test_models.py | {
"start": 273,
"end": 1667
} | class ____:
def test_repr(self, db_request):
ip_address = db_request.ip_address
assert isinstance(repr(ip_address), str)
assert repr(ip_address) == REMOTE_ADDR
def test_invalid_transformed(self, db_request):
ip_address = DBIpAddressFactory(ip_address="wutang")
assert rep... | TestIpAddress |
python | walkccc__LeetCode | solutions/2151. Maximum Good People Based on Statements/2151.py | {
"start": 0,
"end": 838
} | class ____:
def maximumGood(self, statements: list[list[int]]) -> int:
n = len(statements)
ans = 0
def isValid(good: list[int]) -> bool:
for i, g in enumerate(good):
if not g: # The i-th person is bad, so no need to check.
continue
for j in range(n):
if statemen... | Solution |
python | django-extensions__django-extensions | django_extensions/management/commands/update_permissions.py | {
"start": 411,
"end": 2953
} | class ____(BaseCommand):
help = (
"reloads permissions for specified apps, or all apps if no args are specified"
)
def add_arguments(self, parser):
super().add_arguments(parser)
parser.add_argument(
"--apps",
dest="apps",
help="Reload permissions ... | Command |
python | pennersr__django-allauth | allauth/socialaccount/providers/openstreetmap/provider.py | {
"start": 239,
"end": 841
} | class ____(ProviderAccount):
def get_profile_url(self):
return (
"https://www.openstreetmap.org/user/"
+ self.account.extra_data["display_name"]
)
def get_avatar_url(self):
ret = None
if img := self.account.extra_data.get("img"):
ret = img.get... | OpenStreetMapAccount |
python | sqlalchemy__sqlalchemy | test/orm/test_core_compilation.py | {
"start": 44762,
"end": 61744
} | class ____(QueryTest, AssertsCompiledSQL):
__dialect__ = "default"
run_setup_mappers = None
@testing.fixture
def query_expression_fixture(self):
users, User = (
self.tables.users,
self.classes.User,
)
addresses, Address = (self.tables.addresses, self.cla... | ExtraColsTest |
python | doocs__leetcode | solution/0100-0199/0149.Max Points on a Line/Solution2.py | {
"start": 0,
"end": 549
} | class ____:
def maxPoints(self, points: List[List[int]]) -> int:
def gcd(a, b):
return a if b == 0 else gcd(b, a % b)
n = len(points)
ans = 1
for i in range(n):
x1, y1 = points[i]
cnt = Counter()
for j in range(i + 1, n):
... | Solution |
python | jazzband__django-oauth-toolkit | tests/test_scopes.py | {
"start": 2397,
"end": 4786
} | class ____(BaseTest):
def test_scopes_saved_in_grant(self):
"""
Test scopes are properly saved in grant
"""
self.oauth2_settings.PKCE_REQUIRED = False
self.client.login(username="test_user", password="123456")
# retrieve a valid authorization code
authcode_da... | TestScopesSave |
python | scipy__scipy | scipy/special/tests/test_basic.py | {
"start": 142455,
"end": 165832
} | class ____:
def test_itj0y0(self):
it0 = array(special.itj0y0(.2))
assert_allclose(it0, array([0.19933433254006822, -0.34570883800412566]),
atol=1.5e-8, rtol=0)
def test_it2j0y0(self):
it2 = array(special.it2j0y0(.2))
assert_allclose(it2, array([0.0049937... | TestBessel |
python | joerick__pyinstrument | pyinstrument/renderers/jsonrenderer.py | {
"start": 553,
"end": 3336
} | class ____(FrameRenderer):
"""
Outputs a tree of JSON, containing processed frames.
"""
output_file_extension = "json"
def __init__(self, **kwargs: Any):
super().__init__(**kwargs)
def render_frame(self, frame: Frame | None):
if frame is None:
return "null"
... | JSONRenderer |
python | pytest-dev__pytest | testing/test_pytester.py | {
"start": 11957,
"end": 28047
} | class ____:
other_path = {"path": "meta_path", "meta_path": "path"}
@staticmethod
def path(n: int) -> str:
return "my-dirty-little-secret-" + str(n)
def test_restore(self, monkeypatch: MonkeyPatch, path_type) -> None:
other_path_type = self.other_path[path_type]
for i in range(... | TestSysPathsSnapshot |
python | getsentry__sentry | src/sentry/api/endpoints/project_artifact_bundle_files.py | {
"start": 813,
"end": 1175
} | class ____:
def __init__(self, file_path: str, info: dict[str, str]):
self.file_path = file_path
self.info = info
def __eq__(self, other):
return self.file_path == other.file_path
def __hash__(self):
return hash(self.file_path)
def __lt__(self, other):
return s... | ArtifactFile |
python | euske__pdfminer | pdfminer/layout.py | {
"start": 8473,
"end": 9015
} | class ____(LTTextContainer):
def __init__(self, word_margin):
LTTextContainer.__init__(self)
self.word_margin = word_margin
return
def __repr__(self):
return ('<%s %s %r>' %
(self.__class__.__name__, bbox2str(self.bbox),
self.get_text()))
d... | LTTextLine |
python | PyCQA__pylint | tests/functional/n/non/non_iterator_returned.py | {
"start": 337,
"end": 627
} | class ____:
""" __iter__ and next """
def __iter__(self):
return self
def __next__(self):
""" Infinite iterator, but still an iterator """
return 1
def next(self):
"""Same as __next__, but for Python 2."""
return 1
| SecondGoodIterator |
python | tensorflow__tensorflow | tensorflow/security/fuzzing/python_fuzzing.py | {
"start": 1434,
"end": 7142
} | class ____(object):
"""FuzzingHelper makes handling FuzzedDataProvider easier with TensorFlow Python fuzzing."""
def __init__(self, input_bytes):
"""FuzzingHelper initializer.
Args:
input_bytes: Input randomized bytes used to create a FuzzedDataProvider.
"""
self.fdp = atheris.FuzzedDataProv... | FuzzingHelper |
python | Pylons__pyramid | tests/test_testing.py | {
"start": 22716,
"end": 22804
} | class ____:
def __init__(self, kw):
self.__dict__.update(kw)
| DummyRendererInfo |
python | google__pytype | pytype/tests/test_annotations.py | {
"start": 36253,
"end": 37948
} | class ____(test_base.BaseTest):
"""Tests for stringified annotations."""
def test_postponed_evaluation(self):
self.Check("""
from __future__ import annotations
def f() -> int:
return 0
""")
def test_postponed_evaluation_error(self):
self.CheckWithErrors("""
from __future__ ... | TestStringifiedAnnotations |
python | sqlalchemy__sqlalchemy | test/orm/test_unitofwork.py | {
"start": 43278,
"end": 53385
} | class ____(_fixtures.FixtureTest):
run_inserts = None
def test_one_to_many_1(self):
"""Basic save of one to many."""
Address, addresses, users, User = (
self.classes.Address,
self.tables.addresses,
self.tables.users,
self.classes.User,
)
... | OneToManyTest |
python | huggingface__transformers | src/transformers/models/bigbird_pegasus/modeling_bigbird_pegasus.py | {
"start": 60613,
"end": 64144
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: BigBirdPegasusConfig, seed=None):
super().__init__()
self.attention_type = config.attention_type
self.embed_dim = config.d_model
self.self_attn = BigBirdPegasusEncoderAttention(config, seed=seed)
self.self_att... | BigBirdPegasusEncoderLayer |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 142256,
"end": 145893
} | class ____(ASTBase):
def __init__(
self, params: list[ASTTemplateParam], requiresClause: ASTRequiresClause | None
) -> None:
assert params is not None
self.params = params
self.requiresClause = requiresClause
def __eq__(self, other: object) -> bool:
if not isinstance... | ASTTemplateParams |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/setup.py | {
"start": 972,
"end": 2743
} | class ____(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = ['graphql', '-vrsx']
self.test_suite = True
def run_tests(self):
#import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.tes... | PyTest |
python | pennersr__django-allauth | tests/apps/account/test_signup.py | {
"start": 5117,
"end": 16769
} | class ____(TestCase):
def test_signup_same_email_verified_externally(self):
user = self._test_signup_email_verified_externally(
"john@example.com", "john@example.com"
)
self.assertEqual(EmailAddress.objects.filter(user=user).count(), 1)
EmailAddress.objects.get(
... | SignupTests |
python | pytorch__pytorch | torch/distributed/tensor/_op_schema.py | {
"start": 21037,
"end": 22427
} | class ____:
"""
OutputSharding is a data class that is used by the sharding propagation,
it could set the output_spec upon successful propagation. If needs_redistribute
is set to True, a redistribute_schema would be returned together to indicate
the input arguments needs to be redistributed before t... | OutputSharding |
python | numba__numba | numba/tests/test_ctypes.py | {
"start": 1786,
"end": 7431
} | class ____(MemoryLeakMixin, TestCase):
def test_c_sin(self):
pyfunc = use_c_sin
cfunc = njit((types.double,))(pyfunc)
x = 3.14
self.assertEqual(pyfunc(x), cfunc(x))
def test_two_funcs(self):
# Check that two constant functions don't get mixed up.
pyfunc = use_tw... | TestCTypesUseCases |
python | ipython__ipython | tests/test_interactiveshell.py | {
"start": 29721,
"end": 29951
} | class ____(ast.NodeTransformer):
"""Throws an error when it sees a number."""
def visit_Constant(self, node):
if isinstance(node.value, int):
raise ValueError("test")
return node
| ErrorTransformer |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 37251,
"end": 37596
} | class ____(sgqlc.types.Enum):
"""Properties by which mannequins can be ordered.
Enumeration Choices:
* `CREATED_AT`: Order mannequins why when they were created.
* `LOGIN`: Order mannequins alphabetically by their source login.
"""
__schema__ = github_schema
__choices__ = ("CREATED_AT", "... | MannequinOrderField |
python | doocs__leetcode | solution/0500-0599/0598.Range Addition II/Solution.py | {
"start": 0,
"end": 183
} | class ____:
def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:
for a, b in ops:
m = min(m, a)
n = min(n, b)
return m * n
| Solution |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 1035200,
"end": 1035672
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of UpdateProjectCard"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "project_card")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the... | UpdateProjectCardPayload |
python | pydantic__pydantic | tests/mypy/modules/no_strict_optional.py | {
"start": 152,
"end": 335
} | class ____(BaseModel):
model_config = ConfigDict(
validate_assignment=True,
validate_default=True,
extra='forbid',
frozen=True,
)
| CustomBaseModel |
python | walkccc__LeetCode | solutions/1916. Count Ways to Build Rooms in an Ant Colony/1916.py | {
"start": 0,
"end": 505
} | class ____:
def waysToBuildRooms(self, prevRoom: list[int]) -> int:
MOD = 1_000_000_007
graph = collections.defaultdict(list)
for i, prev in enumerate(prevRoom):
graph[prev].append(i)
def dfs(node: int) -> tuple[int, int]:
if not graph[node]:
return 1, 1
ans = 1
l = ... | Solution |
python | scipy__scipy | scipy/interpolate/_fitpack_repro.py | {
"start": 23127,
"end": 31173
} | class ____:
"""
Fit a smooth periodic B-spline curve to given data points.
This class fits a periodic B-spline curve S(t) of degree k through data points
(x, y) with knots t. The spline is smooth and repeats itself at the start and
end, meaning the function and its derivatives up to order k-1 are e... | Fperiodic |
python | scrapy__scrapy | tests/test_engine.py | {
"start": 3070,
"end": 3431
} | class ____(MySpider):
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
spider = cls(*args, **kwargs)
spider._set_crawler(crawler)
crawler.signals.connect(spider.spider_idle, signals.spider_idle)
return spider
def spider_idle(self):
raise CloseSpider(reas... | ChangeCloseReasonSpider |
python | pydata__xarray | xarray/backends/h5netcdf_.py | {
"start": 14857,
"end": 22676
} | class ____(BackendEntrypoint):
"""
Backend for netCDF files based on the h5netcdf package.
It can open ".nc", ".nc4", ".cdf" files but will only be
selected as the default if the "netcdf4" engine is not available.
Additionally it can open valid HDF5 files, see
https://h5netcdf.org/#invalid-net... | H5netcdfBackendEntrypoint |
python | openai__openai-python | tests/lib/chat/test_completions_streaming.py | {
"start": 34595,
"end": 37823
} | class ____(Generic[ResponseFormatT]):
def __init__(self, stream: ChatCompletionStream[ResponseFormatT]) -> None:
self.stream = stream
self.events: list[ChatCompletionStreamEvent[ResponseFormatT]] = []
def __iter__(self) -> Iterator[ChatCompletionStreamEvent[ResponseFormatT]]:
for event ... | StreamListener |
python | huggingface__transformers | src/transformers/models/seggpt/configuration_seggpt.py | {
"start": 783,
"end": 6492
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`SegGptModel`]. It is used to instantiate a SegGPT
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yield a similar configu... | SegGptConfig |
python | allegroai__clearml | clearml/backend_api/services/v2_13/projects.py | {
"start": 83983,
"end": 86198
} | class ____(Response):
"""
Response of projects.get_model_tags endpoint.
:param tags: The list of unique tag values
:type tags: Sequence[str]
:param system_tags: The list of unique system tag values. Returned only if
'include_system' is set to 'true' in the request
:type system_tags: Seq... | GetModelTagsResponse |
python | django-debug-toolbar__django-debug-toolbar | tests/test_utils.py | {
"start": 3916,
"end": 6323
} | class ____(unittest.TestCase):
"""Tests for the sanitize_and_sort_request_vars function."""
def test_dict_sanitization(self):
"""Test sanitization of a regular dictionary."""
test_dict = {
"username": "testuser",
"password": "secret123",
"api_key": "abc123",
... | SanitizeAndSortRequestVarsTestCase |
python | pyca__cryptography | src/cryptography/hazmat/decrepit/ciphers/modes.py | {
"start": 1222,
"end": 1649
} | class ____(ModeWithInitializationVector):
name = "CFB8"
def __init__(self, initialization_vector: utils.Buffer):
utils._check_byteslike("initialization_vector", initialization_vector)
self._initialization_vector = initialization_vector
@property
def initialization_vector(self) -> utils... | CFB8 |
python | huggingface__transformers | src/transformers/models/unispeech/modeling_unispeech.py | {
"start": 16047,
"end": 17418
} | class ____(GradientCheckpointingLayer):
def __init__(self, config):
super().__init__()
self.attention = UniSpeechAttention(
embed_dim=config.hidden_size,
num_heads=config.num_attention_heads,
dropout=config.attention_dropout,
is_decoder=False,
... | UniSpeechEncoderLayer |
python | openai__openai-python | src/openai/types/eval_create_params.py | {
"start": 3733,
"end": 3994
} | class ____(TypedDict, total=False):
text: Required[str]
"""The text output from the model."""
type: Required[Literal["output_text"]]
"""The type of the output text. Always `output_text`."""
| TestingCriterionLabelModelInputEvalItemContentOutputText |
python | kamyu104__LeetCode-Solutions | Python/count-the-number-of-ideal-arrays.py | {
"start": 2173,
"end": 3235
} | class ____(object):
def idealArrays(self, n, maxValue):
"""
:type n: int
:type maxValue: int
:rtype: int
"""
MOD = 10**9+7
fact, inv, inv_fact = [[1]*2 for _ in xrange(3)]
def nCr(n, k):
while len(inv) <= n: # lazy initialization
... | Solution2 |
python | pydantic__pydantic | tests/mypy/outputs/mypy-default_ini/metaclass_args.py | {
"start": 499,
"end": 740
} | class ____(BaseModel, validate_by_name=True):
i: int = Field(2, alias='j')
MetaclassArgumentsWithDefault(i=None)
# MYPY: error: Unexpected keyword argument "i" for "MetaclassArgumentsWithDefault" [call-arg]
| MetaclassArgumentsWithDefault |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/context.py | {
"start": 93870,
"end": 97253
} | class ____:
"""represent an entity column returned within a Query result."""
__slots__ = ()
supports_single_entity: bool
_non_hashable_value = False
_null_column_type = False
use_id_for_hash = False
_label_name: Optional[str]
type: Union[Type[Any], TypeEngine[Any]]
expr: Union[_I... | _QueryEntity |
python | sympy__sympy | sympy/codegen/cfunctions.py | {
"start": 7439,
"end": 8539
} | class ____(Function):
"""
Represents the logarithm function with base ten.
Examples
========
>>> from sympy.abc import x
>>> from sympy.codegen.cfunctions import log10
>>> log10(100).evalf() == 2.0
True
>>> log10(x).diff(x)
1/(x*log(10))
See Also
========
log2
... | log10 |
python | getsentry__sentry | tests/sentry/middleware/integrations/parsers/test_bitbucket_server.py | {
"start": 704,
"end": 2396
} | class ____(TestCase):
get_response = MagicMock(return_value=HttpResponse(content=b"no-error", status=200))
factory = RequestFactory()
region = Region("us", 1, "https://us.testserver", RegionCategory.MULTI_TENANT)
region_config = (region,)
@override_regions(region_config)
@override_settings(SILO... | BitbucketServerRequestParserTest |
python | pytorch__pytorch | test/test_sympy_utils.py | {
"start": 6188,
"end": 13252
} | class ____(TestCase):
@parametrize("fn", UNARY_OPS)
@parametrize("dtype", ("int", "float"))
def test_unary_ref(self, fn, dtype):
dtype = {"int": sympy.Integer, "float": sympy.Float}[dtype]
for v in CONSTANTS:
if not valid_unary(fn, v):
continue
with se... | TestValueRanges |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_type_checking/runtime_evaluated_decorators_1.py | {
"start": 540,
"end": 570
} | class ____:
x: numpy.ndarray
| F |
python | getsentry__sentry | src/sentry/users/api/endpoints/user_emails_confirm.py | {
"start": 635,
"end": 858
} | class ____(Response):
def __init__(self) -> None:
super().__init__(
{"detail": "Invalid email", "email": "Invalid email"},
status=status.HTTP_400_BAD_REQUEST,
)
| InvalidEmailResponse |
python | astropy__astropy | astropy/cosmology/_src/traits/rhocrit.py | {
"start": 274,
"end": 1130
} | class ____:
"""The object has attributes and methods for the critical density."""
critical_density0: Quantity
"""Critical density at redshift 0."""
efunc: Callable[[Any], NDArray[Any]]
def critical_density(self, z: Quantity | ArrayLike, /) -> Quantity:
"""Critical density in grams per cub... | CriticalDensity |
python | numpy__numpy | numpy/linalg/tests/test_linalg.py | {
"start": 19185,
"end": 20312
} | class ____(EigvalsCases):
@pytest.mark.parametrize('dtype', [single, double, csingle, cdouble])
def test_types(self, dtype):
x = np.array([[1, 0.5], [0.5, 1]], dtype=dtype)
assert_equal(linalg.eigvals(x).dtype, dtype)
x = np.array([[1, 0.5], [-1, 1]], dtype=dtype)
assert_equal(li... | TestEigvals |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/cloud_sql.py | {
"start": 46939,
"end": 53282
} | class ____(GoogleCloudBaseOperator):
"""
Perform DML or DDL query on an existing Cloud Sql instance.
It optionally uses cloud-sql-proxy to establish secure connection with the
database.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`h... | CloudSQLExecuteQueryOperator |
python | plotly__plotly.py | plotly/graph_objs/scatter3d/_error_x.py | {
"start": 233,
"end": 14881
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scatter3d"
_path_str = "scatter3d.error_x"
_valid_props = {
"array",
"arrayminus",
"arrayminussrc",
"arraysrc",
"color",
"copy_zstyle",
"symmetric",
"thickness",
"traceref",
... | ErrorX |
python | spyder-ide__spyder | spyder/plugins/debugger/widgets/main_widget.py | {
"start": 2001,
"end": 2164
} | class ____:
Control = 'control_section'
InteractWithConsole = "interact_with_console_section"
Extras = "extras_section"
| DebuggerWidgetMainToolBarSections |
python | python-openxml__python-docx | tests/oxml/unitdata/shared.py | {
"start": 102,
"end": 392
} | class ____(BaseBuilder):
__nspfxs__ = ("w",)
__attrs__ = "w:val"
def __init__(self, tag):
self.__tag__ = tag
super(CT_OnOffBuilder, self).__init__()
def with_val(self, value):
self._set_xmlattr("w:val", str(value))
return self
| CT_OnOffBuilder |
python | ipython__ipython | IPython/core/magic_arguments.py | {
"start": 7066,
"end": 7531
} | class ____:
""" Base class for decorators to add ArgumentParser information to a method.
"""
def __call__(self, func):
if not getattr(func, 'has_arguments', False):
func.has_arguments = True
func.decorators = []
func.decorators.append(self)
return func
d... | ArgDecorator |
python | astropy__astropy | astropy/coordinates/representation/base.py | {
"start": 4518,
"end": 22462
} | class ____(MaskableShapedLikeNDArray):
"""3D coordinate representations and differentials.
Parameters
----------
comp1, comp2, comp3 : `~astropy.units.Quantity` or subclass
The components of the 3D point or differential. The names are the
keys and the subclasses the values of the ``att... | BaseRepresentationOrDifferential |
python | run-llama__llama_index | llama-index-core/llama_index/core/types.py | {
"start": 1041,
"end": 3250
} | class ____(DispatcherSpanMixin, ABC):
"""Output parser class."""
@abstractmethod
def parse(self, output: str) -> Any:
"""Parse, validate, and correct errors programmatically."""
def format(self, query: str) -> str:
"""Format a query with structured output formatting instructions."""
... | BaseOutputParser |
python | pypa__setuptools | setuptools/_vendor/typing_extensions.py | {
"start": 4660,
"end": 53727
} | class ____(typing._SpecialForm, _root=True):
def __repr__(self):
return 'typing_extensions.' + self._name
Final = typing.Final
if sys.version_info >= (3, 11):
final = typing.final
else:
# @final exists in 3.8+, but we backport it for all versions
# before 3.11 to keep support for the __final_... | _ExtensionsSpecialForm |
python | huggingface__transformers | examples/modular-transformers/modeling_test_detr.py | {
"start": 1367,
"end": 4226
} | class ____(nn.Module):
def forward(
self,
value: Tensor,
value_spatial_shapes: Tensor,
value_spatial_shapes_list: list[tuple],
level_start_index: Tensor,
sampling_locations: Tensor,
attention_weights: Tensor,
im2col_step: int,
):
batch_size... | MultiScaleDeformableAttention |
python | ray-project__ray | python/ray/autoscaler/v2/schema.py | {
"start": 675,
"end": 846
} | class ____:
# Resource name.
resource_name: str = ""
# Total resource.
total: float = 0.0
# Resource used.
used: float = 0.0
@dataclass
| ResourceUsage |
python | pallets__jinja | src/jinja2/runtime.py | {
"start": 33247,
"end": 34148
} | class ____(Undefined):
"""An undefined that barks on print and iteration as well as boolean
tests and all kinds of comparisons. In other words: you can do nothing
with it except checking if it's defined using the `defined` test.
>>> foo = StrictUndefined(name='foo')
>>> str(foo)
Traceback (mos... | StrictUndefined |
python | django__django | django/contrib/gis/forms/fields.py | {
"start": 4393,
"end": 4472
} | class ____(GeometryField):
geom_type = "MULTILINESTRING"
| MultiLineStringField |
python | run-llama__llama_index | llama-index-core/llama_index/core/agent/react/output_parser.py | {
"start": 2189,
"end": 4566
} | class ____(BaseOutputParser):
"""ReAct Output parser."""
def parse(self, output: str, is_streaming: bool = False) -> BaseReasoningStep:
"""
Parse output from ReAct agent.
We expect the output to be in one of the following formats:
1. If the agent need to use a tool to answer th... | ReActOutputParser |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_artifacts.py | {
"start": 29738,
"end": 31835
} | class ____:
async def test_update_artifact_succeeds(self, artifact, client):
response = await client.post("/artifacts/filter")
current_time = now("UTC")
assert response.status_code == status.HTTP_200_OK
artifact_id = response.json()[0]["id"]
artifact_key = response.json()[0][... | TestUpdateArtifact |
python | walkccc__LeetCode | solutions/53. Maximum Subarray/53-3.py | {
"start": 271,
"end": 1113
} | class ____:
def maxSubArray(self, nums: list[int]) -> int:
def divideAndConquer(l: int, r: int) -> T:
if l == r:
return T(nums[l], nums[l], nums[l], nums[l])
m = (l + r) // 2
left = divideAndConquer(l, m)
right = divideAndConquer(m + 1, r)
maxSubarraySumLeft = max(left.maxSub... | Solution |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/classes1.py | {
"start": 699,
"end": 778
} | class ____(E, other_keyword=2):
pass
args = [1, 2, 3]
kwargs = {"foo": 5}
| I |
python | tensorflow__tensorflow | tensorflow/python/distribute/coordinator/values.py | {
"start": 5286,
"end": 5685
} | class ____(RemoteValueImpl):
"""A RemoteValue that represents a mutable per-worker variable."""
def get(self):
"""Retrieve value with no caching to ensure we get the up-to-date value."""
self._wait_and_maybe_error()
return self._copy_to_local()
@tf_export("distribute.experimental.coordinator.PerWorke... | RemoteVariable |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.