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 | huggingface__transformers | src/transformers/models/modernbert/modular_modernbert.py | {
"start": 23553,
"end": 28276
} | class ____(Gemma3RotaryEmbedding):
def __init__(self, config: ModernBertConfig, device=None):
super().__init__(config, device)
@staticmethod
def compute_default_rope_parameters(
config: Optional[ModernBertConfig] = None,
device: Optional["torch.device"] = None,
seq_len: Opti... | ModernBertRotaryEmbedding |
python | ansible__ansible | test/lib/ansible_test/_internal/containers.py | {
"start": 19251,
"end": 23127
} | class ____:
"""Context object for tracking information relating to access of support containers."""
def __init__(self, containers: ContainerDatabase, process: t.Optional[SshProcess]) -> None:
self.containers = containers
self.process = process
def close(self) -> None:
"""Close the ... | SupportContainerContext |
python | python-excel__xlwt | xlwt/BIFFRecords.py | {
"start": 13161,
"end": 13304
} | class ____(BiffRecord):
"""
"""
_REC_ID = 0x01B7
def __init__(self):
self._rec_data = pack('<H', 0x00)
| RefreshAllRecord |
python | doocs__leetcode | solution/0300-0399/0308.Range Sum Query 2D - Mutable/Solution.py | {
"start": 449,
"end": 1310
} | class ____:
def __init__(self, matrix: List[List[int]]):
self.trees = []
n = len(matrix[0])
for row in matrix:
tree = BinaryIndexedTree(n)
for j, v in enumerate(row):
tree.update(j + 1, v)
self.trees.append(tree)
def update(self, row: ... | NumMatrix |
python | automl__auto-sklearn | autosklearn/pipeline/components/base.py | {
"start": 5466,
"end": 5996
} | class ____(AutoSklearnComponent):
def fit(self, X, y, sample_weight=None):
self.iterative_fit(X, y, n_iter=2, refit=True)
iteration = 2
while not self.configuration_fully_fitted():
n_iter = int(2**iteration / 2)
self.iterative_fit(X, y, n_iter=n_iter, refit=False)
... | IterativeComponent |
python | sympy__sympy | sympy/physics/biomechanics/curve.py | {
"start": 32778,
"end": 46209
} | class ____(CharacteristicCurveFunction):
r"""Active muscle fiber force-length curve based on De Groote et al., 2016
[1]_.
Explanation
===========
The function is defined by the equation:
$fl_{\text{act}}^M = c_0 \exp\left(-\frac{1}{2}\left(\frac{\tilde{l}^M - c_1}{c_2 + c_3 \tilde{l}^M}\right... | FiberForceLengthActiveDeGroote2016 |
python | keras-team__keras | keras/src/backend/torch/optimizers/torch_sgd.py | {
"start": 121,
"end": 1175
} | class ____(torch_parallel_optimizer.TorchParallelOptimizer, optimizers.SGD):
def _parallel_update_step(
self,
grads,
variables,
learning_rate,
):
keras_variables = variables
variables = [v.value for v in variables]
if self.momentum != 0:
bufs =... | SGD |
python | astropy__astropy | astropy/table/tests/test_table.py | {
"start": 18370,
"end": 19865
} | class ____(SetupData):
def test_override_name(self, table_types):
self._setup(table_types)
t = table_types.Table()
# Check that we can override the name of the input column in the Table
t.add_column(self.a, name="b")
t.add_column(self.b, name="a")
assert t.colnames =... | TestAddName |
python | xlwings__xlwings | xlwings/constants.py | {
"start": 115157,
"end": 115277
} | class ____:
xlCodePage = 2 # from enum XlSortMethodOld
xlSyllabary = 1 # from enum XlSortMethodOld
| SortMethodOld |
python | pydata__xarray | asv_bench/benchmarks/dataset_io.py | {
"start": 4781,
"end": 6415
} | class ____(IOSingleNetCDF):
def setup(self):
# TODO: Lazily skipped in CI as it is very demanding and slow.
# Improve times and remove errors.
_skip_slow()
requires_dask()
self.make_ds()
self.filepath = "test_single_file.nc4.nc"
self.format = "NETCDF4"
... | IOReadSingleNetCDF4Dask |
python | xlwings__xlwings | tests/common.py | {
"start": 356,
"end": 1698
} | class ____(unittest.TestCase):
def __init__(self, methodName):
super(TestBase, self).__init__(methodName)
# Patch the test method being run to skip the test if it
# throws NotImplementedError. This allows us to not consider
# such tests failures, though they will still show up (as
... | TestBase |
python | huggingface__transformers | tests/models/llava_next_video/test_modeling_llava_next_video.py | {
"start": 6618,
"end": 12612
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
"""
Model tester for `LlavaNextVideoForConditionalGeneration`.
"""
all_model_classes = (
(
LlavaNextVideoModel,
LlavaNextVideoForConditionalGeneration,
)
if is_torch_available()
... | LlavaNextVideoForConditionalGenerationModelTest |
python | tensorflow__tensorflow | tensorflow/compiler/tests/spacetobatch_op_test.py | {
"start": 7347,
"end": 12316
} | class ____(xla_test.XLATestCase):
"""Tests input-output pairs for the SpaceToBatchND and BatchToSpaceND ops."""
def _testPad(self, inputs, block_shape, paddings, outputs):
block_shape = np.array(block_shape)
paddings = np.array(paddings).reshape((len(block_shape), 2))
with self.session() as sess, self.... | SpaceToBatchNDTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-shopify/unit_tests/integration/test_bulk_stream.py | {
"start": 3186,
"end": 9363
} | class ____(TestCase):
def setUp(self) -> None:
self._http_mocker = HttpMocker()
self._http_mocker.__enter__()
set_up_shop(self._http_mocker, _SHOP_NAME)
grant_all_scopes(self._http_mocker, _SHOP_NAME)
def tearDown(self) -> None:
self._http_mocker.__exit__(None, None, No... | GraphQlBulkStreamTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 67747,
"end": 68224
} | class ____(sgqlc.types.Enum):
"""The review status of a pull request.
Enumeration Choices:
* `APPROVED`: The pull request has received an approving review.
* `CHANGES_REQUESTED`: Changes have been requested on the pull
request.
* `REVIEW_REQUIRED`: A review is required before the pull reques... | PullRequestReviewDecision |
python | PyCQA__pylint | tests/functional/n/no/no_member_augassign.py | {
"start": 231,
"end": 302
} | class ____:
value: int
obj_a = A()
obj_a.value += 1 # [no-member]
| A |
python | dask__dask | dask/_expr.py | {
"start": 26020,
"end": 28706
} | class ____(Expr):
"""A singleton Expr class
This is used to treat the subclassed expression as a singleton. Singletons
are deduplicated by expr._name which is typically based on the dask.tokenize
output.
This is a crucial performance optimization for expressions that walk through
an optimizer ... | SingletonExpr |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/testing/assertsql.py | {
"start": 1843,
"end": 8252
} | class ____(SQLMatchRule):
def __init__(
self, statement, params=None, dialect="default", enable_returning=True
):
self.statement = statement
self.params = params
self.dialect = dialect
self.enable_returning = enable_returning
def _compare_sql(self, execute_observed, ... | CompiledSQL |
python | django__django | tests/file_storage/models.py | {
"start": 774,
"end": 894
} | class ____(FileSystemStorage):
def __call__(self):
# no-op implementation.
return self
| CallableStorage |
python | mkdocstrings__mkdocstrings | src/mkdocstrings/_internal/plugin.py | {
"start": 1642,
"end": 2970
} | class ____(Config):
"""The configuration options of `mkdocstrings`, written in `mkdocs.yml`."""
handlers = opt.Type(dict, default={})
"""
Global configuration of handlers.
You can set global configuration per handler, applied everywhere,
but overridable in each "autodoc" instruction. Example:
... | PluginConfig |
python | getsentry__sentry | fixtures/safe_migrations_apps/bad_flow_add_column_with_notnull_app/migrations/0002_add_field_notnull.py | {
"start": 153,
"end": 451
} | class ____(CheckedMigration):
dependencies = [
("bad_flow_add_column_with_notnull_app", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="testtable",
name="field",
field=models.IntegerField(),
),
]
| Migration |
python | python-openxml__python-docx | tests/oxml/test_xmlchemy.py | {
"start": 25866,
"end": 26092
} | class ____(BaseOxmlElement):
"""
Oom standing for 'OneOrMore', ``<w:oomChild>`` element, representing a
child element that can appear multiple times in sequence, but must appear
at least once.
"""
| CT_OomChild |
python | getsentry__sentry | src/sentry/auth_v2/utils/session.py | {
"start": 2089,
"end": 3495
} | class ____:
"""
Manages authentication session state and flags.
This class sets session flags that control the authentication
flow on the frontend, based on the current user's state.
"""
def __init__(self, request: Request):
self.request = request
def initialize_auth_flags(self) -... | SessionBuilder |
python | getsentry__sentry | src/sentry/identity/vercel/provider.py | {
"start": 205,
"end": 1081
} | class ____(OAuth2Provider):
key = "vercel"
name = "Vercel"
# https://vercel.com/docs/integrations/reference#using-the-vercel-api/exchange-code-for-access-token
oauth_access_token_url = "https://api.vercel.com/v2/oauth/access_token"
def get_oauth_client_id(self) -> str | int:
return options... | VercelIdentityProvider |
python | huggingface__transformers | src/transformers/models/deberta_v2/modeling_deberta_v2.py | {
"start": 34979,
"end": 36008
} | class ____(nn.Module):
"""https://github.com/microsoft/DeBERTa/blob/master/DeBERTa/deberta/bert.py#L270"""
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
if isinstance(config.hidden_act, str):
self.transform_act... | DebertaV2LMPredictionHead |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0071_migrate_remaining_metric_alerts.py | {
"start": 31501,
"end": 32827
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | openai__openai-python | src/openai/types/images_response.py | {
"start": 926,
"end": 1905
} | class ____(BaseModel):
created: int
"""The Unix timestamp (in seconds) of when the image was created."""
background: Optional[Literal["transparent", "opaque"]] = None
"""The background parameter used for the image generation.
Either `transparent` or `opaque`.
"""
data: Optional[List[Image... | ImagesResponse |
python | readthedocs__readthedocs.org | readthedocs/core/views/__init__.py | {
"start": 2641,
"end": 3070
} | class ____(PrivateViewMixin, TemplateView):
form_class = SupportForm
template_name = "support/index.html"
def get_context_data(self, **kwargs):
"""Pass along endpoint for support form."""
context = super().get_context_data(**kwargs)
context["SUPPORT_FORM_ENDPOINT"] = settings.SUPPOR... | SupportView |
python | scipy__scipy | scipy/optimize/tests/test_minimize_constrained.py | {
"start": 25187,
"end": 28130
} | class ____:
@pytest.mark.parametrize('bounds, x_opt',
[(Bounds(-np.inf, np.inf), Rosenbrock().x_opt),
(Bounds(-np.inf, -0.8), [-0.8, -0.8]),
(Bounds(3.0, np.inf), [3.0, 9.0]),
(Bounds([3.0, 1.0], ... | TestBoundedNelderMead |
python | celery__celery | t/unit/tasks/test_stamping.py | {
"start": 6728,
"end": 7924
} | class ____(StampingVisitor):
def on_signature(self, actual_sig: Signature, **headers) -> dict:
return {"on_signature": "StringStampingVisitor: on_signature-item1"}
def on_group_start(self, actual_sig: Signature, **headers) -> dict:
return {"on_group_start": "StringStampingVisitor: on_group_star... | StringStampingVisitor |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/protocol24.py | {
"start": 598,
"end": 752
} | class ____:
var1: ClassVar[int]
var2: ClassVar[int]
d: ProtoD = E
# This should generate an error because var2 is the wrong type.
e: ProtoD = F
| F |
python | bokeh__bokeh | src/bokeh/core/property/struct.py | {
"start": 3768,
"end": 4538
} | class ____(SimpleNamespace):
"""
Allow access unnamed struct with attributes and keys.
.. note::
This feature is experimental and may change in the short term.
"""
def __getitem__(self, key: str) -> Any:
return getattr(self, key)
def __setitem__(self, key: str, val: Any) -> No... | struct |
python | kamyu104__LeetCode-Solutions | Python/categorize-box-according-to-criteria.py | {
"start": 52,
"end": 626
} | class ____(object):
def categorizeBox(self, length, width, height, mass):
"""
:type length: int
:type width: int
:type height: int
:type mass: int
:rtype: str
"""
bulky = any(x >= 10**4 for x in (length, width, height)) or length*width*height >= 10**9
... | Solution |
python | kamyu104__LeetCode-Solutions | Python/bag-of-tokens.py | {
"start": 33,
"end": 665
} | class ____(object):
def bagOfTokensScore(self, tokens, P):
"""
:type tokens: List[int]
:type P: int
:rtype: int
"""
tokens.sort()
result, points = 0, 0
left, right = 0, len(tokens)-1
while left <= right:
if P >= tokens[left]:
... | Solution |
python | PyCQA__pylint | pylint/reporters/ureports/nodes.py | {
"start": 4589,
"end": 5315
} | class ____(BaseLayout):
"""Some tabular data.
attributes :
* BaseLayout attributes
* cols : the number of columns of the table (REQUIRED)
* rheaders : the first row's elements are table's header
* cheaders : the first col's elements are table's header
* title : the table's optional title
... | Table |
python | keon__algorithms | tests/test_queues.py | {
"start": 151,
"end": 1781
} | class ____(unittest.TestCase):
"""
Test suite for the Queue data structures.
"""
def test_ArrayQueue(self):
queue = ArrayQueue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
# test __iter__()
it = iter(queue)
self.assertEqual(1, next(it... | TestQueue |
python | getsentry__sentry | src/sentry/releases/endpoints/project_release_details.py | {
"start": 1030,
"end": 7532
} | class ____(ProjectEndpoint, ReleaseAnalyticsMixin):
publish_status = {
"DELETE": ApiPublishStatus.UNKNOWN,
"GET": ApiPublishStatus.UNKNOWN,
"PUT": ApiPublishStatus.UNKNOWN,
}
permission_classes = (ProjectReleasePermission,)
def get(self, request: Request, project, version) -> Re... | ProjectReleaseDetailsEndpoint |
python | jina-ai__jina | tests/integration/network_failures/test_network_failures.py | {
"start": 612,
"end": 29531
} | class ____(Executor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._id = str(uuid.uuid4())
@requests(on='/foo')
def foo(self, docs, *args, **kwargs):
docs[0].text = self._id
def _create_worker_runtime(port, name='', executor=None):
args = _genera... | DummyExec |
python | pytorch__pytorch | torch/_inductor/tiling_utils.py | {
"start": 6788,
"end": 8768
} | class ____:
"""
Normalized reads and writes for nodes in the same FusedSchedulerNode.
"""
index_vars: OrderedSet[sympy.Symbol]
reduce_vars: OrderedSet[sympy.Symbol]
reads: dict[sympy.Expr, OrderedSet[str]]
writes: dict[sympy.Expr, OrderedSet[str]]
var_ranges: dict[sympy.Symbol, int]
@... | FusedNormalizedReadsWrites |
python | davidhalter__jedi | test/completion/descriptors.py | {
"start": 492,
"end": 915
} | class ____(object):
x = RevealAccess(10, 'var "x"')
#? RevealAccess()
x
#? ['just_a_method']
x.just_a_method
y = 5.0
def __init__(self):
#? int()
self.x
#? []
self.just_a_method
#? []
C.just_a_method
m = C()
#? int()
m.x
#? float()
m.y
#? int... | C |
python | Textualize__textual | docs/examples/how-to/layout02.py | {
"start": 354,
"end": 491
} | class ____(Screen):
def compose(self) -> ComposeResult:
yield Header(id="Header")
yield Footer(id="Footer")
| TweetScreen |
python | nedbat__coveragepy | coverage/regions.py | {
"start": 488,
"end": 4500
} | class ____:
"""An ast visitor that will find and track regions of code.
Functions and classes are tracked by name. Results are in the .regions
attribute.
"""
def __init__(self) -> None:
self.regions: list[CodeRegion] = []
self.context: list[Context] = []
def parse_source(self... | RegionFinder |
python | arrow-py__arrow | arrow/locales.py | {
"start": 112079,
"end": 113539
} | class ____(Locale):
names = ["ms", "ms-my", "ms-bn"]
past = "{0} yang lalu"
future = "dalam {0}"
and_word = "dan"
timeframes: ClassVar[Mapping[TimeFrameLiteral, Union[str, Mapping[str, str]]]] = {
"now": "sekarang",
"second": "saat",
"seconds": "{0} saat",
"minute":... | MalayLocale |
python | getsentry__sentry | src/social_auth/backends/__init__.py | {
"start": 14703,
"end": 19136
} | class ____(OAuthAuth):
"""Consumer based mechanism OAuth authentication, fill the needed
parameters to communicate properly with authentication service.
AUTHORIZATION_URL Authorization service url
REQUEST_TOKEN_URL Request token URL
ACCESS_TOKEN_URL Access token URL
... | BaseOAuth1 |
python | ApeWorX__ape | src/ape/exceptions.py | {
"start": 2118,
"end": 2360
} | class ____(ApeException):
"""
Raised when issues occur with local contract.
**NOTE**: This error has nothing to do with on-chain
contract logic errors; it is more about ABI-related
issues and alike.
"""
| ContractDataError |
python | huggingface__transformers | src/transformers/models/glm46v/modular_glm46v.py | {
"start": 1179,
"end": 4839
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`Glm4vModel`]. It is used to instantiate a
GLM-4.6V model according to the specified arguments, defining the model architecture. Instantiating a
configuration with the defaults will yield a similar config... | Glm46VConfig |
python | getsentry__sentry | src/sentry/api/serializers/models/rule.py | {
"start": 1731,
"end": 1806
} | class ____(TypedDict):
id: int
name: str
email: str
| RuleCreatedBy |
python | catalyst-team__catalyst | catalyst/contrib/data/sampler_inbatch.py | {
"start": 7999,
"end": 14153
} | class ____(IInbatchTripletSampler):
"""
This sampler selects hardest triplets based on distance to mean vectors:
anchor is a mean vector of features of i-th class in the batch,
the hardest positive sample is the most distant from anchor sample of
anchor's class, the hardest negative sample is the cl... | HardClusterSampler |
python | huggingface__transformers | src/transformers/models/perceiver/modeling_perceiver.py | {
"start": 15308,
"end": 19778
} | class ____(nn.Module):
"""The Perceiver Encoder: a scalable, fully attentional encoder."""
def __init__(self, config, kv_dim=None):
super().__init__()
self.config = config
# Check that we can use multihead-attention with these shapes.
if config.d_latents % config.num_self_atten... | PerceiverEncoder |
python | spack__spack | lib/spack/spack/vendor/jinja2/bccache.py | {
"start": 9802,
"end": 12748
} | class ____(BytecodeCache):
"""This class implements a bytecode cache that uses a memcache cache for
storing the information. It does not enforce a specific memcache library
(tummy's memcache or cmemcache) but will accept any class that provides
the minimal interface required.
Libraries compatible ... | MemcachedBytecodeCache |
python | vyperlang__vyper | vyper/venom/basicblock.py | {
"start": 3617,
"end": 3979
} | class ____(IROperand):
"""
IRLiteral represents a literal in IR
"""
value: int
def __init__(self, value: int) -> None:
assert isinstance(value, int), value
super().__init__(value)
def __repr__(self) -> str:
if abs(self.value) < 1024:
return str(self.value)
... | IRLiteral |
python | aio-libs__aiohttp | aiohttp/client_exceptions.py | {
"start": 1356,
"end": 1439
} | class ____(Exception):
"""Base class for client connection errors."""
| ClientError |
python | coleifer__peewee | tests/base.py | {
"start": 6574,
"end": 7008
} | class ____(BaseTestCase):
database = db
def setUp(self):
if not self.database.is_closed():
self.database.close()
self.database.connect()
super(DatabaseTestCase, self).setUp()
def tearDown(self):
super(DatabaseTestCase, self).tearDown()
self.database.clos... | DatabaseTestCase |
python | PrefectHQ__prefect | src/integrations/prefect-dbt/prefect_dbt/cloud/exceptions.py | {
"start": 188,
"end": 308
} | class ____(DbtCloudException):
"""Raised when unable to list dbt Cloud run artifacts"""
| DbtCloudListRunArtifactsFailed |
python | pola-rs__polars | py-polars/src/polars/string_cache.py | {
"start": 558,
"end": 5483
} | class ____(contextlib.ContextDecorator):
"""
Context manager for enabling and disabling the global string cache.
:class:`Categorical` columns created under the same global string cache have
the same underlying physical value when string values are equal. This allows the
columns to be concatenated o... | StringCache |
python | pydata__xarray | xarray/core/_typed_ops.py | {
"start": 49534,
"end": 54365
} | class ____:
__slots__ = ()
def _binary_op(
self, other: T_Xarray, f: Callable, reflexive: bool = False
) -> T_Xarray:
raise NotImplementedError
def __add__(self, other: T_Xarray) -> T_Xarray:
return self._binary_op(other, operator.add)
def __sub__(self, other: T_Xarray) ->... | DataArrayGroupByOpsMixin |
python | django__django | tests/force_insert_update/models.py | {
"start": 241,
"end": 318
} | class ____(Counter):
tag = models.CharField(max_length=10)
| InheritedCounter |
python | ray-project__ray | rllib/offline/tests/test_feature_importance.py | {
"start": 210,
"end": 1325
} | class ____(unittest.TestCase):
def setUp(self):
ray.init()
def tearDown(self):
ray.shutdown()
def test_feat_importance_cartpole(self):
config = (
MARWILConfig()
.api_stack(
enable_rl_module_and_learner=False,
enable_env_runner... | TestFeatureImportance |
python | huggingface__transformers | src/transformers/pipelines/object_detection.py | {
"start": 645,
"end": 8346
} | class ____(Pipeline):
"""
Object detection pipeline using any `AutoModelForObjectDetection`. This pipeline predicts bounding boxes of objects
and their classes.
Example:
```python
>>> from transformers import pipeline
>>> detector = pipeline(model="facebook/detr-resnet-50")
>>> detect... | ObjectDetectionPipeline |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/validation/rules/lone_anonymous_operation.py | {
"start": 97,
"end": 897
} | class ____(ValidationRule):
__slots__ = 'operation_count',
def __init__(self, context):
self.operation_count = 0
super(LoneAnonymousOperation, self).__init__(context)
def enter_Document(self, node, key, parent, path, ancestors):
self.operation_count = \
sum(1 for defini... | LoneAnonymousOperation |
python | huggingface__transformers | tests/models/mpt/test_modeling_mpt.py | {
"start": 13651,
"end": 17326
} | class ____(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
MptModel,
MptForCausalLM,
MptForSequenceClassification,
MptForTokenClassification,
MptForQuestionAnswering,
)
if is... | MptModelTest |
python | jamielennox__requests-mock | tests/test_matcher.py | {
"start": 684,
"end": 13704
} | class ____(base.TestCase):
def match(self,
target,
url,
matcher_method='GET',
request_method='GET',
complete_qs=False,
headers=None,
request_data=None,
request_headers={},
additional_matche... | TestMatcher |
python | PrefectHQ__prefect | src/prefect/server/utilities/leasing.py | {
"start": 513,
"end": 2468
} | class ____(Protocol[T]):
async def create_lease(
self, resource_ids: list[UUID], ttl: timedelta, metadata: T | None = None
) -> ResourceLease[T]:
"""
Create a new resource lease.
Args:
resource_ids: The IDs of the resources that the lease is associated with.
... | LeaseStorage |
python | apache__airflow | airflow-core/src/airflow/ti_deps/deps/trigger_rule_dep.py | {
"start": 1817,
"end": 3550
} | class ____(NamedTuple):
"""
States of the upstream tis for a specific ti.
This is used to determine whether the specific ti can run in this iteration.
"""
success: int
skipped: int
failed: int
upstream_failed: int
removed: int
done: int
success_setup: int
skipped_setup:... | _UpstreamTIStates |
python | wandb__wandb | wandb/automations/actions.py | {
"start": 2514,
"end": 2793
} | class ____(NotificationActionFields, frozen=False):
action_type: Literal[ActionType.NOTIFICATION] = ActionType.NOTIFICATION
integration: _SlackIntegrationStub
title: Optional[str]
message: Optional[str]
severity: Optional[AlertSeverity]
| SavedNotificationAction |
python | pandas-dev__pandas | pandas/tests/io/parser/conftest.py | {
"start": 2372,
"end": 9144
} | class ____(BaseParser):
engine = "pyarrow"
float_precision_choices = [None]
@pytest.fixture
def csv_dir_path(datapath):
"""
The directory path to the data files needed for parser tests.
"""
return datapath("io", "parser", "data")
@pytest.fixture
def csv1(datapath):
"""
The path to th... | PyArrowParser |
python | huggingface__transformers | tests/models/decision_transformer/test_modeling_decision_transformer.py | {
"start": 6362,
"end": 9272
} | class ____(unittest.TestCase):
@slow
def test_autoregressive_prediction(self):
"""
An integration test that performs autoregressive prediction of state, action and return
from a sequence of state, actions and returns. Test is performed over two timesteps.
"""
NUM_STEPS ... | DecisionTransformerModelIntegrationTest |
python | run-llama__llama_index | llama-index-core/llama_index/core/utils.py | {
"start": 3677,
"end": 5977
} | class ____(Protocol):
def encode(self, text: str, *args: Any, **kwargs: Any) -> List[Any]: ...
def set_global_tokenizer(tokenizer: Union[Tokenizer, Callable[[str], list]]) -> None:
import llama_index.core
if isinstance(tokenizer, Tokenizer):
llama_index.core.global_tokenizer = tokenizer.encode
... | Tokenizer |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/roles.py | {
"start": 6258,
"end": 6314
} | class ____(ReturnsRowsRole):
__slots__ = ()
| HasCTERole |
python | sympy__sympy | sympy/physics/optics/gaussopt.py | {
"start": 1322,
"end": 4657
} | class ____(MutableDenseMatrix):
"""
Base class for a Ray Transfer Matrix.
It should be used if there is not already a more specific subclass mentioned
in See Also.
Parameters
==========
parameters :
A, B, C and D or 2x2 matrix (Matrix(2, 2, [A, B, C, D]))
Examples
=======... | RayTransferMatrix |
python | Unity-Technologies__ml-agents | ml-agents/mlagents/trainers/torch_entities/attention.py | {
"start": 925,
"end": 4023
} | class ____(torch.nn.Module):
NEG_INF = -1e6
def __init__(self, embedding_size: int, num_heads: int):
"""
Multi Head Attention module. We do not use the regular Torch implementation since
Sentis does not support some operators it uses.
Takes as input to the forward method 3 tenso... | MultiHeadAttention |
python | openai__openai-python | src/openai/types/beta/chatkit/chat_session_automatic_thread_titling.py | {
"start": 172,
"end": 297
} | class ____(BaseModel):
enabled: bool
"""Whether automatic thread titling is enabled."""
| ChatSessionAutomaticThreadTitling |
python | ray-project__ray | python/ray/dashboard/modules/job/job_head.py | {
"start": 6548,
"end": 28729
} | class ____(SubprocessModule):
"""Runs on the head node of a Ray cluster and handles Ray Jobs APIs.
NOTE(architkulkarni): Please keep this class in sync with the OpenAPI spec at
`doc/source/cluster/running-applications/job-submission/openapi.yml`.
We currently do not automatically check that the OpenAPI... | JobHead |
python | django__django | tests/model_fields/models.py | {
"start": 14996,
"end": 15060
} | class ____(models.Model):
field = models.UUIDField()
| UUIDModel |
python | PrefectHQ__prefect | src/prefect/client/schemas/actions.py | {
"start": 2616,
"end": 5274
} | class ____(ActionBaseModel):
schedule: SCHEDULE_TYPES = Field(
default=..., description="The schedule for the deployment."
)
active: bool = Field(
default=True, description="Whether or not the schedule is active."
)
max_scheduled_runs: Optional[PositiveInteger] = Field(
defau... | DeploymentScheduleCreate |
python | ray-project__ray | rllib/algorithms/dreamerv3/tests/test_dreamerv3.py | {
"start": 1000,
"end": 12144
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
ray.init()
@classmethod
def tearDownClass(cls):
ray.shutdown()
def test_dreamerv3_compilation(self):
"""Test whether DreamerV3 can be built with all frameworks."""
# Build a DreamerV3Config object.
... | TestDreamerV3 |
python | huggingface__transformers | tests/models/nougat/test_image_processing_nougat.py | {
"start": 3972,
"end": 15188
} | class ____(ImageProcessingTestMixin, unittest.TestCase):
image_processing_class = NougatImageProcessor if is_vision_available() else None
fast_image_processing_class = NougatImageProcessorFast if is_torchvision_available() else None
def setUp(self):
super().setUp()
self.image_processor_test... | NougatImageProcessingTest |
python | apache__airflow | task-sdk/src/airflow/sdk/api/datamodels/_generated.py | {
"start": 7456,
"end": 7872
} | class ____(BaseModel):
"""
Schema for updating TaskInstance to up_for_retry.
"""
model_config = ConfigDict(
extra="forbid",
)
state: Annotated[Literal["up_for_retry"] | None, Field(title="State")] = "up_for_retry"
end_date: Annotated[AwareDatetime, Field(title="End Date")]
rende... | TIRetryStatePayload |
python | pytorch__pytorch | torch/_inductor/autoheuristic/autoheuristic_utils.py | {
"start": 607,
"end": 1308
} | class ____:
"""
AHOperation can be used to augment the data collected by AutoHeuristic.
One might for example store features like m, k, n, but also want to use
features like m*n, or k*n, to learn a heuristic. Instead of storing features
that can be created from the collected data, one can use AHOper... | AHOperation |
python | numpy__numpy | numpy/_core/tests/test_unicode.py | {
"start": 12371,
"end": 12521
} | class ____(ByteorderValues):
"""Check the byteorder in unicode (size 2, UCS2 values)"""
ulen = 2
ucs_value = ucs2_value
| TestByteorder_2_UCS2 |
python | pyinstaller__pyinstaller | tests/unit/test_hookutils.py | {
"start": 1819,
"end": 2642
} | class ____(object):
# Verify that removing a suffix from an empty string is OK.
def test_empty_string(self):
assert '' == hookutils.remove_suffix('', 'suffix')
# An empty suffix should pass the string through unmodified.
def test_emptystr_unmodif(self):
assert 'test' == hookutils.remove... | TestRemoveSuffix |
python | pandas-dev__pandas | pandas/errors/__init__.py | {
"start": 24254,
"end": 25417
} | class ____(Exception):
"""
Exception is raised when trying to index and there is a mismatch in dimensions.
Raised by properties like :attr:`.pandas.DataFrame.iloc` when
an indexer is out of bounds or :attr:`.pandas.DataFrame.loc` when its index is
unalignable to the frame index.
See Also
-... | IndexingError |
python | apache__airflow | task-sdk/src/airflow/sdk/definitions/asset/decorators.py | {
"start": 5036,
"end": 5389
} | class ____(Asset):
"""
Asset representation from decorating a function with ``@asset``.
:meta private:
"""
_function: Callable
_source: asset
def __attrs_post_init__(self) -> None:
with self._source.create_dag(default_dag_id=self.name):
_instantiate_task(self)
@attrs... | AssetDefinition |
python | getsentry__sentry | src/sentry/replays/usecases/query/conditions/error_ids.py | {
"start": 1153,
"end": 2416
} | class ____(ComputedBase):
"""Sum of error ids array condition visitor."""
@staticmethod
def visit_eq(value: UUID) -> Condition:
return contains(ErrorIdsArray.visit_eq(value))
@staticmethod
def visit_neq(value: UUID) -> Condition:
return does_not_contain(ErrorIdsArray.visit_eq(value... | SumOfErrorIdsArray |
python | getsentry__sentry | src/sentry/workflow_engine/migrations/0078_workflow_fire_history_date_index.py | {
"start": 155,
"end": 1580
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# o... | Migration |
python | miyuchina__mistletoe | mistletoe/contrib/jira_renderer.py | {
"start": 1265,
"end": 8435
} | class ____(BaseRenderer):
"""
JIRA renderer class.
See mistletoe.base_renderer module for more info.
"""
def __init__(self, *extras):
"""
Args:
extras (list): allows subclasses to add even more custom tokens.
"""
self.listTokens = []
self.lastChil... | JiraRenderer |
python | scrapy__scrapy | scrapy/downloadermiddlewares/httpcompression.py | {
"start": 1529,
"end": 8344
} | class ____:
"""This middleware allows compressed (gzip, deflate) traffic to be
sent/received from websites"""
def __init__(
self,
stats: StatsCollector | None = None,
*,
crawler: Crawler | None = None,
):
if not crawler:
self.stats = stats
... | HttpCompressionMiddleware |
python | airbytehq__airbyte | airbyte-integrations/connectors/destination-deepset/destination_deepset/models.py | {
"start": 641,
"end": 1319
} | class ____(BaseModel):
"""Configuration for the deepset cloud destination."""
model_config = ConfigDict(extra="allow")
api_key: str = Field(title="API Key", description="Your deepset cloud API key", min_length=8)
base_url: str = Field(
default="https://api.cloud.deepset.ai",
title="Bas... | DeepsetCloudConfig |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_privacy_urls.py | {
"start": 8353,
"end": 9237
} | class ____(ProjectMixin):
request_data = {
"/projects/": {},
"/projects/search/autocomplete/": {"data": {"term": "pip"}},
"/projects/autocomplete/version/pip/": {"data": {"term": "pip"}},
"/projects/pip/autocomplete/file/": {"data": {"term": "pip"}},
}
response_data = {
... | PublicProjectMixin |
python | walkccc__LeetCode | solutions/1700. Number of Students Unable to Eat Lunch/1700.py | {
"start": 0,
"end": 290
} | class ____:
def countStudents(self, students: list[int], sandwiches: list[int]) -> int:
count = collections.Counter(students)
for i, sandwich in enumerate(sandwiches):
if count[sandwich] == 0:
return len(sandwiches) - i
count[sandwich] -= 1
return 0
| Solution |
python | sympy__sympy | sympy/physics/quantum/sho1d.py | {
"start": 1169,
"end": 5382
} | class ____(SHOOp):
"""The Raising Operator or a^dagger.
When a^dagger acts on a state it raises the state up by one. Taking
the adjoint of a^dagger returns 'a', the Lowering Operator. a^dagger
can be rewritten in terms of position and momentum. We can represent
a^dagger as a matrix, which will be i... | RaisingOp |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 34780,
"end": 34943
} | class ____(BoringModel):
def on_after_backward(self):
if self.current_epoch == 1:
raise RuntimeError("Trouble!")
| TroubledModelOnAfterBackward |
python | astropy__astropy | astropy/table/ndarray_mixin.py | {
"start": 139,
"end": 599
} | class ____(ParentDtypeInfo):
_represent_as_dict_primary_data = "data"
def _represent_as_dict(self):
"""Represent Column as a dict that can be serialized."""
col = self._parent
out = {"data": col.view(np.ndarray)}
return out
def _construct_from_dict(self, map):
"""Co... | NdarrayMixinInfo |
python | huggingface__transformers | tests/models/timm_backbone/test_modeling_timm_backbone.py | {
"start": 2816,
"end": 10408
} | class ____(ModelTesterMixin, BackboneTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (TimmBackbone,) if is_torch_available() else ()
pipeline_model_mapping = {"feature-extraction": TimmBackbone} if is_torch_available() else {}
test_resize_embeddings = False
has_attentions = Fa... | TimmBackboneModelTest |
python | dagster-io__dagster | python_modules/dagster/dagster/_core/storage/base_storage.py | {
"start": 349,
"end": 1337
} | class ____(ABC, MayHaveInstanceWeakref[T_DagsterInstance]):
"""Abstract base class for Dagster persistent storage, for reading and writing data for runs,
events, and schedule/sensor state.
Users should not directly instantiate concrete subclasses of this class; they are instantiated
by internal machine... | DagsterStorage |
python | viewflow__viewflow | tests/contrib/test_contrib_auth.py | {
"start": 263,
"end": 3218
} | class ____(TestCase):
def setUp(self):
self.admin = User.objects.create_superuser("admin", "admin@admin.com", "admin")
self.user = User.objects.create_user("user", "user@user.com", "user")
self.validator = html5lib.HTMLParser(strict=True)
@tag("integration")
def test_change_user_ava... | Test |
python | doocs__leetcode | solution/2100-2199/2131.Longest Palindrome by Concatenating Two Letter Words/Solution.py | {
"start": 0,
"end": 364
} | class ____:
def longestPalindrome(self, words: List[str]) -> int:
cnt = Counter(words)
ans = x = 0
for k, v in cnt.items():
if k[0] == k[1]:
x += v & 1
ans += v // 2 * 2 * 2
else:
ans += min(v, cnt[k[::-1]]) * 2
... | Solution |
python | huggingface__transformers | examples/modular-transformers/modeling_dummy_bert.py | {
"start": 1597,
"end": 5644
} | class ____(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings."""
def __init__(self, config):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
self.position_embeddings = nn.E... | DummyBertEmbeddings |
python | networkx__networkx | networkx/algorithms/centrality/tests/test_closeness_centrality.py | {
"start": 6058,
"end": 8728
} | class ____:
@staticmethod
def pick_add_edge(G):
u = nx.utils.arbitrary_element(G)
possible_nodes = set(G) - (set(G.neighbors(u)) | {u})
v = nx.utils.arbitrary_element(possible_nodes)
return (u, v)
@staticmethod
def pick_remove_edge(G):
u = nx.utils.arbitrary_elem... | TestIncrementalClosenessCentrality |
python | cython__cython | Cython/Compiler/StringEncoding.py | {
"start": 66,
"end": 677
} | class ____:
"""Assemble a unicode string.
"""
def __init__(self):
self.chars = []
def append(self, characters):
assert isinstance(characters, str), f"Expected str, got {type(characters)}"
self.chars.append(characters)
def append_charval(self, char_number):
self.char... | UnicodeLiteralBuilder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.