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 | pytorch__pytorch | test/distributed/tensor/test_dtensor_export.py | {
"start": 1525,
"end": 1964
} | class ____(torch.nn.Module):
"""Simple model that uses einsum with DTensor inputs and returns DTensor."""
def __init__(self):
super().__init__()
self.placement = None
def forward(self, x, y, z):
result = torch.einsum("bsh,hd->bsd", x, y)
self.placement = result.placements[0... | EinsumModel |
python | coleifer__peewee | peewee.py | {
"start": 40166,
"end": 40362
} | class ____(WrappedNode):
def __init__(self, node, dest):
super(BindTo, self).__init__(node)
self.dest = dest
def __sql__(self, ctx):
return ctx.sql(self.node)
| BindTo |
python | django-compressor__django-compressor | compressor/filters/closure.py | {
"start": 85,
"end": 311
} | class ____(CompilerFilter):
command = "{binary} {args}"
options = (
("binary", settings.COMPRESS_CLOSURE_COMPILER_BINARY),
("args", settings.COMPRESS_CLOSURE_COMPILER_ARGUMENTS),
)
| ClosureCompilerFilter |
python | pytorch__pytorch | torch/cuda/amp/autocast_mode.py | {
"start": 353,
"end": 3477
} | class ____(torch.amp.autocast_mode.autocast):
r"""See :class:`torch.autocast`.
``torch.cuda.amp.autocast(args...)`` is deprecated. Please use ``torch.amp.autocast("cuda", args...)`` instead.
"""
# TODO: remove this conditional once we stop supporting Python < 3.13
# Prior to Python 3.13, inspect.s... | autocast |
python | huggingface__transformers | tests/models/glm4v_moe/test_modeling_glm4v_moe.py | {
"start": 6582,
"end": 11234
} | class ____(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
all_model_classes = (Glm4vMoeModel, Glm4vMoeForConditionalGeneration) if is_torch_available() else ()
model_split_percents = [0.7, 0.9] # model too big to split at 0.5
_is_composite = True
def setUp(self):
self.model_test... | Glm4vMoeModelTest |
python | tensorflow__tensorflow | tensorflow/python/keras/utils/version_utils.py | {
"start": 1727,
"end": 2085
} | class ____(object):
"""Chooses between Keras v1 and v2 Model class."""
def __new__(cls, *args, **kwargs): # pylint: disable=unused-argument
use_v2 = should_use_v2()
cls = swap_class(cls, training.Model, training_v1.Model, use_v2) # pylint: disable=self-cls-assignment
return super(ModelVersionSelector... | ModelVersionSelector |
python | encode__django-rest-framework | tests/test_pagination.py | {
"start": 38817,
"end": 38898
} | class ____(models.Model):
created = models.IntegerField()
| CursorPaginationModel |
python | falconry__falcon | tests/test_after_hooks.py | {
"start": 4178,
"end": 4354
} | class ____:
@falcon.after(fluffiness_in_the_head, 'fluffy')
def on_get(self, req, resp, field1, field2):
self.fields = (field1, field2)
| ClassResourceWithURIFields |
python | eth-brownie__brownie | brownie/network/multicall.py | {
"start": 834,
"end": 925
} | class ____:
calldata: Tuple[str, bytes]
decoder: FunctionType
readable: str
| Call |
python | readthedocs__readthedocs.org | readthedocs/organizations/views/private.py | {
"start": 7634,
"end": 11542
} | class ____(PrivateViewMixin, OrganizationMixin, ListView):
"""Display security logs related to this organization."""
model = AuditLog
template_name = "organizations/security_log.html"
feature_type = TYPE_AUDIT_LOGS
def get(self, request, *args, **kwargs):
download_data = request.GET.get("d... | OrganizationSecurityLog |
python | django__django | tests/settings_tests/tests.py | {
"start": 17033,
"end": 18078
} | class ____(SimpleTestCase):
"""
Make sure settings that should be lists or tuples throw
ImproperlyConfigured if they are set to a string instead of a list or
tuple.
"""
list_or_tuple_settings = (
"ALLOWED_HOSTS",
"INSTALLED_APPS",
"TEMPLATE_DIRS",
"LOCALE_PATHS",... | TestListSettings |
python | RaRe-Technologies__gensim | gensim/topic_coherence/text_analysis.py | {
"start": 8869,
"end": 10294
} | class ____(UsesDictionary):
"""Gather some stats about relevant terms of a corpus by iterating over windows of texts."""
def __init__(self, relevant_ids, dictionary):
"""
Parameters
----------
relevant_ids : set of int
Relevant id
dictionary : :class:`~gensi... | WindowedTextsAnalyzer |
python | run-llama__llama_index | llama-index-integrations/voice_agents/llama-index-voice-agents-openai/llama_index/voice_agents/openai/types.py | {
"start": 2578,
"end": 3019
} | class ____(BaseVoiceAgentEvent):
call_id: str
name: Optional[str] = Field(default=None)
arguments: Union[str, Dict[str, Any]]
item_id: str
@model_validator(mode="after")
def validate_arguments(self) -> Self:
try:
self.arguments = json.loads(self.arguments)
except jso... | FunctionCallDoneEvent |
python | kamyu104__LeetCode-Solutions | Python/put-boxes-into-the-warehouse-i.py | {
"start": 33,
"end": 506
} | class ____(object):
def maxBoxesInWarehouse(self, boxes, warehouse):
"""
:type boxes: List[int]
:type warehouse: List[int]
:rtype: int
"""
boxes.sort(reverse=True)
result = 0
for h in boxes:
if h > warehouse[result]:
continu... | Solution |
python | prabhupant__python-ds | data_structures/binary_trees/continuous_tree.py | {
"start": 92,
"end": 923
} | class ____:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def continuous(root):
# Can be continuous if
# 1. Root is none
# 2. Both left and right STs are none
# 3. If left ST is none, check for right
# 4. If right ST is none, check for lef... | Node |
python | Lightning-AI__lightning | src/lightning/pytorch/trainer/connectors/logger_connector/result.py | {
"start": 11572,
"end": 20363
} | class ____(dict):
"""Collection (dictionary) of :class:`~lightning.pytorch.trainer.connectors.logger_connector.result._ResultMetric`
Example::
# you can log to a specific collection.
# arguments: fx, key, value, metadata
result = _ResultCollection(training=True)
result.log('tr... | _ResultCollection |
python | google__python-fire | fire/test_components.py | {
"start": 8404,
"end": 8542
} | class ____(dict):
"""A subclass of dict, for testing purposes."""
# An example subdict.
SUBDICT = Subdict({1: 2, 'red': 'blue'})
| Subdict |
python | mlflow__mlflow | tests/pyfunc/test_responses_agent.py | {
"start": 3307,
"end": 7846
} | class ____(ResponsesAgent):
def load_context(self, context):
predict_path = pathlib.Path(context.artifacts["predict_fn"])
self.predict_fn = pickle.loads(predict_path.read_bytes())
def predict(self, request: ResponsesAgentRequest) -> ResponsesAgentResponse:
return ResponsesAgentResponse(... | ResponsesAgentWithContext |
python | apache__airflow | helm-tests/tests/helm_tests/airflow_aux/test_database_cleanup.py | {
"start": 914,
"end": 2453
} | class ____:
"""Tests database cleanup deployments."""
def test_should_have_a_schedule_with_defaults(self):
doc = render_chart(
values={
"databaseCleanup": {"enabled": True},
},
show_only=["templates/database-cleanup/database-cleanup-cronjob.yaml"],
... | TestDatabaseCleanupDeployment |
python | pandas-dev__pandas | pandas/tests/indexes/test_base.py | {
"start": 863,
"end": 47749
} | class ____:
@pytest.fixture
def simple_index(self) -> Index:
return Index(list("abcde"))
def test_can_hold_identifiers(self, simple_index):
index = simple_index
key = index[0]
assert index._can_hold_identifiers_and_holds_name(key) is True
@pytest.mark.parametrize("index... | TestIndex |
python | walkccc__LeetCode | solutions/1349. Maximum Students Taking Exam/1349.py | {
"start": 0,
"end": 1122
} | class ____:
def maxStudents(self, seats: list[list[str]]) -> int:
m = len(seats)
n = len(seats[0])
DIRS = ((-1, -1), (0, -1), (1, -1), (-1, 1), (0, 1), (1, 1))
seen = [[0] * n for _ in range(m)]
match = [[-1] * n for _ in range(m)]
def dfs(i: int, j: int, sessionId: int) -> int:
for dx,... | Solution |
python | qdrant__qdrant-client | qdrant_client/local/qdrant_local.py | {
"start": 798,
"end": 39501
} | class ____(QdrantBase):
"""
Everything Qdrant server can do, but locally.
Use this implementation to run vector search without running a Qdrant server.
Everything that works with local Qdrant will work with server Qdrant as well.
Use for small-scale data, demos, and tests.
If you need more spe... | QdrantLocal |
python | rq__rq | tests/test_worker_pool.py | {
"start": 549,
"end": 5809
} | class ____(RQTestCase):
def test_queues(self):
"""Test queue parsing"""
pool = WorkerPool(['default', 'foo'], connection=self.connection)
self.assertEqual(
set(pool.queues), {Queue('default', connection=self.connection), Queue('foo', connection=self.connection)}
)
# ... | TestWorkerPool |
python | django__django | django/db/models/query.py | {
"start": 1537,
"end": 2925
} | class ____:
def __init__(
self, queryset, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE
):
self.queryset = queryset
self.chunked_fetch = chunked_fetch
self.chunk_size = chunk_size
async def _async_generator(self):
# Generators don't actually start running u... | BaseIterable |
python | pypa__warehouse | warehouse/packaging/services.py | {
"start": 2224,
"end": 2289
} | class ____(DevelopmentModeWarning):
pass
| InsecureStorageWarning |
python | getsentry__sentry | src/sentry/hybridcloud/rpc/resolvers.py | {
"start": 1380,
"end": 1763
} | class ____(RegionResolutionStrategy):
"""Resolve from an `int` parameter representing an organization ID."""
parameter_name: str = "organization_id"
def resolve(self, arguments: ArgumentDict) -> Region:
organization_id = arguments[self.parameter_name]
return self._get_from_mapping(organiza... | ByOrganizationId |
python | pyca__cryptography | tests/hazmat/primitives/test_rsa.py | {
"start": 1654,
"end": 5087
} | class ____(padding.MGF):
_salt_length = 0
_algorithm = hashes.SHA256()
def _check_fips_key_length(backend, private_key):
if (
backend._fips_enabled
and private_key.key_size < backend._fips_rsa_min_key_size
):
pytest.skip(f"Key size not FIPS compliant: {private_key.key_size}")
... | DummyMGF |
python | getsentry__sentry | src/sentry/preprod/api/endpoints/project_preprod_list_builds.py | {
"start": 964,
"end": 6763
} | class ____(ProjectEndpoint):
owner = ApiOwner.EMERGE_TOOLS
publish_status = {
"GET": ApiPublishStatus.EXPERIMENTAL,
}
def get(self, request: Request, project: Project) -> Response:
"""
List preprod builds for a project
````````````````````````````````````````````````````... | ProjectPreprodListBuildsEndpoint |
python | kubernetes-client__python | kubernetes/client/models/v1_selectable_field.py | {
"start": 383,
"end": 4462
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attri... | V1SelectableField |
python | allegroai__clearml | clearml/utilities/plotlympl/mplexporter/renderers/base.py | {
"start": 362,
"end": 16182
} | class ____(object):
@staticmethod
def ax_zoomable(ax: Any) -> bool:
return bool(ax and ax.get_navigate())
@staticmethod
def ax_has_xgrid(ax: Any) -> bool:
if not ax:
return False
_gridOnMajor = ax.xaxis._gridOnMajor if hasattr(ax.xaxis, "_gridOnMajor") else ax.xaxis.... | Renderer |
python | jazzband__tablib | tests/test_tablib.py | {
"start": 56057,
"end": 58291
} | class ____(BaseTestCase):
def test_json_format_detect(self):
"""Test JSON format detection."""
_json = StringIO('[{"last_name": "Adams","age": 90,"first_name": "John"}]')
_bunk = StringIO(
'¡¡¡¡¡¡¡¡£™∞¢£§∞§¶•¶ª∞¶•ªº••ª–º§•†•§º¶•†¥ª–º•§ƒø¥¨©πƒø†ˆ¥ç©¨√øˆ¥≈†ƒ¥ç©ø¨çˆ¥ƒçø¶'
)... | JSONTests |
python | scipy__scipy | benchmarks/benchmarks/go_benchmark_functions/go_funcs_Y.py | {
"start": 74,
"end": 1540
} | class ____(Benchmark):
r"""
Yao-Liu 4 objective function.
This class defines the Yao-Liu function 4 [1]_ global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{YaoLiu04}}(x) = {max}_i \left\{ \left | x_i \right | ,
... | YaoLiu04 |
python | sympy__sympy | sympy/core/symbol.py | {
"start": 6305,
"end": 14086
} | class ____(AtomicExpr, Boolean): # type: ignore
"""
Symbol class is used to create symbolic variables.
Explanation
===========
Symbolic variables are placeholders for mathematical symbols that can represent numbers, constants, or any other mathematical entities and can be used in mathematical expr... | Symbol |
python | getsentry__sentry | tests/sentry/integrations/test_manager.py | {
"start": 198,
"end": 437
} | class ____(TestCase):
def test_excludes_non_visible_integrations(self) -> None:
# The VSTSExtension is not visible
assert all(not isinstance(i, VstsExtensionIntegrationProvider) for i in integrations.all())
| TestIntegrations |
python | pytorch__pytorch | benchmarks/dynamo/genai_layers/kernels.py | {
"start": 7071,
"end": 9062
} | class ____(BenchmarkKernel):
def __init__(self, script_args):
super().__init__(script_args)
self.available_backends = ["eager", "compiled", "quack", "liger"]
def get_shapes(self) -> tuple[tuple[int, ...], ...]:
return (
(32768, 256),
(32768, 512),
(32... | SoftmaxForward |
python | scikit-learn__scikit-learn | sklearn/gaussian_process/kernels.py | {
"start": 17447,
"end": 17778
} | class ____:
"""Mixin for kernels which operate on generic objects such as variable-
length sequences, trees, and graphs.
.. versionadded:: 0.22
"""
@property
def requires_vector_input(self):
"""Whether the kernel works only on fixed-length feature vectors."""
return False
| GenericKernelMixin |
python | kamyu104__LeetCode-Solutions | Python/license-key-formatting.py | {
"start": 29,
"end": 446
} | class ____(object):
def licenseKeyFormatting(self, S, K):
"""
:type S: str
:type K: int
:rtype: str
"""
result = []
for i in reversed(xrange(len(S))):
if S[i] == '-':
continue
if len(result) % (K + 1) == K:
... | Solution |
python | sqlalchemy__sqlalchemy | test/dialect/mysql/test_types.py | {
"start": 26913,
"end": 27942
} | class ____(fixtures.TestBase):
__requires__ = ("json_type",)
__only_on__ = "mysql", "mariadb"
__backend__ = True
@testing.requires.reflects_json_type
def test_reflection(self, metadata, connection):
Table("mysql_json", metadata, Column("foo", mysql.JSON))
metadata.create_all(connect... | JSONTest |
python | run-llama__llama_index | llama-index-integrations/vector_stores/llama-index-vector-stores-timescalevector/llama_index/vector_stores/timescalevector/base.py | {
"start": 596,
"end": 751
} | class ____(enum.Enum):
"""Enumerator for the supported Index types."""
TIMESCALE_VECTOR = 1
PGVECTOR_IVFFLAT = 2
PGVECTOR_HNSW = 3
| IndexType |
python | pytorch__pytorch | test/quantization/core/test_workflow_module.py | {
"start": 43348,
"end": 51011
} | class ____(QuantizationTestCase):
def test_observers_preserve_buffers(self):
"""
Tests that observers only modify buffers in place. Note: this is important
because nn.DataParallel depends on this assumption to work correctly.
However, DataParallel does not expose IDs of the replicas... | TestDistributed |
python | PrefectHQ__prefect | src/prefect/server/task_queue.py | {
"start": 375,
"end": 2922
} | class ____:
_task_queues: Dict[str, Self] = {}
default_scheduled_max_size: int = (
PREFECT_TASK_SCHEDULING_MAX_SCHEDULED_QUEUE_SIZE.value()
)
default_retry_max_size: int = PREFECT_TASK_SCHEDULING_MAX_RETRY_QUEUE_SIZE.value()
_queue_size_configs: Dict[str, Tuple[int, int]] = {}
task_ke... | TaskQueue |
python | run-llama__llama_index | llama-index-integrations/readers/llama-index-readers-github/llama_index/readers/github/issues/github_client.py | {
"start": 693,
"end": 8972
} | class ____:
"""
An asynchronous client for interacting with the GitHub API for issues.
The client supports two authentication methods:
1. Personal Access Token (PAT) - passed as github_token or via GITHUB_TOKEN env var
2. GitHub App - passed as github_app_auth parameter
Examples:
>>> #... | GitHubIssuesClient |
python | matplotlib__matplotlib | lib/matplotlib/_mathtext.py | {
"start": 20154,
"end": 25571
} | class ____(TruetypeFonts):
"""
An abstract base class for handling Unicode fonts.
While some reasonably complete Unicode fonts (such as DejaVu) may
work in some situations, the only Unicode font I'm aware of with a
complete set of math symbols is STIX.
This class will "fallback" on the Bakoma ... | UnicodeFonts |
python | pypa__warehouse | tests/unit/email/test_init.py | {
"start": 11252,
"end": 17457
} | class ____:
@pytest.mark.parametrize("delete_user", [True, False])
def test_send_email_success(self, delete_user, db_session, monkeypatch):
class FakeMailSender:
def __init__(self):
self.emails = []
def send(self, recipient, msg):
self.emails.appe... | TestSendEmail |
python | apache__thrift | lib/py/src/server/TServer.py | {
"start": 4357,
"end": 5998
} | class ____(TServer):
"""Threaded server that spawns a new thread per each connection."""
def __init__(self, *args, **kwargs):
TServer.__init__(self, *args)
self.daemon = kwargs.get("daemon", False)
def serve(self):
self.serverTransport.listen()
while True:
try:
... | TThreadedServer |
python | tiangolo__fastapi | docs_src/pydantic_v1_in_v2/tutorial002_an.py | {
"start": 90,
"end": 284
} | class ____(BaseModel):
name: str
description: Union[str, None] = None
size: float
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item) -> Item:
return item
| Item |
python | pyinstaller__pyinstaller | tests/unit/test_modulegraph/test_compiled_modules.py | {
"start": 98,
"end": 2267
} | class ____(unittest.TestCase):
def setUp(self):
self.base_dir = os.path.join(
os.path.dirname(__file__),
'testpkg-compiled')
self.compiled_dir = os.path.join(
self.base_dir, 'compiled')
self.source_dir = os.path.join(
self.base_... | CompiledModuleTests |
python | wandb__wandb | wandb/vendor/graphql-core-1.1/wandb_graphql/type/definition.py | {
"start": 3461,
"end": 6943
} | class ____(GraphQLType):
"""Object Type Definition
Almost all of the GraphQL types you define will be object types.
Object types have a name, but most importantly describe their fields.
Example:
AddressType = GraphQLObjectType('Address', {
'street': GraphQLField(GraphQLString),
... | GraphQLObjectType |
python | apache__airflow | providers/airbyte/tests/unit/airbyte/sensors/test_airbyte.py | {
"start": 1135,
"end": 4240
} | class ____:
task_id = "task-id"
airbyte_conn_id = "airbyte-conn-test"
job_id = 1
timeout = 120
def get_job(self, status):
response = mock.Mock()
response.job_response = JobResponse(
connection_id="connection-mock",
job_id=self.job_id,
start_time="... | TestAirbyteJobSensor |
python | jmcnamara__XlsxWriter | xlsxwriter/exceptions.py | {
"start": 1287,
"end": 1402
} | class ____(XlsxFileError):
"""Filesize would require ZIP64 extensions. Use workbook.use_zip64()."""
| FileSizeError |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDictClosed6.py | {
"start": 248,
"end": 303
} | class ____(TypedDict, extra_items=int):
pass
| IntDict1 |
python | huggingface__transformers | src/transformers/pipelines/image_feature_extraction.py | {
"start": 731,
"end": 4794
} | class ____(Pipeline):
"""
Image feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base
transformer, which can be used as features in downstream tasks.
Example:
```python
>>> from transformers import pipeline
>>> extractor = pipeline(model="g... | ImageFeatureExtractionPipeline |
python | readthedocs__readthedocs.org | readthedocs/search/documents.py | {
"start": 1048,
"end": 2279
} | class ____(RTDDocTypeMixin, Document):
"""Document representation of a Project."""
# Metadata
url = fields.TextField(attr="get_absolute_url")
users = fields.NestedField(
properties={
"username": fields.TextField(),
"id": fields.IntegerField(),
}
)
languag... | ProjectDocument |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_builtins/A003.py | {
"start": 332,
"end": 500
} | class ____:
@staticmethod
def property(f):
return f
id = 1
@[property][0]
def f(self, x=[id]):
return x
bin = 2
foo = [bin]
| C |
python | Lightning-AI__lightning | src/lightning/fabric/loggers/logger.py | {
"start": 4095,
"end": 4498
} | class ____:
"""Dummy experiment."""
def nop(self, *args: Any, **kw: Any) -> None:
pass
def __getattr__(self, _: Any) -> Callable:
return self.nop
def __getitem__(self, idx: int) -> "_DummyExperiment":
# enables self.logger.experiment[0].add_image(...)
return self
... | _DummyExperiment |
python | ray-project__ray | python/ray/tests/test_logging_2.py | {
"start": 1394,
"end": 3177
} | class ____:
def __init__(self):
pass
def print_message(self):
logger = logging.getLogger(__name__)
logger.info("This is a Ray actor")
actor_instance = actor.remote()
ray.get(actor_instance.print_message.remote())
"""
stderr = run_string_as_driver(script)
should_exist = ... | actor |
python | pyparsing__pyparsing | examples/shapes.py | {
"start": 234,
"end": 474
} | class ____:
def __init__(self, tokens):
self.__dict__.update(tokens.as_dict())
def area(self):
raise NotImplemented()
def __str__(self):
return "<{}>: {}".format(self.__class__.__name__, vars(self))
| Shape |
python | coleifer__peewee | tests/regressions.py | {
"start": 59105,
"end": 60384
} | class ____(ModelTestCase):
requires = [State, Transition]
def test_join_prefetch_multiple_fks(self):
s1, s2a, s2b, s3 = [State.create(name=s)
for s in ('s1', 's2a', 's2b', 's3')]
t1 = Transition.create(src=s1, dest=s2a)
t2 = Transition.create(src=s1, dest=s2b... | TestJoinTypePrefetchMultipleFKs |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/concepts/partitions_schedules_sensors/date_config_job.py | {
"start": 58,
"end": 320
} | class ____(Config):
date: str
@op
def process_data_for_date(context: OpExecutionContext, config: ProcessDateConfig):
date = config.date
context.log.info(f"processing data for {date}")
@job
def do_stuff():
process_data_for_date()
| ProcessDateConfig |
python | Textualize__textual | tests/test_data_table.py | {
"start": 663,
"end": 52110
} | class ____(App):
messages_to_record = {
"CellHighlighted",
"CellSelected",
"RowHighlighted",
"RowSelected",
"ColumnHighlighted",
"ColumnSelected",
"HeaderSelected",
"RowLabelSelected",
}
def __init__(self):
super().__init__()
s... | DataTableApp |
python | getsentry__sentry | tests/sentry/snuba/metrics/test_metrics_query_layer/test_metrics_query_layer.py | {
"start": 817,
"end": 17617
} | class ____(BaseMetricsLayerTestCase, TestCase):
@property
def now(self) -> datetime:
return BaseMetricsLayerTestCase.MOCK_DATETIME
def test_resolve_metrics_query(self) -> None:
self.store_performance_metric(
name=TransactionMRI.DURATION.value,
project_id=self.project... | MetricsQueryLayerTest |
python | huggingface__transformers | src/transformers/models/xcodec/modeling_xcodec.py | {
"start": 4105,
"end": 5215
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
if len(config.strides) != len(config.channel_ratios):
raise ValueError("Number of strides must match the number of channel_ratios.")
self.conv = nn.Conv1d(
config.semantic_hidden_size,
c... | SemanticEncoder |
python | kamyu104__LeetCode-Solutions | Python/largest-3-same-digit-number-in-string.py | {
"start": 493,
"end": 723
} | class ____(object):
def largestGoodInteger(self, num):
"""
:type num: str
:rtype: str
"""
return max(num[i] if num[i] == num[i+1] == num[i+2] else '' for i in xrange(len(num)-2))*3
| Solution2 |
python | pennersr__django-allauth | allauth/socialaccount/providers/naver/provider.py | {
"start": 394,
"end": 972
} | class ____(OAuth2Provider):
id = "naver"
name = "Naver"
account_class = NaverAccount
oauth2_adapter_class = NaverOAuth2Adapter
def extract_uid(self, data):
return str(data["id"])
def extract_common_fields(self, data):
email = data.get("email")
return dict(email=email)
... | NaverProvider |
python | great-expectations__great_expectations | great_expectations/core/batch_spec.py | {
"start": 6565,
"end": 7553
} | class ____(BatchSpec):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
if "database_name" not in self:
raise InvalidBatchSpecError("GlueDataCatalogBatchSpec requires a database_name") # noqa: TRY003 # FIXME CoP
if "table_name" not in self:
... | GlueDataCatalogBatchSpec |
python | great-expectations__great_expectations | great_expectations/data_context/store/html_site_store.py | {
"start": 1009,
"end": 20637
} | class ____:
"""
A HtmlSiteStore facilitates publishing rendered documentation built from Expectation Suites, Profiling Results, and Validation Results.
--ge-feature-maturity-info--
id: html_site_store_filesystem
title: HTML Site Store - Filesystem
icon:
short_description: D... | HtmlSiteStore |
python | sqlalchemy__sqlalchemy | test/orm/test_attributes.py | {
"start": 83145,
"end": 91649
} | class ____(fixtures.TestBase):
def test_lazy_backref_collections(self):
# TODO: break into individual tests
class Foo(BasicEntity):
pass
class Bar(BasicEntity):
pass
lazy_load = []
def lazyload(state, passive):
return lazy_load
... | LazyloadHistoryTest |
python | PyCQA__pylint | pylint/checkers/base/name_checker/naming_style.py | {
"start": 3318,
"end": 5911
} | class ____(NamingStyle):
pass
NAMING_STYLES = {
"snake_case": SnakeCaseStyle,
"camelCase": CamelCaseStyle,
"PascalCase": PascalCaseStyle,
"UPPER_CASE": UpperCaseStyle,
"any": AnyStyle,
}
# Name types that have a style option
KNOWN_NAME_TYPES_WITH_STYLE = {
"module",
"const",
"clas... | AnyStyle |
python | Netflix__metaflow | test/core/metaflow_extensions/test_org/plugins/cards/simplecard/__init__.py | {
"start": 118,
"end": 470
} | class ____(MetaflowCard):
type = "non_editable_import_test_card"
ALLOW_USER_COMPONENTS = False
def __init__(self, options={}, components=[], graph=None, flow=None, **kwargs):
self._options, self._components, self._graph = options, components, graph
def render(self, task):
return task.... | TestNonEditableImportCard |
python | ansible__ansible | test/units/playbook/test_taggable.py | {
"start": 1058,
"end": 4435
} | class ____(unittest.TestCase):
def assert_evaluate_equal(self, test_value, tags, only_tags, skip_tags):
taggable_obj = TaggableTestObj()
taggable_obj.tags = tags
evaluate = taggable_obj.evaluate_tags(only_tags, skip_tags, {})
self.assertEqual(test_value, evaluate)
def test_ev... | TestTaggable |
python | bokeh__bokeh | src/bokeh/embed/bundle.py | {
"start": 2225,
"end": 2384
} | class ____(Artifact):
def __init__(self, content: str, type: str = "text/javascript") -> None:
self.content = content
self.type = type
| Script |
python | falconry__falcon | falcon/errors.py | {
"start": 51398,
"end": 53726
} | class ____(HTTPError):
"""423 Locked.
The 423 (Locked) status code means the source or destination resource
of a method is locked. This response SHOULD contain an appropriate
precondition or postcondition code, such as 'lock-token-submitted' or
'no-conflicting-lock'.
(See also: RFC 4918, Secti... | HTTPLocked |
python | apache__airflow | providers/databricks/tests/unit/databricks/hooks/test_databricks.py | {
"start": 60062,
"end": 62367
} | class ____:
"""
Tests for DatabricksHook when auth is done with AAD token for SP as user inside workspace and
using non-global Azure cloud (China, GovCloud, Germany)
"""
@pytest.fixture(autouse=True)
def setup_connections(self, create_connection_without_db):
self.tenant_id = "3ff810a6-5... | TestDatabricksHookAadTokenOtherClouds |
python | sphinx-doc__sphinx | sphinx/domains/c/_ast.py | {
"start": 18307,
"end": 19071
} | class ____(ASTExpression):
def __init__(self, expr: ASTExpression) -> None:
self.expr = expr
def __eq__(self, other: object) -> bool:
if not isinstance(other, ASTSizeofExpr):
return NotImplemented
return self.expr == other.expr
def __hash__(self) -> int:
return ... | ASTSizeofExpr |
python | spyder-ide__spyder | spyder/plugins/ipythonconsole/api.py | {
"start": 2499,
"end": 2630
} | class ____:
Edit = 'edit_section'
View = 'view_section'
Switch = 'switch_section'
| IPythonConsoleWidgetOptionsMenuSections |
python | ethereum__web3.py | web3/types.py | {
"start": 14206,
"end": 14309
} | class ____(BlockData):
calls: Sequence[SimulateV1CallResult]
#
# web3.geth types
#
| SimulateV1Result |
python | sympy__sympy | sympy/functions/special/bessel.py | {
"start": 27835,
"end": 28946
} | class ____(BesselBase):
r"""
Hankel function of the second kind.
Explanation
===========
This function is defined as
.. math ::
H_\nu^{(2)} = J_\nu(z) - iY_\nu(z),
where $J_\nu(z)$ is the Bessel function of the first kind, and
$Y_\nu(z)$ is the Bessel function of the second k... | hankel2 |
python | pydantic__pydantic | pydantic-core/python/pydantic_core/core_schema.py | {
"start": 143465,
"end": 154674
} | class ____(TypedDict, total=False):
type: Required[Literal['definition-ref']]
schema_ref: Required[str]
ref: str
metadata: dict[str, Any]
serialization: SerSchema
def definition_reference_schema(
schema_ref: str,
ref: str | None = None,
metadata: dict[str, Any] | None = None,
seria... | DefinitionReferenceSchema |
python | scipy__scipy | scipy/optimize/tests/test_least_squares.py | {
"start": 1866,
"end": 3300
} | class ____:
def __init__(self, n=100, mode='sparse'):
rng = np.random.default_rng(123440)
self.n = n
self.x0 = -np.ones(n)
self.lb = np.linspace(-2, -1.5, n)
self.ub = np.linspace(-0.8, 0.0, n)
self.lb += 0.1 * rng.standard_normal(n)
self.ub += 0.1 * rng.st... | BroydenTridiagonal |
python | getsentry__sentry | src/sentry/search/events/fields.py | {
"start": 43679,
"end": 44152
} | class ____(ColumnArg):
string_array_columns = {
"tags.key",
"tags.value",
"measurements_key",
"span_op_breakdowns_key",
"spans_op",
"spans_group",
}
def normalize(self, value: str, params: ParamsType, combinator: Combinator | None) -> str:
if value in... | StringArrayColumn |
python | getsentry__sentry | src/sentry/notifications/platform/target.py | {
"start": 865,
"end": 2272
} | class ____(NotificationTarget):
"""
A designated recipient for a notification. This could be a user, a team, or a channel.
Accepts the renderable object type that matches the connected provider.
"""
is_prepared: bool = field(init=False, default=False)
provider_key: NotificationProviderKey
r... | GenericNotificationTarget |
python | skorch-dev__skorch | skorch/hf.py | {
"start": 691,
"end": 6109
} | class ____(TransformerMixin, BaseEstimator):
"""Base class for yet to train and pretrained tokenizers
Implements the ``vocabulary_`` attribute and the methods
``get_feature_names``, ``transform``, and ``inverse_transform``.
Subclasses should implement the ``fit`` method.
"""
@property
de... | _HuggingfaceTokenizerBase |
python | great-expectations__great_expectations | great_expectations/exceptions/exceptions.py | {
"start": 2404,
"end": 2677
} | class ____(CheckpointError):
def __init__(self) -> None:
super().__init__(
"Checkpoint.run() requires at least one validation definition. "
"Please add one and try your action again."
)
| CheckpointRunWithoutValidationDefinitionError |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pyupgrade/UP046_0.py | {
"start": 1138,
"end": 1207
} | class ____(Base1, Base2, Base3, Generic[T]):
var: T
| MoreBaseClasses |
python | pytorch__pytorch | torch/distributions/constraints.py | {
"start": 2765,
"end": 5437
} | class ____(Constraint):
"""
Placeholder for variables whose support depends on other variables.
These variables obey no simple coordinate-wise constraints.
Args:
is_discrete (bool): Optional value of ``.is_discrete`` in case this
can be computed statically. If not provided, access t... | _Dependent |
python | google__jax | jax/_src/tpu/linalg/stack.py | {
"start": 886,
"end": 2570
} | class ____:
"""A bounded functional stack implementation. Elements may be pytrees."""
def __init__(self, size, data):
"""Private constructor."""
self._size = size
self._data = data
def __repr__(self):
return f"Stack({self._size}, {self._data})"
@staticmethod
def create(capacity: int, prototy... | Stack |
python | ray-project__ray | python/ray/serve/tests/test_telemetry_2.py | {
"start": 768,
"end": 4066
} | class ____(RequestRouter):
async def choose_replicas(
self,
candidate_replicas: List[RunningReplica],
pending_request: Optional[PendingRequest] = None,
) -> List[List[RunningReplica]]:
return [candidate_replicas]
@pytest.mark.parametrize("location", ["driver", "deployment", Non... | CustomRequestRouter |
python | MorvanZhou__Reinforcement-learning-with-tensorflow | contents/3_Sarsa_maze/maze_env.py | {
"start": 592,
"end": 4012
} | class ____(tk.Tk, object):
def __init__(self):
super(Maze, self).__init__()
self.action_space = ['u', 'd', 'l', 'r']
self.n_actions = len(self.action_space)
self.title('maze')
self.geometry('{0}x{1}'.format(MAZE_W * UNIT, MAZE_H * UNIT))
self._build_maze()
def _b... | Maze |
python | celery__celery | t/unit/app/test_control.py | {
"start": 6721,
"end": 7533
} | class ____:
def setup_method(self):
self.app.control.mailbox = Mock(name='mailbox')
def test_broadcast(self):
self.app.control.broadcast('foobarbaz', arguments={'foo': 2})
self.app.control.mailbox.assert_called()
self.app.control.mailbox()._broadcast.assert_called_with(
... | test_Control_broadcast |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/column_aggregate_metrics/column_non_null_count.py | {
"start": 499,
"end": 1194
} | class ____(ColumnAggregateMetricProvider):
metric_name = "column.non_null_count"
@column_aggregate_partial(engine=SqlAlchemyExecutionEngine)
def _sqlalchemy(cls, column, **kwargs):
# This counts all rows where the column is not null.
return sa.func.count(column)
@column_aggregate_value... | ColumnNonNullCount |
python | pytorch__pytorch | torch/_numpy/_dtypes.py | {
"start": 845,
"end": 891
} | class ____(number):
name = "integer"
| integer |
python | jazzband__django-oauth-toolkit | tests/models.py | {
"start": 240,
"end": 503
} | class ____(AbstractApplication):
allowed_schemes = models.TextField(blank=True)
def get_allowed_schemes(self):
if self.allowed_schemes:
return self.allowed_schemes.split()
return super().get_allowed_schemes()
| BaseTestApplication |
python | bottlepy__bottle | bottle.py | {
"start": 137901,
"end": 138550
} | class ____(ServerAdapter):
""" Adapter for Google App Engine. """
quiet = True
def run(self, handler):
depr(0, 13, "AppEngineServer no longer required",
"Configure your application directly in your app.yaml")
from google.appengine.ext.webapp import util
# A main() funct... | AppEngineServer |
python | scipy__scipy | scipy/fftpack/tests/test_real_transforms.py | {
"start": 15729,
"end": 15872
} | class ____(_TestDSTIVBase):
def setup_method(self):
self.rdt = np.float64
self.dec = 12
self.type = 4
| TestDSTIVDouble |
python | pytorch__pytorch | torch/_inductor/bounds.py | {
"start": 638,
"end": 6114
} | class ____:
"""
Performs Value Range Analysis on LoopBody's fx graph by calling BoundVars.run()
It exposes the ranges of the nodes in the `bounds` variable
Note. A current limitation of this analysis is that it just works on a per-loop basis.
We should be able to propagate the bounds between across... | BoundVars |
python | kamyu104__LeetCode-Solutions | Python/wiggle-sort-ii.py | {
"start": 480,
"end": 2491
} | class ____(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
def nth_element(nums, n, compare=lambda a, b: a < b):
def tri_partition(nums, left, right, target, compare):
... | Solution2 |
python | pytorch__pytorch | torch/_dynamo/aot_compile.py | {
"start": 2107,
"end": 9995
} | class ____:
_artifacts: CompileArtifacts
_guard_check_enabled: bool = True
def guard_check(self, *args: Any, **kwargs: Any) -> bool:
f_locals: dict[str, Any] = {}
env = self._artifacts.runtime_env
if env.closure:
assert env.bytecode.co_freevars and len(env.closure) == le... | AOTCompiledFunction |
python | getsentry__sentry | tests/sentry/event_manager/grouping/test_seer_grouping.py | {
"start": 7396,
"end": 13571
} | class ____(TestCase):
def assert_correct_seer_metadata(
self,
grouphash: GroupHash,
expected_seer_date_sent: datetime | None,
expected_seer_event_sent: str | None,
expected_seer_model: str | None,
expected_seer_matched_grouphash: GroupHash | None,
expected_see... | StoredSeerMetadataTest |
python | django__django | tests/inspectdb/models.py | {
"start": 620,
"end": 860
} | class ____(models.Model):
people_unique = models.ForeignKey(People, models.CASCADE, unique=True)
message = models.ForeignKey(Message, models.CASCADE, blank=True, null=True)
license = models.CharField(max_length=255)
| PeopleMoreData |
python | instagram__MonkeyType | monkeytype/cli.py | {
"start": 4814,
"end": 16284
} | class ____(Exception):
pass
def get_newly_imported_items(
stub_module: Module, source_module: Module
) -> List[ImportItem]:
context = CodemodContext()
gatherer = GatherImportsVisitor(context)
stub_module.visit(gatherer)
stub_imports = list(gatherer.symbol_mapping.values())
context = Codem... | HandlerError |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.