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
EpistasisLab__tpot
tpot/builtin_modules/arithmetictransformer.py
{ "start": 13452, "end": 14082 }
class ____(TransformerMixin, BaseEstimator): def __init__(self): """ A transformer that returns an array of zeros. """ pass def fit(self, X, y=None): return self def transform(self, X): transformed_X = np.array(self.transform_helper(np.array(X))) ...
ZeroTransformer
python
django__django
tests/migrations/test_migrations_plan/0003_third.py
{ "start": 43, "end": 449 }
class ____(migrations.Migration): dependencies = [ ("migrations", "0002_second"), ] operations = [ migrations.CreateModel( "Author", [ ("id", models.AutoField(primary_key=True)), ], ), migrations.RunSQL( ["SELEC...
Migration
python
gevent__gevent
src/gevent/testing/util.py
{ "start": 15061, "end": 17572 }
class ____(object): """ Something that uses the ``examples/`` directory from the root of the gevent distribution. The `cwd` property is set to the root of the gevent distribution. """ #: Arguments to pass to the example file. example_args = [] before_delay = 3 after_delay = 0.5 ...
ExampleMixin
python
fluentpython__example-code-2e
15-more-types/cafeteria/cafeteria.py
{ "start": 251, "end": 436 }
class ____(Generic[T_co]): def __init__(self, beverage: T_co) -> None: self.beverage = beverage def dispense(self) -> T_co: return self.beverage
BeverageDispenser
python
apache__airflow
airflow-core/src/airflow/ti_deps/deps/ready_to_reschedule.py
{ "start": 1084, "end": 3833 }
class ____(BaseTIDep): """Determines whether a task is ready to be rescheduled.""" NAME = "Ready To Reschedule" IGNORABLE = True IS_TASK_DEP = True RESCHEDULEABLE_STATES = {TaskInstanceState.UP_FOR_RESCHEDULE, None} @provide_session def _get_dep_statuses(self, ti, session, dep_context): ...
ReadyToRescheduleDep
python
huggingface__transformers
src/transformers/models/perception_lm/modular_perception_lm.py
{ "start": 5768, "end": 12779 }
class ____(LlavaModel): _checkpoint_conversion_mapping = {} def __init__(self, config: PerceptionLMConfig): super().__init__(config) self.vision_tower = AutoModel.from_config(config.vision_config) self.multi_modal_projector = PerceptionLMMultiModalProjector(config) self.language...
PerceptionLMModel
python
neetcode-gh__leetcode
python/0036-valid-sudoku.py
{ "start": 0, "end": 749 }
class ____: def isValidSudoku(self, board: List[List[str]]) -> bool: cols = collections.defaultdict(set) rows = collections.defaultdict(set) squares = collections.defaultdict(set) # key = (r /3, c /3) for r in range(9): for c in range(9): if board[r][c] ...
Solution
python
getsentry__sentry
src/sentry/sentry_apps/api/parsers/sentry_app.py
{ "start": 2026, "end": 2498 }
class ____(serializers.URLField): def to_internal_value(self, url): # The Django URLField doesn't distinguish between different types of # invalid URLs, so do any manual checks here to give the User a better # error message. if url and not url.startswith("http"): raise Va...
URLField
python
langchain-ai__langchain
libs/standard-tests/langchain_tests/unit_tests/embeddings.py
{ "start": 734, "end": 4597 }
class ____(EmbeddingsTests): """Base class for embeddings unit tests. Test subclasses must implement the `embeddings_class` property to specify the embeddings model to be tested. You can also override the `embedding_model_params` property to specify initialization parameters. ```python from ty...
EmbeddingsUnitTests
python
kamyu104__LeetCode-Solutions
Python/query-kth-smallest-trimmed-number.py
{ "start": 58, "end": 1108 }
class ____(object): def smallestTrimmedNumbers(self, nums, queries): """ :type nums: List[str] :type queries: List[List[int]] :rtype: List[int] """ max_t = max(t for _, t in queries) lookup = [[] for _ in xrange(max_t+1)] for i, (k, t) in enumerate(que...
Solution
python
ray-project__ray
python/ray/serve/tests/unit/test_proxy_state.py
{ "start": 949, "end": 1159 }
class ____: def __init__(self, *args, **kwargs): pass def ready(self): return json.dumps(["mock_worker_id", "mock_log_file_path"]) def check_health(self): pass
FakeProxyActor
python
PrefectHQ__prefect
src/prefect/cli/transfer/_migratable_resources/deployments.py
{ "start": 947, "end": 10191 }
class ____(MigratableResource[DeploymentResponse]): _instances: dict[uuid.UUID, Self] = {} def __init__(self, deployment: DeploymentResponse): self.source_deployment = deployment self.destination_deployment: DeploymentResponse | None = None self._dependencies: dict[uuid.UUID, Migratable...
MigratableDeployment
python
PyCQA__pylint
pylint/reporters/reports_handler_mix_in.py
{ "start": 754, "end": 3304 }
class ____: """A mix-in class containing all the reports and stats manipulation related methods for the main lint class. """ def __init__(self) -> None: self._reports: ReportsDict = collections.defaultdict(list) self._reports_state: dict[str, bool] = {} def report_order(self) -> Mu...
ReportsHandlerMixIn
python
PyCQA__pylint
tests/functional/i/implicit/implicit_flag_alias.py
{ "start": 369, "end": 509 }
class ____(ExplicitUnionFlags): # [invalid-enum-extension] """Class with flags that overlap a superclass""" RWX = 7
SubclassUnionFlags
python
great-expectations__great_expectations
contrib/experimental/great_expectations_experimental/rule_based_profiler/data_assistant/statistics_data_assistant.py
{ "start": 1343, "end": 32260 }
class ____(DataAssistant): """ StatisticsDataAssistant provides metrics for dataset exploration purposes. Fundamentally, StatisticsDataAssistant is "OnboardingDataAssistant minus Expectations -- only Metrics", the intended usecase being obtaining description of data via metrics as well as comparing met...
StatisticsDataAssistant
python
getsentry__sentry
src/sentry/auth/providers/saml2/jumpcloud/provider.py
{ "start": 80, "end": 177 }
class ____(GenericSAML2Provider): name = "Jumpcloud" key = "jumpcloud"
JumpcloudSAML2Provider
python
dask__dask
dask/array/core.py
{ "start": 3199, "end": 44342 }
class ____(Warning): """A warning given when bad chunking may cause poor performance""" def getter(a, b, asarray=True, lock=None): if isinstance(b, tuple) and any(x is None for x in b): b2 = tuple(x for x in b if x is not None) b3 = tuple( None if x is None else slice(None, None) ...
PerformanceWarning
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/dataproc.py
{ "start": 2441, "end": 7148 }
class ____: """A helper class for building Dataproc job.""" def __init__( self, project_id: str, task_id: str, cluster_name: str, job_type: str, properties: dict[str, str] | None = None, ) -> None: name = f"{task_id.replace('.', '_')}_{uuid.uuid4()!s:...
DataProcJobBuilder
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_bar04.py
{ "start": 315, "end": 2165 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_bar04.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_f...
TestCompareXLSXFiles
python
mlflow__mlflow
mlflow/system_metrics/metrics/base_metrics_monitor.py
{ "start": 94, "end": 780 }
class ____(abc.ABC): """Base class of system metrics monitor.""" def __init__(self): self._metrics = defaultdict(list) @abc.abstractmethod def collect_metrics(self): """Method to collect metrics. Subclass should implement this method to collect metrics and store in `self._metr...
BaseMetricsMonitor
python
apache__airflow
airflow-core/tests/unit/ti_deps/deps/test_pool_slots_available_dep.py
{ "start": 1229, "end": 3039 }
class ____: def setup_method(self): db.clear_db_pools() with create_session() as session: test_pool = Pool(pool="test_pool", include_deferred=False) test_includes_deferred_pool = Pool(pool="test_includes_deferred_pool", include_deferred=True) session.add_all([test...
TestPoolSlotsAvailableDep
python
cherrypy__cherrypy
cherrypy/process/plugins.py
{ "start": 8186, "end": 12151 }
class ____(SimplePlugin): """Drop privileges. uid/gid arguments not available on Windows. Special thanks to `Gavin Baker <http://antonym.org/2005/12/dropping-privileges-in-python.html>`_. """ def __init__(self, bus, umask=None, uid=None, gid=None): """Initialize the privilege dropping plug...
DropPrivileges
python
doocs__leetcode
solution/2000-2099/2089.Find Target Indices After Sorting Array/Solution.py
{ "start": 0, "end": 170 }
class ____: def targetIndices(self, nums: List[int], target: int) -> List[int]: nums.sort() return [i for i, v in enumerate(nums) if v == target]
Solution
python
huggingface__transformers
tests/fsdp/test_context_parallel.py
{ "start": 1125, "end": 7748 }
class ____(TestCasePlus): """Test Trainer with Torch context parallelism enabled via accelerate's ParallelismConfig.""" @require_torch_multi_accelerator @require_accelerate @slow @run_first def test_cp_equivalence(self): """Test that CP produces the same losses as without CP.""" ...
TestContextParallel
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/constructor14.py
{ "start": 537, "end": 756 }
class ____(Generic[T_contra]): def __init__(self, callback: Callback[T_contra]) -> None: self._callback: Callback[T_contra] = callback def copy(self) -> Self: return type(self)(self._callback)
Thing
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dags.py
{ "start": 2441, "end": 8814 }
class ____: """Common class for /dags related unit tests.""" @staticmethod def _clear_db(): clear_db_connections() clear_db_runs() clear_db_dags() clear_db_assets() clear_db_serialized_dags() def _create_deactivated_paused_dag(self, session=None): dag_mo...
TestDagEndpoint
python
sqlalchemy__sqlalchemy
test/orm/test_lockmode.py
{ "start": 1860, "end": 4652 }
class ____(_fixtures.FixtureTest): __sparse_driver_backend__ = True # test against the major backends. We are naming specific databases # here rather than using requirements rules since the behavior of # "FOR UPDATE" as well as "OF" is very specific to each DB, and we need # to run the query diff...
BackendTest
python
pallets__click
src/click/testing.py
{ "start": 6336, "end": 19102 }
class ____: """The CLI runner provides functionality to invoke a Click command line script for unittesting purposes in a isolated environment. This only works in single-threaded systems without any concurrency as it changes the global interpreter state. :param charset: the character set for the in...
CliRunner
python
getsentry__sentry
src/sentry/monitors/endpoints/project_monitor_details.py
{ "start": 875, "end": 3181 }
class ____(ProjectMonitorEndpoint, MonitorDetailsMixin): publish_status = { "DELETE": ApiPublishStatus.PUBLIC, "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } owner = ApiOwner.CRONS @extend_schema( operation_id="Retrieve a Monitor for a Project", ...
ProjectMonitorDetailsEndpoint
python
getsentry__sentry
tests/sentry/seer/autofix/test_autofix.py
{ "start": 44329, "end": 49246 }
class ____(TestCase): def test_get_github_username_for_user_with_github(self) -> None: """Tests getting GitHub username from ExternalActor with GitHub provider.""" from sentry.integrations.models.external_actor import ExternalActor from sentry.integrations.types import ExternalProviders ...
TestGetGithubUsernameForUser
python
numpy__numpy
numpy/f2py/tests/test_symbolic.py
{ "start": 450, "end": 18561 }
class ____(util.F2PyTest): def test_eliminate_quotes(self): def worker(s): r, d = eliminate_quotes(s) s1 = insert_quotes(r, d) assert s1 == s for kind in ["", "mykind_"]: worker(kind + '"1234" // "ABCD"') worker(kind + '"1234" // ' + kind ...
TestSymbolic
python
ansible__ansible
test/lib/ansible_test/_internal/ci/azp.py
{ "start": 571, "end": 4180 }
class ____(CIProvider): """CI provider implementation for Azure Pipelines.""" def __init__(self) -> None: self.auth = AzurePipelinesAuthHelper() self._changes: AzurePipelinesChanges | None = None @staticmethod def is_supported() -> bool: """Return True if this provider is supp...
AzurePipelines
python
scipy__scipy
benchmarks/benchmarks/cluster.py
{ "start": 3077, "end": 3529 }
class ____(Benchmark): params = [[2, 10, 50], ['float32', 'float64']] param_names = ['k', 'dtype'] def __init__(self): rnd = np.random.RandomState(0) self.data = rnd.rand(5000, 5) self.cbook_source = rnd.rand(50, 5) def setup(self, k, dtype): self.obs = self.data.astype...
VQ
python
allegroai__clearml
clearml/backend_api/services/v2_23/frames.py
{ "start": 130330, "end": 133918 }
class ____(Request): """ Get specific frames for a dataset version using the frame ids. Random Access API. :param dataset: Dataset ID :type dataset: str :param version: Version ID :type version: str :param frame_ids: Frame IDs :type frame_ids: Sequence[str] :param projection: Used t...
GetByIdsRequest
python
tensorflow__tensorflow
tensorflow/python/keras/layers/rnn_cell_wrapper_v2.py
{ "start": 4994, "end": 5385 }
class ____(rnn_cell_wrapper_impl.DeviceWrapperBase, _RNNCellWrapperV2): """Operator that ensures an RNNCell runs on a particular device.""" def __init__(self, *args, **kwargs): # pylint: disable=useless-super-delegation super(DeviceWrapper, self).__init__(*args, **kwargs) __init__.__doc...
DeviceWrapper
python
ipython__ipython
IPython/lib/display.py
{ "start": 9136, "end": 10185 }
class ____: """ Generic class to embed an iframe in an IPython notebook """ iframe = """ <iframe width="{width}" height="{height}" src="{src}{params}" frameborder="0" allowfullscreen {extras} ></iframe> """ ...
IFrame
python
openai__openai-python
src/openai/_module_client.py
{ "start": 2131, "end": 2258 }
class ____(LazyProxy["Videos"]): @override def __load__(self) -> Videos: return _load_client().videos
VideosProxy
python
tensorflow__tensorflow
tensorflow/python/distribute/cluster_resolver/cluster_resolver.py
{ "start": 1974, "end": 11814 }
class ____(object): """Abstract class for all implementations of ClusterResolvers. This defines the skeleton for all implementations of ClusterResolvers. ClusterResolvers are a way for TensorFlow to communicate with various cluster management systems (e.g. GCE, AWS, etc...) and gives TensorFlow necessary inf...
ClusterResolver
python
dagster-io__dagster
python_modules/dagster/dagster_tests/execution_tests/pipes_tests/in_process_client.py
{ "start": 759, "end": 1069 }
class ____(PipesContextLoader): def __init__(self, pipes_context_data: PipesContextData): self.pipes_context_data = pipes_context_data @contextmanager def load_context(self, params: PipesParams) -> Iterator[PipesContextData]: yield self.pipes_context_data
InProcessPipesContextLoader
python
tensorflow__tensorflow
tensorflow/python/util/nest_test.py
{ "start": 1603, "end": 1901 }
class ____(collections.abc.Mapping): def __init__(self, *args, **kwargs): self._wrapped = dict(*args, **kwargs) def __getitem__(self, key): return self._wrapped[key] def __iter__(self): return iter(self._wrapped) def __len__(self): return len(self._wrapped)
_CustomMapping
python
django__django
tests/admin_changelist/admin.py
{ "start": 2562, "end": 2698 }
class ____(admin.ModelAdmin): list_filter = [NrOfMembersFilter] site.register(Band, BandCallableFilterAdmin)
BandCallableFilterAdmin
python
sympy__sympy
sympy/functions/elementary/complexes.py
{ "start": 30025, "end": 32363 }
class ____(DefinedFunction): """ Lift argument to the Riemann surface of the logarithm, using the standard branch. Examples ======== >>> from sympy import Symbol, polar_lift, I >>> p = Symbol('p', polar=True) >>> x = Symbol('x') >>> polar_lift(4) 4*exp_polar(0) >>> polar_li...
polar_lift
python
conda__conda
conda/exceptions.py
{ "start": 14284, "end": 14627 }
class ____(CondaError): def __init__(self, dist: str, placeholder: str, placeholder_length: int): msg = ( "Placeholder of length '%d' too short in package %s.\n" "The package must be rebuilt with conda-build > 2.0." % (placeholder_length, dist) ) super()._...
PaddingError
python
etianen__django-reversion
tests/test_app/tests/test_commands.py
{ "start": 776, "end": 2007 }
class ____(TestModelMixin, TestBase): def testCreateInitialRevisionsAppLabel(self): obj = TestModel.objects.create() self.callCommand("createinitialrevisions", "test_app") self.assertSingleRevision((obj,), comment="Initial version.") def testCreateInitialRevisionsAppLabelMissing(self):...
CreateInitialRevisionsAppLabelTest
python
pyqtgraph__pyqtgraph
pyqtgraph/imageview/ImageView.py
{ "start": 1523, "end": 33734 }
class ____(QtWidgets.QWidget): """ Widget used for display and analysis of image data. Implements many features: * Displays 2D and 3D image data. For 3D data, a z-axis slider is displayed allowing the user to select which frame is displayed. * Displays histogram of image data with m...
ImageView
python
has2k1__plotnine
plotnine/labels.py
{ "start": 2344, "end": 2572 }
class ____(labs): """ Label/name for the y aesthetic Parameters ---------- name : y aesthetic label i.e. y-axis label """ def __init__(self, label: str): super().__init__(y=label)
ylab
python
TheAlgorithms__Python
ciphers/polybius.py
{ "start": 365, "end": 3084 }
class ____: def __init__(self) -> None: self.SQUARE = np.array(SQUARE) def letter_to_numbers(self, letter: str) -> np.ndarray: """ Return the pair of numbers that represents the given letter in the polybius square >>> np.array_equal(PolybiusCipher().letter_to_numbers('a'...
PolybiusCipher
python
encode__django-rest-framework
tests/test_validation.py
{ "start": 3071, "end": 3651 }
class ____(TestCase): """ If serializer was initialized with invalid data (None or non dict-like), it should avoid validation layer (validate_<field> and validate methods) """ def test_serializer_errors_has_only_invalid_data_error(self): serializer = ValidationSerializer(data='invalid data')...
TestAvoidValidation
python
modin-project__modin
modin/tests/pandas/native_df_interoperability/test_compiler_caster.py
{ "start": 10178, "end": 27769 }
class ____(BaseTestAutoMover): """Represents a local query compiler that prefers small data.""" # Operations are cheap on this engine for small data, but there is an upper bound _MAX_SIZE_THIS_ENGINE_CAN_HANDLE = BIG_DATA_CLOUD_MIN_NUM_ROWS _OPERATION_PER_ROW_OVERHEAD = 1 def __init__(self, pandas...
LocalForSmallDataQC
python
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/counter_test.py
{ "start": 1158, "end": 1913 }
class ____(test_base.DatasetTestBase, parameterized.TestCase): @combinations.generate( combinations.times( test_base.default_test_combinations(), combinations.combine(start=3, step=4, expected_output=[[3, 7, 11]]) + combinations.combine(start=0, step=-1, expected_output=[[0, -1, -...
CounterTest
python
pyinstaller__pyinstaller
PyInstaller/building/makespec.py
{ "start": 6376, "end": 35999 }
class ____: def __init__( self, datas, binaries, hiddenimports, collect_data, collect_binaries, collect_submodules, collect_all, copy_metadata, recursive_copy_metadata ): # Initialize with literal values - will be switched to preamble variable name later, if necessary self.binari...
Preamble
python
jina-ai__jina
tests/docker_compose/test-executor/debug_executor.py
{ "start": 64, "end": 2920 }
class ____(Executor): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) from jina.logging.logger import JinaLogger self.logger = JinaLogger(self.__class__.__name__) self._name = self.runtime_args.name @requests(on='/debug') def debug(self, docs: Documen...
TestExecutor
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_comprehensions/C420_3.py
{ "start": 0, "end": 111 }
class ____: a = None {C.a: None for C.a in "abc"} print(C.a) x = [None] {x[0]: None for x[0] in "abc"} print(x)
C
python
apache__airflow
providers/apache/druid/src/airflow/providers/apache/druid/transfers/hive_to_druid.py
{ "start": 1325, "end": 10166 }
class ____(BaseOperator): """ Moves data from Hive to Druid. [del]note that for now the data is loaded into memory before being pushed to Druid, so this operator should be used for smallish amount of data.[/del] :param sql: SQL query to execute against the Druid database. (templated) :param dr...
HiveToDruidOperator
python
MongoEngine__mongoengine
docs/code/tumblelog.py
{ "start": 626, "end": 682 }
class ____(Post): image_path = StringField()
ImagePost
python
mlflow__mlflow
mlflow/genai/scorers/builtin_scorers.py
{ "start": 29973, "end": 36058 }
class ____(BuiltInScorer): """ This scorer evaluates whether the agent's response follows specific constraints or instructions provided for each row in the input dataset. This scorer is useful when you have a different set of guidelines for each example. To use this scorer, the input dataset should...
ExpectationsGuidelines
python
getsentry__sentry
src/sentry/audit_log/services/log/impl.py
{ "start": 4037, "end": 5076 }
class ____(LogService): def record_audit_log(self, *, event: AuditLogEvent) -> None: outbox = RegionOutbox( shard_scope=OutboxScope.AUDIT_LOG_SCOPE, shard_identifier=event.organization_id, category=OutboxCategory.AUDIT_LOG_EVENT, object_identifier=RegionOutbox...
OutboxBackedLogService
python
huggingface__transformers
src/transformers/models/clip/modeling_clip.py
{ "start": 9551, "end": 11895 }
class ____(nn.Module): def __init__(self, config: CLIPTextConfig): super().__init__() embed_dim = config.hidden_size self.token_embedding = nn.Embedding(config.vocab_size, embed_dim) self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim) # positio...
CLIPTextEmbeddings
python
keon__algorithms
tests/test_maths.py
{ "start": 13926, "end": 14392 }
class ____(unittest.TestCase): """[summary] Test for the file num_digits.py Arguments: unittest {[type]} -- [description] """ def test_num_digits(self): self.assertEqual(2, num_digits(12)) self.assertEqual(5, num_digits(99999)) self.assertEqual(1, num_digits(8)) ...
TestNumberOfDigits
python
ray-project__ray
python/ray/data/preprocessors/imputer.py
{ "start": 691, "end": 9174 }
class ____(SerializablePreprocessorBase): """Replace missing values with imputed values. If the column is missing from a batch, it will be filled with the imputed value. Examples: >>> import pandas as pd >>> import ray >>> from ray.data.preprocessors import SimpleImputer >>>...
SimpleImputer
python
sphinx-doc__sphinx
tests/test_builders/test_build_linkcheck.py
{ "start": 32777, "end": 34733 }
class ____(BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' def do_HEAD(self) -> None: self.send_response(302, 'Found') self.send_header('Location', '/redirected') self.send_header('Content-Length', '0') self.end_headers() def do_GET(self) -> None: content = b...
InfiniteRedirectOnHeadHandler
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/dataclassFrozen1.py
{ "start": 427, "end": 618 }
class ____(DC2): val4: int = 4 val5: ClassVar[int] # This should generate an error because a non-frozen dataclass # cannot inherit from a frozen dataclass. @dataclass(frozen=False)
DC4
python
scipy__scipy
scipy/io/tests/test_mmio.py
{ "start": 13054, "end": 19596 }
class ____: def setup_method(self): self.tmpdir = mkdtemp(suffix=str(threading.get_native_id())) self.fn = os.path.join(self.tmpdir, 'testfile.mtx') def teardown_method(self): shutil.rmtree(self.tmpdir) def check_read(self, example, a, info, dense, over32, over64): with ope...
TestMMIOReadLargeIntegers
python
getsentry__sentry
src/sentry/testutils/pytest/json_report_reruns.py
{ "start": 893, "end": 1664 }
class ____: def __init__(self, json_tests: JSONTestItems): self.json_tests = json_tests def pytest_json_runtest_stage(self, report: pytest.TestReport) -> None: assert self.json_tests is not None nodeid = report.nodeid json_testitem = self.json_tests[nodeid] if report.wh...
PytestRerunJSONReporter
python
dagster-io__dagster
examples/project_fully_featured/project_fully_featured/resources/hn_resource.py
{ "start": 1037, "end": 1626 }
class ____(HNClient): @cached_method def load_items(self) -> dict[str, HNItemRecord]: file_path = file_relative_path(__file__, "../utils/snapshot.gzip") with gzip.open(file_path, "r") as f: return json.loads(f.read().decode()) def fetch_item_by_id(self, item_id: int) -> Optional...
HNSnapshotClient
python
tiangolo__fastapi
tests/test_pydantic_v1_v2_mixed.py
{ "start": 620, "end": 55952 }
class ____(NewBaseModel): new_title: str new_size: int new_description: Union[str, None] = None new_sub: NewSubItem new_multi: List[NewSubItem] = [] app = FastAPI() @app.post("/v1-to-v2/item") def handle_v1_item_to_v2(data: Item) -> NewItem: return NewItem( new_title=data.title, ...
NewItem
python
pydantic__pydantic
pydantic-core/tests/test_json.py
{ "start": 12034, "end": 12122 }
class ____(type): def __repr__(self): raise ValueError('bad repr')
BedReprMeta
python
charliermarsh__ruff
python/ruff-ecosystem/ruff_ecosystem/types.py
{ "start": 630, "end": 2101 }
class ____(Serializable): def __init__(self, lines: Iterable[str], leading_spaces: int = 0) -> None: self.lines = list(lines) # Compute added and removed lines once self.added = list( line[2:] for line in self.lines if line.startswith("+" + " " * leading_...
Diff
python
weaviate__weaviate-python-client
weaviate/rbac/models.py
{ "start": 636, "end": 713 }
class ____: user_id: str user_type: UserTypes @dataclass
UserAssignment
python
pytorch__pytorch
test/test_nnapi.py
{ "start": 715, "end": 25713 }
class ____(TestCase): def setUp(self): super().setUp() # Avoid saturation in fbgemm torch.backends.quantized.engine = "qnnpack" libneuralnetworks_path = os.environ.get("LIBNEURALNETWORKS_PATH") if libneuralnetworks_path: ctypes.cdll.LoadLibrary(libneuralnetworks_...
TestNNAPI
python
apache__airflow
airflow-core/src/airflow/api_fastapi/core_api/datamodels/common.py
{ "start": 2983, "end": 3537 }
class ____(BulkBaseAction[T]): """Bulk Delete entity serializer for request bodies.""" action: Literal[BulkAction.DELETE] = Field(description="The action to be performed on the entities.") entities: list[Union[str, BulkTaskInstanceBody]] = Field( ..., description="A list of entity id/key or...
BulkDeleteAction
python
django__django
django/contrib/gis/gdal/layer.py
{ "start": 888, "end": 8820 }
class ____(GDALBase): """ A class that wraps an OGR Layer, needs to be instantiated from a DataSource object. """ def __init__(self, layer_ptr, ds): """ Initialize on an OGR C pointer to the Layer and the `DataSource` object that owns this layer. The `DataSource` object is r...
Layer
python
eriklindernoren__ML-From-Scratch
mlfromscratch/deep_learning/layers.py
{ "start": 14614, "end": 16351 }
class ____(Layer): """A parent class of MaxPooling2D and AveragePooling2D """ def __init__(self, pool_shape=(2, 2), stride=1, padding=0): self.pool_shape = pool_shape self.stride = stride self.padding = padding self.trainable = True def forward_pass(self, X, training=Tru...
PoolingLayer
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_escapes06.py
{ "start": 315, "end": 967 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("escapes06.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file a num format that require XML escaping.""" ...
TestCompareXLSXFiles
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/pickleable.py
{ "start": 648, "end": 732 }
class ____(ComparableEntity): pass # TODO: these are kind of arbitrary....
Address
python
ethereum__web3.py
web3/utils/caching.py
{ "start": 230, "end": 2540 }
class ____: def __init__(self, size: int = 100): self._size = size self._data: OrderedDict[str, Any] = OrderedDict() def __contains__(self, key: str) -> bool: return key in self._data def __len__(self) -> int: return len(self._data) def cache(self, key: str, value: Any...
SimpleCache
python
ipython__ipython
tests/test_magic.py
{ "start": 53631, "end": 55731 }
class ____(Magics): @line_magic def lazy_line(self, line): print("Lazy Line") @cell_magic def lazy_cell(self, line, cell): print("Lazy Cell") def load_ipython_extension(ipython): ipython.register_magics(LazyMagics) """ def test_lazy_magics(): with pytest.raises(UsageError): ...
LazyMagics
python
google__pytype
pytype/typegraph/cfg_utils_test.py
{ "start": 7954, "end": 13026 }
class ____(unittest.TestCase): """Test abstract graph utilities.""" def setUp(self): super().setUp() self.prog = cfg.Program() def test_compute_predecessors(self): # n7 n6 # ^ ^ # | | # | | # n1 ---> n20 --> n3 --> n5 -+ # | ^ ^ | #...
GraphUtilTest
python
pytorch__pytorch
torch/_inductor/pattern_matcher.py
{ "start": 3664, "end": 3912 }
class ____(Protocol): def __call__( self, fn: Union[SearchFn, ReplaceFn], *args: Any, **kwargs: Any ) -> torch.fx.GraphModule: ... T = TypeVar("T") # What's a better name for this? FnsType = Union[torch.fx.node.Target, str]
TraceFn
python
django__django
tests/generic_relations_regress/models.py
{ "start": 2135, "end": 2346 }
class ____(models.Model): content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() note = models.TextField()
Note
python
protocolbuffers__protobuf
python/google/protobuf/internal/text_format_test.py
{ "start": 1436, "end": 1904 }
class ____(unittest.TestCase): # The members of _QUOTES are formatted into a regexp template that # expects single characters. Therefore it's an error (in addition to being # non-sensical in the first place) to try to specify a "quote mark" that is # more than one character. def testQuoteMarksAreSingleChars...
SimpleTextFormatTests
python
tensorflow__tensorflow
tensorflow/python/ops/image_ops_test.py
{ "start": 208413, "end": 216995 }
class ____(test_util.TensorFlowTestCase): def testNonMaxSuppression(self): boxes_np = [[0, 0, 1, 1], [0, 0.1, 1, 1.1], [0, -0.1, 1, 0.9], [0, 10, 1, 11], [0, 10.1, 1, 11.1], [0, 100, 1, 101]] scores_np = [0.9, 0.75, 0.6, 0.95, 0.5, 0.3] max_output_size_np = 3 iou_threshold_np = 0.5 ...
NonMaxSuppressionTest
python
dagster-io__dagster
python_modules/libraries/dagster-sling/dagster_sling/components/sling_replication_collection/component.py
{ "start": 1820, "end": 2558 }
class ____(Resolvable): path: str op: Optional[OpSpec] = None translation: Optional[ Annotated[ TranslationFn[Mapping[str, Any]], TranslationFnResolver( template_vars_for_translation_fn=lambda data: {"stream_definition": data} ), ] ] = ...
SlingReplicationSpecModel
python
django__django
django/core/serializers/base.py
{ "start": 6504, "end": 7162 }
class ____: """ Abstract base deserializer class. """ def __init__(self, stream_or_string, **options): """ Init this serializer given a stream or a string """ self.options = options if isinstance(stream_or_string, str): self.stream = StringIO(stream_o...
Deserializer
python
run-llama__llama_index
llama-index-integrations/llms/llama-index-llms-vllm/tests/test_integration.py
{ "start": 584, "end": 4499 }
class ____(VCRTestCase): # replace to local_vllm(), it requires vllm installed and fail ..stream.. tests due to Not Implemented vllm = remote_vllm() # drop it to record new cassete files def _get_vcr_kwargs(self, **kwargs): return {"record_mode": RecordMode.NONE} def test_completion(self):...
TestVllmIntegration
python
pytorch__pytorch
test/fx/quantization.py
{ "start": 2193, "end": 2626 }
class ____(NoObserver): def quantize(self, quantizer, node, load_arg): return torch.relu( load_arg(node.args[0]) ) # torch.relu works directly on quantized tensors? # these ops have quantized equivalents that do not need any extra information @register_pattern(torch.nn.ReLU) @register...
Relu
python
xlwings__xlwings
xlwings/_xlwindows.py
{ "start": 52626, "end": 53983 }
class ____(base_classes.Characters): def __init__(self, parent, xl, start=None, length=None): self.parent = parent self.xl = xl self.start = start if start else 1 self.length = length if length else xl().Count @property def api(self): return self.xl(self.start, self....
Characters
python
airbytehq__airbyte
airbyte-ci/connectors/pipelines/tests/test_helpers/test_execution/test_run_steps.py
{ "start": 603, "end": 14807 }
class ____(Step): title = "Test Step" async def _run(self, result_status=StepStatus.SUCCESS) -> StepResult: return StepResult(step=self, status=result_status) @pytest.mark.anyio @pytest.mark.parametrize( "desc, steps, expected_results, options", [ ( "All consecutive steps ...
TestStep
python
altair-viz__altair
tools/schemapi/codegen.py
{ "start": 1191, "end": 5150 }
class ____: nonkeyword: bool required: set[str] kwds: set[str] invalid_kwds: set[str] additional: bool schema_info: SchemaInfo def iter_args( self, group: Iterable[str] | AttrGetter[ArgInfo, set[str]], *more_groups: Iterable[str] | AttrGetter[ArgInfo, set[str]], ...
ArgInfo
python
numba__numba
numba/core/base.py
{ "start": 43387, "end": 44302 }
class ____(object): """ A wrapper object to call an implementation function with some predefined (context, signature) arguments. The wrapper also forwards attribute queries, which is important. """ def __init__(self, imp, context, sig): self._callable = _wrap_missing_loc(imp) se...
_wrap_impl
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_font06.py
{ "start": 315, "end": 2628 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_font06.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_...
TestCompareXLSXFiles
python
huggingface__transformers
src/transformers/models/vit/modeling_vit.py
{ "start": 5269, "end": 8272 }
class ____(nn.Module): """ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a Transformer. """ def __init__(self, config: ViTConfig): ...
ViTPatchEmbeddings
python
pyqtgraph__pyqtgraph
pyqtgraph/examples/customGraphicsItem.py
{ "start": 271, "end": 1954 }
class ____(pg.GraphicsObject): def __init__(self, data): pg.GraphicsObject.__init__(self) self.data = data ## data must have fields: time, open, close, min, max self.generatePicture() def generatePicture(self): ## pre-computing a QPicture object allows paint() to run much m...
CandlestickItem
python
keras-team__keras
keras/src/backend/torch/core.py
{ "start": 23020, "end": 24369 }
class ____(torch.autograd.Function): """Enables custom forward & backward passes for gradient computation.""" @staticmethod def forward(ctx, forward_fn, *args, **kwargs): """Forward pass computation specification. Args: ctx: Context object. forward_fn: Function to c...
CustomGradientFunction
python
pytorch__pytorch
test/onnx/test_pytorch_onnx_onnxruntime.py
{ "start": 5515, "end": 492971 }
class ____(onnx_test_common._TestONNXRuntime): def test_fuse_conv_bn1d(self): class Fuse(torch.nn.Module): def __init__(self) -> None: super().__init__() self.conv = torch.nn.Conv1d(16, 33, 3, stride=2) self.bn = torch.nn.BatchNorm1d(33) ...
TestONNXRuntime
python
walkccc__LeetCode
solutions/315. Count of Smaller Numbers After Self/315.py
{ "start": 421, "end": 898 }
class ____: def countSmaller(self, nums: list[int]) -> list[int]: ans = [] ranks = self._getRanks(nums) tree = FenwickTree(len(ranks)) for num in reversed(nums): ans.append(tree.get(ranks[num] - 1)) tree.add(ranks[num], 1) return ans[::-1] def _getRanks(self, nums: list[int]) -> d...
Solution
python
plotly__plotly.py
plotly/graph_objs/sunburst/_insidetextfont.py
{ "start": 233, "end": 17196 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "sunburst" _path_str = "sunburst.insidetextfont" _valid_props = { "color", "colorsrc", "family", "familysrc", "lineposition", "linepositionsrc", "shadow", "shadowsrc", "size", ...
Insidetextfont
python
kennethreitz__tablib
tests/test_tablib.py
{ "start": 29346, "end": 30592 }
class ____(BaseTestCase): def test_tsv_import_set(self): """Generate and import TSV set serialization.""" data.append(self.john) data.append(self.george) data.headers = self.headers _tsv = data.tsv data.tsv = _tsv self.assertEqual(_tsv, data.tsv) def t...
TSVTests
python
davidhalter__jedi
test/completion/inheritance.py
{ "start": 1, "end": 113 }
class ____(object): attribute = 3 def func(self): return 1 class Inner(): pass
Super
python
MongoEngine__mongoengine
tests/fixtures.py
{ "start": 105, "end": 194 }
class ____(EmbeddedDocument): date = DateTimeField(default=datetime.now)
PickleEmbedded