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 | readthedocs__readthedocs.org | readthedocs/proxito/tests/test_old_redirects.py | {
"start": 802,
"end": 5416
} | class ____(BaseDocServing):
"""
Test our own internal redirects.
* redirects at / --happens at ``ServeDocs`` view
* redirects on /page/.* --happens at ``URLConf``
* invalid URLs --happens at ``URLConf``
"""
def test_root_url(self):
r = self.client.get("/", headers={"host": "projec... | InternalRedirectTests |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 132304,
"end": 132695
} | class ____(BaseModel, extra="forbid"):
languages: Optional[List["Language"]] = Field(
default=None,
description="Set of languages to use for stopwords. Multiple pre-defined lists of stopwords can be combined.",
)
custom: Optional[List[str]] = Field(
default=None, description="Custom ... | StopwordsSet |
python | getsentry__sentry | src/sentry/services/filestore/gcs.py | {
"start": 5006,
"end": 5507
} | class ____(Blob):
def __init__(self, download_url, *args, **kwargs):
self.download_url = download_url
super().__init__(*args, **kwargs)
def _get_download_url(self, *args, **kwargs):
# media_link is for public objects; we completely ignore it.
download_url = f"{self.download_url}... | FancyBlob |
python | numba__llvmlite | llvmlite/binding/value.py | {
"start": 854,
"end": 997
} | class ____(enum.IntEnum):
# The LLVMDLLStorageClass enum from llvm-c/Core.h
default = 0
dllimport = 1
dllexport = 2
| StorageClass |
python | sympy__sympy | sympy/series/sequences.py | {
"start": 13279,
"end": 17244
} | class ____(SeqExpr):
"""
Represents a periodic sequence.
The elements are repeated after a given period.
Examples
========
>>> from sympy import SeqPer, oo
>>> from sympy.abc import k
>>> s = SeqPer((1, 2, 3), (0, 5))
>>> s.periodical
(1, 2, 3)
>>> s.period
3
For... | SeqPer |
python | pytorch__pytorch | torch/ao/nn/quantized/modules/conv.py | {
"start": 39180,
"end": 43515
} | class ____(_ConvTransposeNd):
r"""Applies a 3D transposed convolution operator over an input image
composed of several input planes.
For details on input arguments, parameters, and implementation see
:class:`~torch.nn.ConvTranspose3d`.
.. note:: Currently only the FBGEMM engine is implemented.
... | ConvTranspose3d |
python | walkccc__LeetCode | solutions/1366. Rank Teams by Votes/1366.py | {
"start": 192,
"end": 587
} | class ____:
def rankTeams(self, votes: list[str]) -> str:
teamSize = len(votes[0])
teams = [Team(chr(ord('A') + i), teamSize) for i in range(26)]
for vote in votes:
for i in range(teamSize):
teams[ord(vote[i]) - ord('A')].rank[i] += 1
teams.sort(key=lambda x: (x.rank, -ord(x.name)), re... | Solution |
python | pyca__cryptography | src/cryptography/hazmat/primitives/serialization/pkcs7.py | {
"start": 13650,
"end": 13943
} | class ____(email.message.MIMEPart):
# A MIMEPart subclass that replicates OpenSSL's behavior of not including
# a newline if there are no headers.
def _write_headers(self, generator) -> None:
if list(self.raw_items()):
generator._write_headers(self)
| OpenSSLMimePart |
python | great-expectations__great_expectations | great_expectations/datasource/fluent/bigquery_datasource.py | {
"start": 292,
"end": 886
} | class ____(SQLDatasource):
"""Adds a bigquery datasource to the data context.
Args:
name: The name of this big query datasource.
connection_string: The connection string used to connect to the database.
For example: "bigquery://<gcp_project_name>/<bigquery_dataset>"
assets: A... | BigQueryDatasource |
python | dask__dask | dask/dataframe/dask_expr/_groupby.py | {
"start": 24696,
"end": 24918
} | class ____(SingleAggregation):
groupby_chunk = staticmethod(_head_chunk)
groupby_aggregate = staticmethod(_head_aggregate)
@classmethod
def combine(cls, inputs, **kwargs):
return _concat(inputs)
| Head |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 4107,
"end": 4269
} | class ____(str, Enum):
DEFAULT = "default"
BINARY = "binary"
SCALAR4BITS = "scalar4bits"
SCALAR8BITS = "scalar8bits"
| BinaryQuantizationQueryEncoding |
python | getsentry__sentry | src/sentry/models/groupsearchviewstarred.py | {
"start": 580,
"end": 5774
} | class ____(BaseManager["GroupSearchViewStarred"]):
def num_starred_views(self, organization: Organization, user_id: int) -> int:
"""
Returns the number of starred views for a user in an organization.
"""
return self.filter(organization=organization, user_id=user_id).count()
def ... | GroupSearchViewStarredManager |
python | django__django | django/contrib/staticfiles/management/commands/collectstatic.py | {
"start": 428,
"end": 15970
} | class ____(BaseCommand):
"""
Copies or symlinks static files from different locations to the
settings.STATIC_ROOT.
"""
help = "Collect static files in a single location."
requires_system_checks = [Tags.staticfiles]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwar... | Command |
python | facebook__pyre-check | source/interprocedural_analyses/taint/test/integration/sanitize.py | {
"start": 19550,
"end": 20293
} | class ____:
def sanitize_sources(self):
self.foo = _test_source()
def sanitize_test_a_source(self):
if 1 > 2:
self.foo = a_source()
else:
self.foo = b_source()
def sanitize_parameter(self):
self.foo = _test_source()
def sanitize_parameter_test_a... | GenerationOnSelf |
python | sphinx-doc__sphinx | sphinx/domains/cpp/_ast.py | {
"start": 134143,
"end": 136726
} | class ____(ASTTemplateParam):
def __init__(
self, key: str, identifier: ASTIdentifier, parameterPack: bool, default: ASTType
) -> None:
assert key
if parameterPack:
assert default is None
self.key = key
self.identifier = identifier
self.parameterPack =... | ASTTemplateKeyParamPackIdDefault |
python | fluentpython__example-code | attic/sequences/table.py | {
"start": 2147,
"end": 2638
} | class ____(collections.UserList):
def __init__(self, cells):
super().__init__(cells)
if len(self) < 1:
raise ValueError('Row must have at least one cell.')
def __getitem__(self, position):
if isinstance(position, slice):
return Row(self.data[position]) # build ... | Row |
python | ipython__ipython | tests/test_pretty.py | {
"start": 881,
"end": 972
} | class ____(dict):
def _repr_pretty_(self, p, cycle):
p.text("MyDict(...)")
| MyDict |
python | plotly__plotly.py | plotly/graph_objs/layout/newshape/label/_font.py | {
"start": 235,
"end": 9913
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.newshape.label"
_path_str = "layout.newshape.label.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
... | Font |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/descriptor1.py | {
"start": 2352,
"end": 2648
} | class ____[GT, ST]:
@overload
def __get__(self, instance: None, owner: Any) -> Self: ...
@overload
def __get__(self, instance: Any, owner: Any) -> GT: ...
def __get__(self, instance: Any, owner: Any) -> Any: ...
def __set__(self, instance: Any, value: ST): ...
| Descriptor6 |
python | weaviate__weaviate-python-client | weaviate/rbac/models.py | {
"start": 1522,
"end": 1594
} | class ____(TypedDict):
group: str
groupType: str
| PermissionsGroups |
python | sqlalchemy__sqlalchemy | test/orm/test_generative.py | {
"start": 6580,
"end": 9733
} | class ____(_fixtures.FixtureTest):
run_setup_mappers = "once"
run_inserts = "once"
run_deletes = None
@classmethod
def setup_mappers(cls):
addresses, Order, User, Address, orders, users = (
cls.tables.addresses,
cls.classes.Order,
cls.classes.User,
... | RelationshipsTest |
python | pyca__cryptography | tests/hazmat/primitives/test_concatkdf.py | {
"start": 441,
"end": 5323
} | class ____:
def test_length_limit(self, backend):
big_length = hashes.SHA256().digest_size * (2**32 - 1) + 1
error = OverflowError if sys.maxsize <= 2**31 else ValueError
with pytest.raises(error):
ConcatKDFHash(hashes.SHA256(), big_length, None, backend)
def test_already_f... | TestConcatKDFHash |
python | pytorch__pytorch | test/dynamo/test_subclasses.py | {
"start": 100564,
"end": 102490
} | class ____(torch.nn.Module):
def forward(
self,
primals_5: "Sym(s47)", # SubclassSizeAOTInput(base=PlainAOTInput(idx=2), idx=0)
primals_7: "Sym(s16)", # SubclassStrideAOTInput(base=PlainAOTInput(idx=2), idx=0)
tangents_1: "f32[s16*s47]", # SubclassGetAttrAOTInput(base=TangentAOTIn... | GraphModule |
python | readthedocs__readthedocs.org | readthedocs/organizations/tests/test_orgs.py | {
"start": 7513,
"end": 9415
} | class ____(OrganizationTestCase):
def test_team_add(self):
"""Test member team add form."""
self.add_team(team="foobar")
self.assertEqual(self.organization.teams.count(), 1)
def test_team_add_slug_conflict(self):
"""Add multiple teams with the same slug."""
self.add_team... | OrganizationTeamTests |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/descriptor_props.py | {
"start": 5814,
"end": 32181
} | class ____(
_MapsColumns[_CC], _IntrospectsAnnotations, DescriptorProperty[_CC]
):
"""Defines a "composite" mapped attribute, representing a collection
of columns as one attribute.
:class:`.CompositeProperty` is constructed using the :func:`.composite`
function.
.. seealso::
:ref:`map... | CompositeProperty |
python | milvus-io__pymilvus | tests/test_bulk_writer_stage.py | {
"start": 20878,
"end": 23648
} | class ____:
"""Integration tests for stage operations."""
@pytest.fixture
def mock_server_responses(self) -> Dict[str, Any]:
"""Mock server responses for integration testing."""
return {
"apply_stage": {
"code": 0,
"message": "success",
... | TestIntegration |
python | aio-libs__aiohttp | aiohttp/test_utils.py | {
"start": 6610,
"end": 7201
} | class ____(BaseTestServer[BaseRequest]):
def __init__(
self,
handler: _RequestHandler[BaseRequest],
*,
scheme: str = "",
host: str = "127.0.0.1",
port: int | None = None,
**kwargs: Any,
) -> None:
self._handler = handler
super().__init__(sc... | RawTestServer |
python | django__django | django/template/base.py | {
"start": 3378,
"end": 3458
} | class ____(Enum):
TEXT = 0
VAR = 1
BLOCK = 2
COMMENT = 3
| TokenType |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/models.py | {
"start": 1229,
"end": 1534
} | class ____(models.Model):
name = models.CharField(max_length=100, unique=True)
email = models.EmailField(max_length=100, unique=True)
gender = models.CharField(max_length=50, null=True) # noqa # avoid nullable strs
age = models.IntegerField()
birthday = models.DateTimeField()
| Customer |
python | doocs__leetcode | solution/1600-1699/1670.Design Front Middle Back Queue/Solution.py | {
"start": 0,
"end": 1509
} | class ____:
def __init__(self):
self.q1 = deque()
self.q2 = deque()
def pushFront(self, val: int) -> None:
self.q1.appendleft(val)
self.rebalance()
def pushMiddle(self, val: int) -> None:
self.q1.append(val)
self.rebalance()
def pushBack(self, val: int)... | FrontMiddleBackQueue |
python | Netflix__metaflow | metaflow/decorators.py | {
"start": 10401,
"end": 33295
} | class ____(Decorator):
"""
Base class for all step decorators.
Example:
@my_decorator
@step
def a(self):
pass
@my_decorator
@step
def b(self):
pass
To make the above work, define a subclass
class MyDecorator(StepDecorator):
name = "my_decorator"
... | StepDecorator |
python | tensorflow__tensorflow | tensorflow/python/distribute/tpu_values.py | {
"start": 16682,
"end": 21450
} | class ____(values.OnWritePolicy):
"""Policy defined for `tf.VariableSynchronization.ON_WRITE` synchronization.
This policy is created when `synchronization` is set to
`tf.VariableSynchronization.AUTO` or `tf.VariableSynchronization.ON_WRITE`.
"""
def assign_sub(self,
var,
v... | TPUOnWritePolicy |
python | getsentry__sentry | src/sentry/lang/native/symbolicator.py | {
"start": 15666,
"end": 20485
} | class ____:
"""
The `SymbolicatorSession` is a glorified HTTP request wrapper that does the following things:
- Maintains a `worker_id` which is used downstream in the load balancer for routing.
- Maintains `timeout` parameters which are passed to Symbolicator.
- Converts 404 and 503 errors into pr... | SymbolicatorSession |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-tplcentral/source_tplcentral/source.py | {
"start": 483,
"end": 2286
} | class ____(Oauth2Authenticator):
def __init__(
self,
token_refresh_endpoint: str,
client_id: str,
client_secret: str,
user_login_id: int = None,
user_login: str = None,
scopes: List[str] = None,
):
super().__init__(
token_refresh_endpoi... | TplcentralAuthenticator |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/operators/dataform.py | {
"start": 27477,
"end": 30689
} | class ____(GoogleCloudBaseOperator):
"""
Creates workspace.
:param project_id: Required. The ID of the Google Cloud project where workspace should be in.
:param region: Required. Name of the Google Cloud region that where workspace should be in.
:param repository_id: Required. The ID of the Datafor... | DataformCreateWorkspaceOperator |
python | pytorch__pytorch | test/onnx/test_pytorch_onnx_shape_inference.py | {
"start": 1241,
"end": 16471
} | class ____(pytorch_test_common.ExportTestCase):
def setUp(self):
self.opset_version = _constants.ONNX_TORCHSCRIPT_EXPORTER_MAX_OPSET
GLOBALS.export_onnx_opset_version = self.opset_version
def run_test(self, g, n, type_assertion_funcs):
if not isinstance(type_assertion_funcs, list):
... | TestONNXShapeInference |
python | python-attrs__attrs | tests/test_validators.py | {
"start": 9241,
"end": 11504
} | class ____:
"""
Tests for `in_`.
"""
def test_in_all(self):
"""
Verify that this validator is in ``__all__``.
"""
assert in_.__name__ in validator_module.__all__
def test_success_with_value(self):
"""
If the value is in our options, nothing happens.
... | TestIn_ |
python | pytorch__pytorch | torch/ao/quantization/fx/_model_report/detector.py | {
"start": 1096,
"end": 4436
} | class ____:
r"""
This class contains the QConfig information for a single module.
The list of variables / values this contains can grow depending on the
extensibility of the qconfig mapping feature set but this currently includes:
- if activation observer is dynamic
- if weight observer is per c... | DetectorQConfigInfo |
python | huggingface__transformers | src/transformers/models/ibert/modeling_ibert.py | {
"start": 43148,
"end": 43938
} | class ____(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.out_proj = nn.Linear(config.hidden_... | IBertClassificationHead |
python | numba__numba | numba/tests/test_sort.py | {
"start": 4597,
"end": 16275
} | class ____(BaseSortingTest):
def merge_init(self, keys):
f = self.timsort.merge_init
return f(keys)
def test_binarysort(self):
n = 20
def check(l, n, start=0):
res = self.array_factory(l)
f(res, res, 0, n, start)
self.assertSorted(l, res)
... | BaseTimsortTest |
python | scipy__scipy | scipy/sparse/linalg/_eigen/tests/test_svds.py | {
"start": 35961,
"end": 36616
} | class ____(SVDSCommonTests):
def setup_method(self):
self.solver = 'propack'
def test_svd_LM_ones_matrix(self):
message = ("PROPACK does not return orthonormal singular vectors "
"associated with zero singular values.")
# There are some other issues with this matrix ... | Test_SVDS_PROPACK |
python | PyCQA__pylint | doc/data/messages/i/invalid-length-returned/good.py | {
"start": 0,
"end": 159
} | class ____:
def __init__(self, fruits):
self.fruits = ["Apple", "Banana", "Orange"]
def __len__(self):
return len(self.fruits)
| FruitBasket |
python | great-expectations__great_expectations | great_expectations/render/components.py | {
"start": 1430,
"end": 1743
} | class ____(str, Enum):
"""Available atomic diagnostic renderer names"""
FAILED = ".".join([AtomicRendererType.DIAGNOSTIC, "failed"])
OBSERVED_VALUE = ".".join([AtomicRendererType.DIAGNOSTIC, "observed_value"])
@override
def __str__(self):
return self.value
| AtomicDiagnosticRendererType |
python | Lightning-AI__lightning | tests/tests_pytorch/strategies/test_ddp_integration.py | {
"start": 12663,
"end": 13350
} | class ____(BoringModel):
def configure_optimizers(self):
assert all(param.device.type == "cuda" for param in self.parameters())
super().configure_optimizers()
@RunIf(min_cuda_gpus=1)
@pytest.mark.parametrize("strategy", ["ddp", "ddp_spawn"])
def test_model_parameters_on_device_for_optimizer(strate... | CheckOptimizerDeviceModel |
python | PyCQA__pylint | tests/regrtest_data/max_inferable_limit_for_classes/main.py | {
"start": 577,
"end": 667
} | class ____(FunctionElement):
def __init__(self):
super().__init__()
| months_between |
python | conda__conda | conda/models/records.py | {
"start": 1656,
"end": 2986
} | class ____(NumberField):
def __init__(self):
super().__init__(default=0, required=False, default_in_dump=False)
@staticmethod
def _make_seconds(val):
if val:
val = val
if val > 253402300799: # 9999-12-31
val /= (
1000 # convert m... | TimestampField |
python | xlwings__xlwings | tests/test_shape.py | {
"start": 8240,
"end": 8772
} | class ____(TestBase):
def test_add_no_name(self):
fig = plt.figure()
plt.plot([-1, 1, -2, 2, -3, 3, 2])
self.wb1.sheets[0].pictures.add(fig)
self.assertEqual(len(self.wb1.sheets[0].pictures), 1)
def test_add_with_name(self):
fig = plt.figure()
plt.plot([-1, 1, -2... | TestMatplotlib |
python | getsentry__sentry | tests/sentry/monitors/consumers/test_end_to_end.py | {
"start": 1711,
"end": 10877
} | class ____(TestCase):
def send_checkin(
self,
status: str,
guid: str | None = None,
ts: datetime | None = None,
item_ts: datetime | None = None,
) -> str:
if ts is None:
ts = self.time.replace(tzinfo=None)
if item_ts is None:
item_t... | MonitorsClockTickEndToEndTest |
python | pytorch__pytorch | test/distributed/tensor/experimental/test_tp_transform.py | {
"start": 1387,
"end": 5602
} | class ____(DTensorTestBase):
def setUp(self) -> None:
super().setUp()
def assert_has_c10d_ops(
self, gm: torch.fx.GraphModule, expected_ops_count: dict[str, int]
) -> None:
actual_ops_count: dict[str, int] = defaultdict(int)
for node in gm.graph.nodes:
if node.op... | TensorParallelTest |
python | kamyu104__LeetCode-Solutions | Python/all-paths-from-source-lead-to-destination.py | {
"start": 58,
"end": 1102
} | class ____(object):
def leadsToDestination(self, n, edges, source, destination):
"""
:type n: int
:type edges: List[List[int]]
:type source: int
:type destination: int
:rtype: bool
"""
UNVISITED, VISITING, DONE = range(3)
def dfs(children, node... | Solution |
python | bokeh__bokeh | src/bokeh/events.py | {
"start": 9465,
"end": 9731
} | class ____(ModelEvent):
''' Announce a click event on a Bokeh legend item.
'''
event_name = 'legend_item_click'
def __init__(self, model: Legend, item: LegendItem) -> None:
self.item = item
super().__init__(model=model)
| LegendItemClick |
python | pydantic__pydantic | pydantic-core/tests/validators/test_dataclasses.py | {
"start": 46844,
"end": 46927
} | class ____:
a: str
b: bool
@dataclasses.dataclass(**kwargs)
| FooDataclassSlots |
python | pallets__werkzeug | src/werkzeug/datastructures/range.py | {
"start": 194,
"end": 1147
} | class ____:
"""Very simple object that represents the `If-Range` header in parsed
form. It will either have neither a etag or date or one of either but
never both.
.. versionadded:: 0.7
"""
def __init__(self, etag: str | None = None, date: datetime | None = None):
#: The etag parsed a... | IfRange |
python | ray-project__ray | python/ray/autoscaler/v2/scheduler.py | {
"start": 3395,
"end": 3870
} | class ____(ABC):
"""
Interface for a resource scheduler.
Implements the `instance_manager.proto ResourceSchedulerService` interface.
"""
@abstractmethod
def schedule(self, request: SchedulingRequest) -> SchedulingReply:
"""
Given the resource requests and the current cluster st... | IResourceScheduler |
python | vyperlang__vyper | vyper/venom/analysis/mem_ssa.py | {
"start": 1869,
"end": 1961
} | class ____(MemoryAccess):
"""
For type checking purposes
"""
pass
| LiveOnEntry |
python | dateutil__dateutil | src/dateutil/parser/_parser.py | {
"start": 58616,
"end": 58796
} | class ____(RuntimeWarning):
"""Raised when the parser finds a timezone it cannot parse into a tzinfo.
.. versionadded:: 2.7.0
"""
# vim:ts=4:sw=4:et
| UnknownTimezoneWarning |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_defined_name02.py | {
"start": 315,
"end": 865
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("defined_name02.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file with defined names."""
workbook... | TestCompareXLSXFiles |
python | getsentry__sentry | tests/sentry/api/endpoints/release_thresholds/test_release_threshold_details.py | {
"start": 2686,
"end": 4798
} | class ____(APITestCase):
def setUp(self) -> None:
super().setUp()
self.user = self.create_user(is_staff=True, is_superuser=True)
self.canary_environment = Environment.objects.create(
organization_id=self.organization.id, name="canary"
)
self.production_environmen... | ReleaseThresholdDetailsDELETETest |
python | huggingface__transformers | src/transformers/models/instructblipvideo/modeling_instructblipvideo.py | {
"start": 13323,
"end": 15139
} | class ____(InstructBlipVideoPreTrainedModel):
main_input_name = "pixel_values"
input_modalities = "video"
config: InstructBlipVideoVisionConfig
_can_record_outputs = {
"hidden_states": InstructBlipVideoEncoderLayer,
"attentions": InstructBlipVideoAttention,
}
def __init__(self, ... | InstructBlipVideoVisionModel |
python | coleifer__peewee | tests/manytomany.py | {
"start": 21568,
"end": 22642
} | class ____(ModelTestCase):
database = get_in_memory_db()
requires = [Permission, Visitor, Visitor.allowed.through_model,
Visitor.denied.through_model]
def test_multiple_manytomany_same_tables(self):
p1, p2, p3 = [Permission.create(name=n) for n in ('p1', 'p2', 'p3')]
v1, v2,... | TestMultipleManyToManySameTables |
python | huggingface__transformers | src/transformers/models/sam3_tracker_video/modeling_sam3_tracker_video.py | {
"start": 39439,
"end": 41935
} | class ____(nn.Module):
def __init__(self, config: Sam3TrackerVideoConfig):
super().__init__()
self.layers = nn.ModuleList(
[Sam3TrackerVideoMemoryAttentionLayer(config) for _ in range(config.memory_attention_num_layers)]
)
self.layer_norm = nn.LayerNorm(config.memory_atte... | Sam3TrackerVideoMemoryAttention |
python | pytorch__pytorch | torch/distributed/fsdp/_fully_shard/_fsdp_collectives.py | {
"start": 1816,
"end": 2467
} | class ____:
def __init__(self, group: dist.ProcessGroup, *args: Any, **kwargs: Any):
self._group = group
super().__init__(*args, **kwargs)
def allocate(
self,
size: Sequence[Union[int, torch.SymInt]],
*,
dtype: torch.dtype,
device: torch.device,
) -> ... | ProcessGroupAllocMixin |
python | numba__llvmlite | llvmlite/tests/test_binding.py | {
"start": 84866,
"end": 87677
} | class ____(BaseTest):
mod_asm = """
;ModuleID = <string>
target triple = "{triple}"
declare i32 @sum(i32 %.1, i32 %.2)
define i32 @sum_twice(i32 %.1, i32 %.2) {{
%.3 = call i32 @sum(i32 %.1, i32 %.2)
%.4 = call i32 @sum(i32 %.3, i32 %.3)
ret i32... | TestObjectFile |
python | tornadoweb__tornado | tornado/test/gen_test.py | {
"start": 28117,
"end": 31862
} | class ____(AsyncTestCase):
def is_pypy3(self):
return platform.python_implementation() == "PyPy" and sys.version_info > (3,)
@gen_test
def test_gc(self):
# GitHub issue 1769: Runner objects can get GCed unexpectedly
# while their future is alive.
weakref_scope = [None] # ty... | RunnerGCTest |
python | huggingface__transformers | src/transformers/models/janus/modular_janus.py | {
"start": 29190,
"end": 31885
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.num_resolutions = len(config.channel_multiplier)
self.num_res_blocks = config.num_res_blocks
base_channels = config.base_channels
latent_channels = config.latent_channels
out_channels = config... | JanusVQVAEDecoder |
python | realpython__materials | python-maze-solver/source_code_final/src/maze_solver/view/renderer.py | {
"start": 573,
"end": 1307
} | class ____:
xml_content: str
@property
def html_content(self) -> str:
return textwrap.dedent(
"""\
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<t... | SVG |
python | astropy__astropy | astropy/coordinates/tests/test_celestial_transformations.py | {
"start": 6478,
"end": 8758
} | class ____:
"""
Check HCRS<->ICRS coordinate conversions.
Uses ICRS Solar positions predicted by get_body_barycentric; with `t1` and
`tarr` as defined below, the ICRS Solar positions were predicted using, e.g.
coord.ICRS(coord.get_body_barycentric(tarr, 'sun')).
"""
def setup_method(self):... | TestHCRS |
python | sphinx-doc__sphinx | sphinx/builders/linkcheck.py | {
"start": 2144,
"end": 7557
} | class ____(DummyBuilder):
"""Checks for broken external links."""
name = 'linkcheck'
epilog = __('Look for any errors in the above output or in %(outdir)s/output.txt')
def init(self) -> None:
self.broken_hyperlinks = 0
self.timed_out_hyperlinks = 0
self.hyperlinks: dict[str, Hy... | CheckExternalLinksBuilder |
python | dask__dask | dask/dataframe/dask_expr/io/parquet.py | {
"start": 8471,
"end": 25085
} | class ____(Expr):
_parameters = ToParquet._parameters
@property
def _meta(self):
return None
def _divisions(self):
return (None, None)
def _layer(self):
if self.write_metadata_file:
append = self.append
compression = self.write_kwargs.get("compressi... | ToParquetBarrier |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 130564,
"end": 132550
} | class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
api_key: str,
start_date: Optional[str] = None,
lookback_window_days: Optional[int] = None,
string_event_properties_keys: Optional[list[str]] = None,
numeric_event_properties_keys: ... | OrbSource |
python | gevent__gevent | src/gevent/tests/lock_tests.py | {
"start": 5019,
"end": 6490
} | class ____(BaseLockTests):
"""
Tests for recursive locks.
"""
def test_reacquire(self):
lock = self.locktype()
lock.acquire()
lock.acquire()
lock.release()
lock.acquire()
lock.release()
lock.release()
def test_release_unacquired(self):
... | RLockTests |
python | huggingface__transformers | src/transformers/models/pvt_v2/configuration_pvt_v2.py | {
"start": 1065,
"end": 8005
} | class ____(BackboneConfigMixin, PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`PvtV2Model`]. It is used to instantiate a Pvt V2
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
defaults will yie... | PvtV2Config |
python | pandas-dev__pandas | pandas/tests/series/methods/test_copy.py | {
"start": 115,
"end": 2451
} | class ____:
@pytest.mark.parametrize("deep", ["default", None, False, True])
def test_copy(self, deep):
ser = Series(np.arange(10), dtype="float64")
# default deep is True
if deep == "default":
ser2 = ser.copy()
else:
ser2 = ser.copy(deep=deep)
#... | TestCopy |
python | mlflow__mlflow | mlflow/server/graphql/graphql_schema_extensions.py | {
"start": 2180,
"end": 2766
} | class ____(QueryType):
test = graphene.Field(Test, input_string=graphene.String(), description="Simple echoing field")
mlflow_search_runs = graphene.Field(MlflowSearchRunsResponse, input=MlflowSearchRunsInput())
def resolve_test(self, info, input_string):
return {"output": input_string}
def re... | Query |
python | huggingface__transformers | src/transformers/utils/auto_docstring.py | {
"start": 6971,
"end": 20106
} | class ____:
labels = {
"description": """
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
(masked), the loss is only computed for the tokens with l... | ModelArgs |
python | ray-project__ray | python/ray/serve/tests/unit/test_proxy_state.py | {
"start": 699,
"end": 949
} | class ____:
def __init__(self):
self.alive_nodes = []
def get_alive_nodes(self):
return self.alive_nodes
def get_alive_node_ids(self):
return {node_id for node_id, _, _ in self.alive_nodes}
| MockClusterNodeInfoCache |
python | pallets__jinja | src/jinja2/nodes.py | {
"start": 30255,
"end": 30815
} | class ____(Expr):
"""An internal name in the compiler. You cannot create these nodes
yourself but the parser provides a
:meth:`~jinja2.parser.Parser.free_identifier` method that creates
a new identifier for you. This identifier is not available from the
template and is not treated specially by the... | InternalName |
python | pypa__pip | src/pip/_vendor/rich/highlighter.py | {
"start": 3543,
"end": 4755
} | class ____(RegexHighlighter):
"""Highlights JSON"""
# Captures the start and end of JSON strings, handling escaped quotes
JSON_STR = r"(?<![\\\w])(?P<str>b?\".*?(?<!\\)\")"
JSON_WHITESPACE = {" ", "\n", "\r", "\t"}
base_style = "json."
highlights = [
_combine_regex(
r"(?P<b... | JSONHighlighter |
python | pytorch__pytorch | test/dynamo/cpython/3_13/test_baseexception.py | {
"start": 676,
"end": 1570
} | class ____(importlib.abc.MetaPathFinder):
def find_spec(self, fullname, path, target=None):
# Check if the import is the problematic one
if fullname in redirect_imports:
try:
# Attempt to import the standalone module
name = fullname.removeprefix("test.")
... | RedirectImportFinder |
python | kamyu104__LeetCode-Solutions | Python/number-of-paths-with-max-score.py | {
"start": 31,
"end": 1042
} | class ____(object):
def pathsWithMaxScore(self, board):
"""
:type board: List[str]
:rtype: List[int]
"""
MOD = 10**9+7
directions = [[1, 0], [0, 1], [1, 1]]
dp = [[[0, 0] for r in xrange(len(board[0])+1)]
for r in xrange(2)]
dp[(len(board... | Solution |
python | doocs__leetcode | solution/0300-0399/0344.Reverse String/Solution.py | {
"start": 0,
"end": 185
} | class ____:
def reverseString(self, s: List[str]) -> None:
i, j = 0, len(s) - 1
while i < j:
s[i], s[j] = s[j], s[i]
i, j = i + 1, j - 1
| Solution |
python | encode__django-rest-framework | tests/schemas/views.py | {
"start": 4441,
"end": 4992
} | class ____(generics.GenericAPIView):
serializer_class = ExampleValidatedSerializer
def get(self, *args, **kwargs):
serializer = self.get_serializer(integer=33, string='hello', regex='foo', decimal1=3.55,
decimal2=5.33, email='a@b.co',
... | ExampleValidatedAPIView |
python | sqlalchemy__sqlalchemy | test/orm/test_attributes.py | {
"start": 111976,
"end": 113418
} | class ____(fixtures.TestBase):
def setup_test(self):
class A:
pass
class B:
pass
self.A = A
self.B = B
instrumentation.register_class(A)
instrumentation.register_class(B)
_register_attribute(A, "bs", uselist=True, useobject=True)
... | TestUnlink |
python | numba__numba | numba/tests/test_np_functions.py | {
"start": 9188,
"end": 233635
} | class ____(MemoryLeakMixin, TestCase):
"""
Tests for various Numpy functions.
"""
def setUp(self):
super(TestNPFunctions, self).setUp()
self.rnd = np.random.RandomState(42)
def run_unary(self, pyfunc, x_types, x_values, func_extra_types=None,
func_extra_args=None,... | TestNPFunctions |
python | pytorch__pytorch | test/distributed/elastic/multiprocessing/redirects_test.py | {
"start": 550,
"end": 4749
} | class ____(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp(prefix=f"{self.__class__.__name__}_")
def tearDown(self):
shutil.rmtree(self.test_dir)
def test_redirect_invalid_std(self):
with self.assertRaises(ValueError):
with redirect("stdfoo", os.pa... | RedirectsTest |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 67873,
"end": 68134
} | class ____(_PrintableStructure):
_fields_ = [
('pid', c_uint),
('timeStamp', c_ulonglong),
('smUtil', c_uint),
('memUtil', c_uint),
('encUtil', c_uint),
('decUtil', c_uint),
]
| c_nvmlProcessUtilizationSample_t |
python | encode__django-rest-framework | tests/schemas/views.py | {
"start": 901,
"end": 1225
} | class ____(APIView):
"""
get: A description of my GET operation.
post: A description of my POST operation.
"""
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get(self, *args, **kwargs):
pass
def post(self, request, *args, **kwargs):
pass
| DocStringExampleListView |
python | boto__boto3 | tests/functional/test_s3.py | {
"start": 8518,
"end": 12573
} | class ____(BaseTransferTest):
def setUp(self):
super().setUp()
self.contents = io.BytesIO(b'foo\n')
def stub_put_object(self):
put_object_response = {
"ETag": self.etag,
"ResponseMetadata": {"HTTPStatusCode": 200},
}
expected_params = {
... | TestUploadFileobj |
python | doocs__leetcode | solution/0400-0499/0474.Ones and Zeroes/Solution.py | {
"start": 0,
"end": 539
} | class ____:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
sz = len(strs)
f = [[[0] * (n + 1) for _ in range(m + 1)] for _ in range(sz + 1)]
for i, s in enumerate(strs, 1):
a, b = s.count("0"), s.count("1")
for j in range(m + 1):
for k ... | Solution |
python | pytorch__pytorch | torch/fx/experimental/const_fold.py | {
"start": 324,
"end": 14300
} | class ____(torch.fx.GraphModule):
"""
FoldedGraphModule is a GraphModule which also contains another
`const_subgraph_module` representing a subgraph which has all const attr
inputs and which can be run once before running the main standard
`graph`. The `const_output_names` are the ordered list names... | FoldedGraphModule |
python | sqlalchemy__sqlalchemy | test/base/test_utils.py | {
"start": 39973,
"end": 40979
} | class ____(fixtures.TestBase):
def test_lru(self):
class item:
def __init__(self, id_):
self.id = id_
def __str__(self):
return "item id %d" % self.id
lru = util.LRUCache(10, threshold=0.2)
for id_ in range(1, 20):
lru[id... | LRUTest |
python | apache__airflow | providers/fab/tests/unit/fab/auth_manager/test_security.py | {
"start": 4194,
"end": 43022
} | class ____(BaseView):
route_base = ""
@expose("/some_action")
@has_access
def some_action(self):
return "action!"
def _clear_db_dag_and_runs():
clear_db_runs()
clear_db_dags()
clear_db_dag_bundles()
def _delete_dag_permissions(dag_id, security_manager):
dag_resource_name = _... | SomeBaseView |
python | pytorch__pytorch | test/test_dataloader.py | {
"start": 119915,
"end": 120555
} | class ____(Dataset):
from collections import namedtuple
Batch = namedtuple("Batch", ["data", "label", "random_tensor"])
Data = namedtuple("Data", ["positive", "negative"])
def __len__(self):
return 4
def __getitem__(self, ndx):
return self.Batch(
data=self.Data(positiv... | NamedTupleDataset |
python | kamyu104__LeetCode-Solutions | Python/n-ary-tree-preorder-traversal.py | {
"start": 146,
"end": 581
} | class ____(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
result, stack = [], [root]
while stack:
node = stack.pop()
result.append(node.val)
for child in reve... | Solution |
python | marshmallow-code__marshmallow | src/marshmallow/fields.py | {
"start": 48746,
"end": 49503
} | class ____(_TemporalField[dt.time]):
"""A formatted time string.
Example: ``'03:12:58.019077'``
:param format: Either ``"iso"`` (for ISO8601) or a date format string.
If `None`, defaults to "iso".
:param kwargs: The same keyword arguments that :class:`Field` receives.
"""
SERIALIZATIO... | Time |
python | tensorflow__tensorflow | tensorflow/python/ops/image_ops_test.py | {
"start": 93741,
"end": 108904
} | class ____(test_util.TensorFlowTestCase):
def _testSampleDistortedBoundingBox(self, image, bounding_box,
min_object_covered, aspect_ratio_range,
area_range):
original_area = float(np.prod(image.shape))
bounding_box_area = float((boun... | SelectDistortedCropBoxTest |
python | langchain-ai__langchain | libs/langchain_v1/langchain/agents/middleware/types.py | {
"start": 8930,
"end": 9798
} | class ____:
"""Response from model execution including messages and optional structured output.
The result will usually contain a single `AIMessage`, but may include an additional
`ToolMessage` if the model used a tool for structured output.
"""
result: list[BaseMessage]
"""List of messages fr... | ModelResponse |
python | keras-team__keras | keras/src/losses/losses_test.py | {
"start": 71807,
"end": 74324
} | class ____(testing.TestCase):
def test_config(self):
self.run_class_serialization_test(losses.Tversky(name="mytversky"))
def test_correctness(self):
y_true = np.array(([[1, 2], [1, 2]]))
y_pred = np.array(([[4, 1], [6, 1]]))
output = losses.Tversky()(y_true, y_pred)
self... | TverskyTest |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-feishu-docs/llama_index/readers/feishu_docs/base.py | {
"start": 805,
"end": 3779
} | class ____(BaseReader):
"""
Feishu Docs reader.
Reads a page from Google Docs
"""
host = "https://open.feishu.cn"
documents_raw_content_url_path = "/open-apis/docx/v1/documents/{}/raw_content"
tenant_access_token_internal_url_path = (
"/open-apis/auth/v3/tenant_access_token/intern... | FeishuDocsReader |
python | kamyu104__LeetCode-Solutions | Python/minimum-operations-to-form-subsequence-with-target-sum.py | {
"start": 1049,
"end": 1790
} | class ____(object):
def minOperations(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
total = sum(nums)
if total < target:
return -1
nums.sort()
result = 0
while target:
x = nums... | Solution2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.