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
scikit-learn__scikit-learn
asv_benchmarks/benchmarks/linear_model.py
{ "start": 5553, "end": 6606 }
class ____(Predictor, Estimator, Benchmark): """ Benchmarks for Lasso. """ param_names = ["representation", "precompute"] params = (["dense", "sparse"], [True, False]) def setup_cache(self): super().setup_cache() def make_data(self, params): representation, precompute = pa...
LassoBenchmark
python
django-compressor__django-compressor
compressor/tests/test_filters.py
{ "start": 7916, "end": 8431 }
class ____(TestCase): def test_csscompressor_filter(self): content = """/*! * django-compressor * Copyright (c) 2009-2014 Django Compressor authors */ p { background: rgb(51,102,153) url('../../images/image.gif'); } """ output = """/*! * django-compressor * C...
CSSCompressorTestCase
python
pennersr__django-allauth
allauth/socialaccount/providers/snapchat/provider.py
{ "start": 305, "end": 445 }
class ____(ProviderAccount): def get_user_data(self): return self.account.extra_data.get("data", {}).get("me", {})
SnapchatAccount
python
spyder-ide__spyder
spyder/plugins/editor/widgets/status.py
{ "start": 430, "end": 848 }
class ____(StatusBarWidget): """Status bar widget for current file read/write mode.""" ID = "read_write_status" def update_readonly(self, readonly): """Update read/write file status.""" value = "R" if readonly else "RW" self.set_value(value.ljust(3)) def get_tooltip(self): ...
ReadWriteStatus
python
hyperopt__hyperopt
hyperopt/mongoexp.py
{ "start": 4942, "end": 5082 }
class ____(Exception): """Raised when the search program tries to change the bandit attached to an experiment. """
DomainSwapError
python
pytorch__pytorch
torch/fx/experimental/proxy_tensor.py
{ "start": 72084, "end": 72185 }
class ____: def reset_proxy_mapping(self, base: Module, path: str) -> None: pass
_AttrProxy
python
kamyu104__LeetCode-Solutions
Python/compute-alternating-sum.py
{ "start": 37, "end": 278 }
class ____(object): def alternatingSum(self, nums): """ :type nums: List[int] :rtype: int """ return sum(nums[i] for i in xrange(0, len(nums), 2))-sum(nums[i] for i in xrange(1, len(nums), 2))
Solution
python
apache__airflow
providers/fab/tests/unit/fab/auth_manager/schemas/test_role_and_permission_schema.py
{ "start": 2477, "end": 3889 }
class ____: def test_serialize(self, minimal_app_for_auth_api): with minimal_app_for_auth_api.app_context(): role1 = create_role( minimal_app_for_auth_api, name="Test1", permissions=[ (permissions.ACTION_CAN_CREATE, permissions....
TestRoleCollectionSchema
python
getsentry__sentry
tests/sentry/metrics/test_datadog.py
{ "start": 314, "end": 2118 }
class ____(TestCase): def setUp(self) -> None: self.backend = DatadogMetricsBackend(prefix="sentrytest.") @patch("datadog.threadstats.base.ThreadStats.increment") def test_incr(self, mock_incr: MagicMock) -> None: self.backend.incr("foo", instance="bar") mock_incr.assert_called_once...
DatadogMetricsBackendTest
python
tensorflow__tensorflow
tensorflow/python/checkpoint/checkpoint_test.py
{ "start": 6197, "end": 6905 }
class ____(saver_lib.BaseSaverBuilder.SaveableObject): def __init__(self, primary_variable, mirrored_variable, name): self._primary_variable = primary_variable self._mirrored_variable = mirrored_variable tensor = self._primary_variable.read_value() spec = saver_lib.BaseSaverBuilder.SaveSpec( ...
_MirroringSaveable
python
sympy__sympy
sympy/plotting/series.py
{ "start": 75088, "end": 78722 }
class ____(SurfaceBaseSeries): """Representation for a 3D surface consisting of three parametric SymPy expressions and a range.""" is_parametric = True def __init__(self, expr_x, expr_y, expr_z, var_start_end_u, var_start_end_v, label="", **kwargs): super().__init__(**kwargs) s...
ParametricSurfaceSeries
python
pallets__click
src/click/_compat.py
{ "start": 14039, "end": 18693 }
class ____: def __init__(self, f: t.IO[t.Any], tmp_filename: str, real_filename: str) -> None: self._f = f self._tmp_filename = tmp_filename self._real_filename = real_filename self.closed = False @property def name(self) -> str: return self._real_filename def c...
_AtomicFile
python
kamyu104__LeetCode-Solutions
Python/paint-house-iv.py
{ "start": 42, "end": 939 }
class ____(object): def minCost(self, n, cost): """ :type n: int :type cost: List[List[int]] :rtype: int """ l = len(cost[0]) dp = [[0]*l for i in xrange(l)] for k in xrange(n//2): new_dp = [[float("inf")]*l for i in xrange(l)] ...
Solution
python
huggingface__transformers
src/transformers/models/cohere2/modeling_cohere2.py
{ "start": 9327, "end": 12661 }
class ____(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: Cohere2Config, layer_idx: Optional[int] = None): super().__init__() self.config = config self.layer_idx = layer_idx self.head_dim = getattr(config, "head_dim", c...
Cohere2Attention
python
airbytehq__airbyte
airbyte-integrations/connectors/source-google-ads/unit_tests/test_streams.py
{ "start": 2861, "end": 3488 }
class ____(MockGoogleAds): def send_request(self, query: str, customer_id: str, login_customer_id: str = "none"): self.count += 1 if self.count == 1: return mock_response_fails_1() else: return mock_response_fails_2() def mock_response_fails_one_date(): yield [ ...
MockGoogleAdsFails
python
pytorch__pytorch
torch/cuda/_sanitizer.py
{ "start": 19968, "end": 22374 }
class ____(TorchDispatchMode): def __init__(self) -> None: self.event_handler = EventHandler() torch._C._activate_gpu_trace() gpu_trace.register_callback_for_event_creation( self.event_handler._handle_event_creation ) gpu_trace.register_callback_for_event_deletion...
CUDASanitizerDispatchMode
python
Textualize__textual
tests/test_freeze.py
{ "start": 129, "end": 246 }
class ____(Screen): def compose(self): yield Header() yield Input() yield Footer()
MyScreen
python
eth-brownie__brownie
brownie/utils/docopt.py
{ "start": 7892, "end": 9850 }
class ____(_Pattern): """Branch/inner node of a pattern tree.""" def __init__(self, *children) -> None: self.children = list(children) def match(self, left: list[_Pattern], collected: list[_Pattern] | None = None) -> Any: raise NotImplementedError # pragma: no cover def fix(self) -> ...
_BranchPattern
python
doocs__leetcode
solution/2900-2999/2912.Number of Ways to Reach Destination in the Grid/Solution.py
{ "start": 0, "end": 601 }
class ____: def numberOfWays( self, n: int, m: int, k: int, source: List[int], dest: List[int] ) -> int: mod = 10**9 + 7 a, b, c, d = 1, 0, 0, 0 for _ in range(k): aa = ((n - 1) * b + (m - 1) * c) % mod bb = (a + (n - 2) * b + (m - 1) * d) % mod ...
Solution
python
pytest-dev__pytest-asyncio
docs/reference/markers/module_scoped_loop_strict_mode_example.py
{ "start": 313, "end": 450 }
class ____: async def test_this_runs_in_same_loop(self): global loop assert asyncio.get_running_loop() is loop
TestClassA
python
skorch-dev__skorch
skorch/history.py
{ "start": 152, "end": 3511 }
class ____: """Special placeholder since ``None`` is a valid value.""" def _not_none(items): """Whether the item is a placeholder or contains a placeholder.""" if not isinstance(items, (tuple, list)): items = (items,) return all(item is not _none for item in items) def _getitem_list_list(ite...
_none
python
scikit-learn__scikit-learn
sklearn/linear_model/_base.py
{ "start": 13105, "end": 15047 }
class ____: """Mixin for converting coef_ to and from CSR format. L1-regularizing estimators should inherit this. """ def densify(self): """ Convert coefficient matrix to dense array format. Converts the ``coef_`` member (back) to a numpy.ndarray. This is the default f...
SparseCoefMixin
python
prompt-toolkit__python-prompt-toolkit
src/prompt_toolkit/output/vt100.py
{ "start": 7372, "end": 11468 }
class ____(Dict[Attrs, str]): """ Cache for VT100 escape codes. It maps (fgcolor, bgcolor, bold, underline, strike, italic, blink, reverse, hidden, dim) tuples to VT100 escape sequences. :param true_color: When True, use 24bit colors instead of 256 colors. """ def __init__(self, color_dept...
_EscapeCodeCache
python
getsentry__sentry
src/sentry/objectstore/__init__.py
{ "start": 399, "end": 3698 }
class ____(MetricsBackend): def increment( self, name: str, value: int | float = 1, tags: Tags | None = None, ) -> None: sentry_metrics.incr(name, int(value), tags=tags) def gauge(self, name: str, value: int | float, tags: Tags | None = None) -> None: """ ...
SentryMetricsBackend
python
google__pytype
pytype/tests/test_errors2.py
{ "start": 15879, "end": 16713 }
class ____(test_base.BaseTest): """Test matrix operations.""" def test_matmul(self): errors = self.CheckWithErrors(""" def f(): return 'foo' @ 3 # unsupported-operands[e] """) self.assertErrorSequences( errors, { "e": [ "@", "st...
MatrixOperationsTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeVarDefaultClass2.py
{ "start": 3941, "end": 3985 }
class ____(Generic[T1, *Ts1, T2]): ...
ClassTB
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/sensors/tasks.py
{ "start": 1249, "end": 3541 }
class ____(BaseSensorOperator): """ Pulls tasks count from a cloud task queue; waits for queue to return task count as 0. :param project_id: the Google Cloud project ID for the subscription (templated) :param gcp_conn_id: The connection ID to use connecting to Google Cloud. :param queue_name: The q...
TaskQueueEmptySensor
python
spyder-ide__spyder
external-deps/python-lsp-server/pylsp/workspace.py
{ "start": 19625, "end": 21826 }
class ____: """Represents a notebook.""" def __init__( self, uri, notebook_type, workspace, cells=None, version=None, metadata=None ) -> None: self.uri = uri self.notebook_type = notebook_type self.workspace = workspace self.version = version self.cells = cel...
Notebook
python
walkccc__LeetCode
solutions/1760. Minimum Limit of Balls in a Bag/1760.py
{ "start": 0, "end": 392 }
class ____: def minimumSize(self, nums: list[int], maxOperations: int) -> int: def numOperations(m: int) -> int: """Returns the number of operations required to make m penalty.""" return sum((num - 1) // m for num in nums) l = 1 r = max(nums) return bisect.bisect_left( range(l, r),...
Solution
python
django__django
django/db/models/functions/math.py
{ "start": 1819, "end": 2045 }
class ____(Transform): function = "CEILING" lookup_name = "ceil" def as_oracle(self, compiler, connection, **extra_context): return super().as_sql(compiler, connection, function="CEIL", **extra_context)
Ceil
python
pyparsing__pyparsing
tests/test_unit.py
{ "start": 393562, "end": 394240 }
class ____(Test02_WithoutPackrat): """ rerun Test2 tests, now with unbounded packrat cache """ def test000_assert_packrat_status(self): print("Packrat enabled:", ParserElement._packratEnabled) print( "Packrat cache:", type(ParserElement.packrat_cache).__name__, ...
Test08_WithUnboundedPackrat
python
PrefectHQ__prefect
tests/server/schemas/test_core.py
{ "start": 2496, "end": 4035 }
class ____: class OldFlowRunPolicy(PrefectBaseModel): # Schemas ignore extras during normal execution, but raise errors during tests if not explicitly ignored. model_config = ConfigDict(extra="ignore") max_retries: int = 0 retry_delay_seconds: float = 0 async def test_flow_run_...
TestFlowRunPolicy
python
sqlalchemy__sqlalchemy
test/orm/declarative/test_mixin.py
{ "start": 2276, "end": 54782 }
class ____(DeclarativeTestBase): @testing.combinations("generate_base", "subclass", argnames="base_type") def test_init_subclass_works(self, registry, base_type): reg = registry if base_type == "generate_base": class Base: def __init_subclass__(cls): ...
DeclarativeMixinTest
python
redis__redis-py
tests/test_multidb/test_healthcheck.py
{ "start": 436, "end": 2117 }
class ____: def test_policy_returns_true_for_all_successful_probes(self): mock_hc1 = Mock(spec=HealthCheck) mock_hc2 = Mock(spec=HealthCheck) mock_hc1.check_health.return_value = True mock_hc2.check_health.return_value = True mock_db = Mock(spec=Database) policy = He...
TestHealthyAllPolicy
python
scipy__scipy
scipy/fftpack/tests/test_real_transforms.py
{ "start": 8406, "end": 8547 }
class ____(_TestDCTIBase): def setup_method(self): self.rdt = np.float64 self.dec = 10 self.type = 1
TestDCTIDouble
python
chroma-core__chroma
chromadb/test/property/test_collections.py
{ "start": 622, "end": 12327 }
class ____(RuleBasedStateMachine): collections: Bundle[strategies.ExternalCollection] _model: Dict[str, Optional[types.CollectionMetadata]] collections = Bundle("collections") def __init__(self, client: ClientAPI): super().__init__() self._model = {} self.client = client @...
CollectionStateMachine
python
PrefectHQ__prefect
tests/logging/test_logs_subscriber.py
{ "start": 3939, "end": 22682 }
class ____: token: Optional[str] hard_auth_failure: bool refuse_any_further_connections: bool hard_disconnect_after: Optional[str] # log id outgoing_logs: list[Log] def __init__(self): self.hard_auth_failure = False self.refuse_any_further_connections = False self.har...
LogPuppeteer
python
gevent__gevent
src/gevent/tests/test__hub.py
{ "start": 4018, "end": 12343 }
class ____(greentest.TestCase): def _reset_hub(self): hub = get_hub() try: del hub.exception_stream except AttributeError: pass if hub._threadpool is not None: hub.threadpool.join() hub.threadpool.kill() del hub.threadpool ...
TestPeriodicMonitoringThread
python
automl__auto-sklearn
test/test_pipeline/components/feature_preprocessing/test_select_rates_classification.py
{ "start": 302, "end": 4623 }
class ____(unittest.TestCase): def test_default_configuration(self): transformation, original = _test_preprocessing(SelectClassificationRates) self.assertEqual(transformation.shape[0], original.shape[0]) self.assertEqual(transformation.shape[1], 3) self.assertFalse((transformation ==...
SelectClassificationRatesComponentTest
python
numpy__numpy
numpy/distutils/fcompiler/nv.py
{ "start": 81, "end": 1541 }
class ____(FCompiler): """ NVIDIA High Performance Computing (HPC) SDK Fortran Compiler https://developer.nvidia.com/hpc-sdk Since august 2020 the NVIDIA HPC SDK includes the compilers formerly known as The Portland Group compilers, https://www.pgroup.com/index.htm. See also `numpy.distutils...
NVHPCFCompiler
python
python-openxml__python-docx
src/docx/enum/table.py
{ "start": 116, "end": 1627 }
class ____(BaseXmlEnum): """Alias: **WD_ALIGN_VERTICAL** Specifies the vertical alignment of text in one or more cells of a table. Example:: from docx.enum.table import WD_ALIGN_VERTICAL table = document.add_table(3, 3) table.cell(0, 0).vertical_alignment = WD_ALIGN_VERTICAL.BOTT...
WD_CELL_VERTICAL_ALIGNMENT
python
mozilla__bleach
bleach/_vendor/parse.py
{ "start": 5322, "end": 6307 }
class ____(object): """Shared methods for the parsed result objects containing a netloc element""" __slots__ = () @property def username(self): return self._userinfo[0] @property def password(self): return self._userinfo[1] @property def hostname(self): hostnam...
_NetlocResultMixinBase
python
dagster-io__dagster
python_modules/libraries/dagster-msteams/dagster_msteams/utils.py
{ "start": 42, "end": 414 }
class ____(NamedTuple): text: str url: str def build_message_with_link( is_legacy_webhook: bool, text: str, link: Optional[MSTeamsHyperlink] ) -> str: if link: if is_legacy_webhook: return f"{text} <a href='{link.url}'>{link.text}</a>" else: return f"{text} [{li...
MSTeamsHyperlink
python
huggingface__transformers
tests/models/roc_bert/test_modeling_roc_bert.py
{ "start": 1524, "end": 19096 }
class ____: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, vocab_size=99, pronunciation_vocab_size=99, shape_vocab_size=99, pronu...
RoCBertModelTester
python
pydata__xarray
xarray/tests/test_dataarray.py
{ "start": 234504, "end": 251141 }
class ____(TestReduce): def test_argmin_dim( self, x: np.ndarray, minindices_x: dict[str, np.ndarray], minindices_y: dict[str, np.ndarray], minindices_z: dict[str, np.ndarray], minindices_xy: dict[str, np.ndarray], minindices_xz: dict[str, np.ndarray], ...
TestReduce3D
python
getsentry__sentry
src/sentry/search/events/fields.py
{ "start": 32719, "end": 33571 }
class ____(FunctionArg): def __init__(self, name: str, start: float | None, end: float | None): super().__init__(name) self.start = start self.end = end def normalize( self, value: str, params: ParamsType, combinator: Combinator | None ) -> float | None: try: ...
NumberRange
python
ray-project__ray
python/ray/llm/tests/common/cloud/test_s3_filesystem.py
{ "start": 15784, "end": 19531 }
class ____: """Integration tests for S3FileSystem (requires actual S3 access).""" def test_list_subfolders_real_s3(self): """Test listing subfolders from real S3 bucket.""" # Test listing subfolders in the parent directory which has actual subfolders folders = S3FileSystem.list_subfolde...
TestS3FileSystemIntegration
python
fastapi__sqlmodel
docs_src/tutorial/update/tutorial002.py
{ "start": 100, "end": 1860 }
class ____(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_u...
Hero
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/mpileaks/package.py
{ "start": 217, "end": 1413 }
class ____(Package): """Mpileaks is a mock package that passes audits""" homepage = "http://www.spack.llnl.gov" url = "http://www.spack.llnl.gov/mpileaks-1.0.tar.gz" version("2.3", sha256="2e34cc4505556d1c1f085758e26f2f8eea0972db9382f051b2dcfb1d7d9e1825") version("2.2", sha256="2e34cc4505556d1c1f0...
Mpileaks
python
django__django
django/contrib/postgres/search.py
{ "start": 2360, "end": 3020 }
class ____(Expression): def __init__(self, config): super().__init__() if not hasattr(config, "resolve_expression"): config = Value(config) self.config = config @classmethod def from_parameter(cls, config): if config is None or isinstance(config, cls): ...
SearchConfig
python
pytorch__pytorch
test/test_overrides.py
{ "start": 8061, "end": 11854 }
class ____(DiagonalTensor): """A subclass of ``DiagonalTensor`` to test custom dispatch This class tests semantics for defining ``__torch_function__`` on a subclass of another class that defines ``__torch_function__``. The only difference compared with the superclass is that this class provides a s...
SubDiagonalTensor
python
run-llama__llama_index
llama-index-integrations/readers/llama-index-readers-airbyte-salesforce/llama_index/readers/airbyte_salesforce/base.py
{ "start": 126, "end": 722 }
class ____(AirbyteCDKReader): """ AirbyteSalesforceReader reader. Retrieve documents from Salesforce Args: config: The config object for the salesforce source. """ def __init__( self, config: Mapping[str, Any], record_handler: Optional[RecordHandler] = None, ...
AirbyteSalesforceReader
python
pypa__warehouse
warehouse/oidc/forms/_core.py
{ "start": 635, "end": 4402 }
class ____: # Attributes that must be provided by subclasses _user: User _check_project_name: typing.Callable[[str], None] _route_url: typing.Callable[..., str] project_name = wtforms.StringField( validators=[ wtforms.validators.InputRequired(message=_("Specify project name")), ...
PendingPublisherMixin
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_display_units09.py
{ "start": 315, "end": 1205 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_display_units09.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(...
TestCompareXLSXFiles
python
apache__airflow
providers/cloudant/src/airflow/providers/cloudant/cloudant_fake.py
{ "start": 822, "end": 1026 }
class ____: """Phony class to pass mypy when real class is not imported.""" def __init__(self, authenticator): pass def set_service_url(self, service_url: str): pass
CloudantV1
python
allegroai__clearml
clearml/backend_api/services/v2_9/tasks.py
{ "start": 202067, "end": 221343 }
class ____(Response): """ Response of tasks.get_all endpoint. :param tasks: List of tasks :type tasks: Sequence[Task] """ _service = "tasks" _action = "get_all" _version = "2.9" _schema = { "definitions": { "artifact": { "properties": { ...
GetAllResponse
python
mlflow__mlflow
tests/resources/mlflow-test-plugin/mlflow_test_plugin/dummy_backend.py
{ "start": 244, "end": 600 }
class ____(SubmittedRun): """ A run that just does nothing """ def __init__(self, run_id): self._run_id = run_id def wait(self): return True def get_status(self): return RunStatus.FINISHED def cancel(self): pass @property def run_id(self): ...
DummySubmittedRun
python
doocs__leetcode
solution/0500-0599/0542.01 Matrix/Solution.py
{ "start": 0, "end": 686 }
class ____: def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: m, n = len(mat), len(mat[0]) ans = [[-1] * n for _ in range(m)] q = deque() for i, row in enumerate(mat): for j, x in enumerate(row): if x == 0: ans[i][j] = 0 ...
Solution
python
django-import-export__django-import-export
tests/core/tests/test_resources/test_import_export.py
{ "start": 18704, "end": 19853 }
class ____(TestCase): """ If a custom field is declared, import should skip setting an attribute if the Field declaration has no attribute name. # 1874 """ class _EBookResource(ModelResource): published = Field(column_name="published") class Meta: model = EBook ...
DeclaredFieldWithNoAttributeTestCase
python
ethereum__web3.py
tests/core/method-class/test_method.py
{ "start": 9860, "end": 10031 }
class ____(Exception): pass def return_exception_raising_formatter(_method): def formatter(_params): raise Success() return compose(formatter)
Success
python
geekcomputers__Python
swap.py
{ "start": 0, "end": 1998 }
class ____: """ A class to perform swapping of two values. Methods: ------- swap_tuple_unpacking(self): Swaps the values of x and y using a tuple unpacking method. swap_temp_variable(self): Swaps the values of x and y using a temporary variable. swap_arithmetic_operations(...
Swapper
python
graphql-python__graphene
graphene/types/tests/test_definition.py
{ "start": 514, "end": 674 }
class ____(ObjectType): id = String() name = String() pic = Field(Image, width=Int(), height=Int()) recent_article = Field(lambda: Article)
Author
python
jina-ai__jina
tests/unit/orchestrate/pods/test_pod.py
{ "start": 440, "end": 2284 }
class ____(BaseExecutor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # pod/pod-specific assert os.environ['key1'] == 'value1' assert os.environ['key2'] == 'value2' # inherit from parent process assert os.environ['key_parent'] == 'value3' ...
EnvChecker1
python
scipy__scipy
benchmarks/benchmarks/signal.py
{ "start": 4810, "end": 5259 }
class ____(Benchmark): def setup(self): self.system = signal.lti(1.0, [1, 0, 1]) self.t = np.arange(0, 100, 0.5) self.u = np.sin(2 * self.t) def time_lsim(self): signal.lsim(self.system, self.u, self.t) def time_step(self): signal.step(self.system, T=self.t) d...
LTI
python
getsentry__sentry
tests/sentry/models/test_environment.py
{ "start": 111, "end": 1265 }
class ____(TestCase): def test_simple(self) -> None: project = self.create_project() with pytest.raises(Environment.DoesNotExist): Environment.get_for_organization_id(project.organization_id, "prod") env = Environment.get_or_create(project=project, name="prod") assert ...
GetOrCreateTest
python
huggingface__transformers
src/transformers/models/dots1/modular_dots1.py
{ "start": 2726, "end": 2942 }
class ____(DeepseekV3DecoderLayer): def __init__(self, config: Dots1Config, layer_idx: int): super().__init__(config, layer_idx) self.attention_type = config.layer_types[layer_idx]
Dots1DecoderLayer
python
jina-ai__jina
jina/serve/runtimes/gateway/streamer.py
{ "start": 1131, "end": 19242 }
class ____: """ Wrapper object to be used in a Custom Gateway. Naming to be defined """ def __init__( self, graph_representation: Dict, executor_addresses: Dict[str, Union[str, List[str]]], graph_conditions: Dict = {}, deployments_metadata: Dict[str, Dict[str, st...
GatewayStreamer
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py
{ "start": 51939, "end": 52630 }
class ____(BaseModel): type: Literal["DefaultPaginator"] pagination_strategy: Union[CursorPagination, CustomPaginationStrategy, OffsetIncrement, PageIncrement] = Field( ..., description="Strategy defining how records are paginated.", title="Pagination Strategy", ) decoder: Option...
DefaultPaginator
python
readthedocs__readthedocs.org
readthedocs/projects/views/private.py
{ "start": 37868, "end": 38041 }
class ____(EnvironmentVariableMixin, DeleteViewWithMessage): success_message = _("Environment variable deleted") http_method_names = ["post"]
EnvironmentVariableDelete
python
more-itertools__more-itertools
tests/test_recipes.py
{ "start": 7290, "end": 7750 }
class ____(TestCase): """Tests for ``flatten()``""" def test_basic_usage(self): """ensure list of lists is flattened one level""" f = [[0, 1, 2], [3, 4, 5]] self.assertEqual(list(range(6)), list(mi.flatten(f))) def test_single_level(self): """ensure list of lists is flatten...
FlattenTests
python
dagster-io__dagster
python_modules/dagster-graphql/dagster_graphql/schema/instigation.py
{ "start": 6184, "end": 6854 }
class ____(DynamicPartitionsRequestMixin, graphene.ObjectType): class Meta: # pyright: ignore[reportIncompatibleVariableOverride] name = "DynamicPartitionRequest" def __init__( self, dynamic_partition_request: Union[ AddDynamicPartitionsRequest, DeleteDynamicPartitionsReque...
GrapheneDynamicPartitionsRequest
python
apache__airflow
providers/google/tests/unit/google/cloud/links/test_base_link.py
{ "start": 3010, "end": 3627 }
class ____(GoogleCloudBaseOperator): operator_extra_links = (GoogleLink(),) def __init__(self, project_id: str, location: str, cluster_id: str, **kwargs): super().__init__(**kwargs) self.project_id = project_id self.location = location self.cluster_id = cluster_id @property...
MyOperator
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 562518, "end": 562865 }
class ____(sgqlc.types.Type): """Autogenerated return type of DeleteTeamDiscussion""" __schema__ = github_schema __field_names__ = ("client_mutation_id",) client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId") """A unique identifier for the client performing the mutation.""...
DeleteTeamDiscussionPayload
python
OmkarPathak__pygorithm
tests/test_sorting.py
{ "start": 3596, "end": 3780 }
class ____(unittest.TestCase, TestSortingAlgorithm): inplace = False alph_support = True @staticmethod def sort(arr): return bucket_sort.sort(arr)
TestBucketSort
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/engine/mock.py
{ "start": 904, "end": 4156 }
class ____: def __init__(self, dialect: Dialect, execute: Callable[..., Any]): self._dialect = dialect self._execute_impl = execute engine: Engine = cast(Any, property(lambda s: s)) dialect: Dialect = cast(Any, property(attrgetter("_dialect"))) name: str = cast(Any, property(lambda s: s...
MockConnection
python
rushter__MLAlgorithms
mla/neuralnet/layers/basic.py
{ "start": 1052, "end": 2076 }
class ____(Layer, ParamMixin): def __init__(self, output_dim, parameters=None): """A fully connected layer. Parameters ---------- output_dim : int """ self._params = parameters self.output_dim = output_dim self.last_input = None if parameters...
Dense
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typeNarrowingLiteralMember1.py
{ "start": 459, "end": 2568 }
class ____: kind: Literal[1, 2, 3] def eq_obj1(c: Union[A, B]): if c.kind == "A": reveal_type(c, expected_text="A") else: reveal_type(c, expected_text="B") def is_obj1_1(c: Union[A, B]): if c.kind is "A": reveal_type(c, expected_text="A | B") else: reveal_type(c, ...
D
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/typedDictReadOnly2.py
{ "start": 2560, "end": 2608 }
class ____(TypedDict): a: NotRequired[int]
TD9
python
networkx__networkx
networkx/classes/tests/test_filters.py
{ "start": 39, "end": 5851 }
class ____: def test_no_filter(self): nf = nx.filters.no_filter assert nf() assert nf(1) assert nf(2, 1) def test_hide_nodes(self): f = nx.classes.filters.hide_nodes([1, 2, 3]) assert not f(1) assert not f(2) assert not f(3) assert f(4) ...
TestFilterFactory
python
graphql-python__graphene
graphene/types/schema.py
{ "start": 2176, "end": 14476 }
class ____(dict): def __init__( self, query=None, mutation=None, subscription=None, types=None, auto_camelcase=True, ): assert_valid_root_type(query) assert_valid_root_type(mutation) assert_valid_root_type(subscription) if types is ...
TypeMap
python
kamyu104__LeetCode-Solutions
Python/maximum-total-subarray-value-ii.py
{ "start": 1479, "end": 3338 }
class ____(object): def maxTotalValue(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ # RMQ - Sparse Table # Template: https://github.com/kamyu104/GoogleCodeJam-Farewell-Rounds/blob/main/Round%20D/genetic_sequences2.py3 # Time: ...
Solution2
python
doocs__leetcode
solution/2400-2499/2448.Minimum Cost to Make Array Equal/Solution.py
{ "start": 0, "end": 546 }
class ____: def minCost(self, nums: List[int], cost: List[int]) -> int: arr = sorted(zip(nums, cost)) n = len(arr) f = [0] * (n + 1) g = [0] * (n + 1) for i in range(1, n + 1): a, b = arr[i - 1] f[i] = f[i - 1] + a * b g[i] = g[i - 1] + b ...
Solution
python
django__django
django/contrib/admin/widgets.py
{ "start": 1933, "end": 2310 }
class ____(DateTimeWidgetContextMixin, forms.DateInput): class Media: js = [ "admin/js/calendar.js", "admin/js/admin/DateTimeShortcuts.js", ] def __init__(self, attrs=None, format=None): attrs = {"class": "vDateField", "size": "10", **(attrs or {})} super...
BaseAdminDateWidget
python
tensorflow__tensorflow
tensorflow/python/autograph/operators/conditional_expressions_test.py
{ "start": 1223, "end": 2238 }
class ____(test.TestCase): def test_tensor(self): self.assertEqual(self.evaluate(_basic_expr(constant_op.constant(True))), 1) self.assertEqual(self.evaluate(_basic_expr(constant_op.constant(False))), 2) def test_tensor_mismatched_type(self): # tf.function required because eager cond degenerates to Pyt...
IfExpTest
python
great-expectations__great_expectations
great_expectations/exceptions/exceptions.py
{ "start": 12274, "end": 12339 }
class ____(DatasourceError): pass
DatasourceInitializationError
python
ZoranPandovski__al-go-rithms
data_structures/Diameter_Of_Binary_Tree/Diameter_Of_Binary_Tree.py
{ "start": 361, "end": 520 }
class ____: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
TreeNode
python
python__mypy
mypy/nodes.py
{ "start": 88443, "end": 90154 }
class ____(SymbolNode, Expression): """Base class for TypeVarExpr, ParamSpecExpr and TypeVarTupleExpr. Note that they are constructed by the semantic analyzer. """ __slots__ = ("_name", "_fullname", "upper_bound", "default", "variance", "is_new_style") _name: str _fullname: str # Upper bo...
TypeVarLikeExpr
python
jazzband__django-oauth-toolkit
tests/test_models.py
{ "start": 958, "end": 1129 }
class ____(TestCase): @classmethod def setUpTestData(cls): cls.user = UserModel.objects.create_user("test_user", "test@example.com", "123456")
BaseTestModels
python
squidfunk__mkdocs-material
material/plugins/search/plugin.py
{ "start": 1673, "end": 6156 }
class ____(BasePlugin[SearchConfig]): # Initialize plugin def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Initialize incremental builds self.is_dirty = False self.is_dirtyreload = False # Initialize search index cache self.search_index_...
SearchPlugin
python
numpy__numpy
numpy/f2py/tests/test_modules.py
{ "start": 106, "end": 510 }
class ____(util.F2PyTest): sources = [ util.getpath( "tests", "src", "modules", "gh26920", "two_mods_with_one_public_routine.f90" ) ] # we filter the only public function mod2 only = ["mod1_func1", ] def test_gh26920(self): # if it compiles and can be...
TestModuleFilterPublicEntities
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/dag_run.py
{ "start": 1487, "end": 1683 }
class ____(str, Enum): """Enum for DAG Run states when updating a DAG Run.""" QUEUED = DagRunState.QUEUED SUCCESS = DagRunState.SUCCESS FAILED = DagRunState.FAILED
DAGRunPatchStates
python
coleifer__peewee
tests/sqlite.py
{ "start": 50576, "end": 52532 }
class ____(TestFullTextSearch): database = SqliteExtDatabase(':memory:', c_extensions=CYTHON_EXTENSION) def test_c_extensions(self): self.assertTrue(self.database._c_extensions) self.assertTrue(Post._meta.database._c_extensions) def test_bm25f(self): def assertResults(term, expecte...
TestFullTextSearchCython
python
ray-project__ray
python/ray/serve/_private/benchmarks/streaming/_grpc/test_server_pb2_grpc.py
{ "start": 5229, "end": 8850 }
class ____(object): """Missing associated documentation comment in .proto file.""" @staticmethod def Unary( request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, ...
GRPCTestServer
python
pypa__hatch
tests/cli/fmt/test_fmt.py
{ "start": 10793, "end": 14679 }
class ____: def test_only_linter(self, hatch, temp_dir, config_file, env_run, mocker, platform, defaults_file_stable): config_file.model.template.plugins["default"]["tests"] = False config_file.save() project_name = "My.App" with temp_dir.as_cwd(): result = hatch("new",...
TestComponents
python
pytorch__pytorch
test/dynamo/test_modules.py
{ "start": 8593, "end": 9171 }
class ____(torch.nn.Module): def __init__(self) -> None: super().__init__() self.layers = torch.nn.ModuleList( [ torch.nn.Linear(10, 10), torch.nn.ReLU(), torch.nn.Linear(10, 10), torch.nn.ReLU(), ] ) ...
CustomGetItemModuleList
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 573987, "end": 574288 }
class ____(sgqlc.types.Type): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("cursor", "node") cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor") node = sgqlc.types.Field("Ref", graphql_name="node")
RefEdge
python
apache__airflow
devel-common/src/tests_common/test_utils/azure_system_helpers.py
{ "start": 3966, "end": 5784 }
class ____(SystemTest): """Base class for Azure system tests.""" @classmethod def create_share(cls, share_name: str, azure_fileshare_conn_id: str): hook = AzureFileShareHook(azure_fileshare_conn_id=azure_fileshare_conn_id) hook.create_share(share_name) @classmethod def delete_share...
AzureSystemTest
python
numpy__numpy
benchmarks/benchmarks/bench_core.py
{ "start": 6242, "end": 6330 }
class ____(Benchmark): def time_indices(self): np.indices((1000, 500))
Indices
python
getsentry__sentry
tests/sentry/incidents/subscription_processor/test_subscription_processor_base.py
{ "start": 8110, "end": 10206 }
class ____(ProcessUpdateBaseClass): def test_uses_stored_last_update_value(self) -> None: stored_timestamp = timezone.now() + timedelta(minutes=10) store_detector_last_update(self.metric_detector, self.project.id, stored_timestamp) processor = SubscriptionProcessor(self.sub) old_upd...
TestSubscriptionProcessorLastUpdate
python
tensorflow__tensorflow
tensorflow/tools/proto_splitter/split_graph_def.py
{ "start": 9922, "end": 10945 }
class ____(SplitBasedOnSize): """Splits the FunctionDef message type.""" def build_chunks(self) -> int: """Splits the proto, and returns the size of the chunks created.""" size_diff = 0 # First check if the entire FunctionDef can be split into a separate chunk. # We do this before the `RepeatedMes...
FunctionDefSplitter