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
django__django
tests/admin_inlines/admin.py
{ "start": 6499, "end": 6567 }
class ____(admin.ModelAdmin): inlines = [ChapterInline]
NovelAdmin
python
tensorflow__tensorflow
tensorflow/python/keras/distribute/distribute_coordinator_utils.py
{ "start": 1612, "end": 1982 }
class ____(object): PS = "ps" WORKER = "worker" CHIEF = "chief" EVALUATOR = "evaluator" CLIENT = "client" def _get_num_workers(cluster_spec): """Gets number of workers including chief.""" if not cluster_spec: return 0 return len(cluster_spec.as_dict().get(_TaskType.WORKER, [])) + len( cluste...
_TaskType
python
great-expectations__great_expectations
tests/datasource/fluent/test_spark_filesystem_datasource.py
{ "start": 41399, "end": 45367 }
class ____: @pytest.mark.spark @pytest.mark.xfail(strict=True, reason="Will fix or refactor as part of V1-306") def test_parameter_keys_with_partitioner_file_asset_batch_parameters( self, file_asset, daily_partitioner ): assert file_asset.get_batch_parameters_keys(partitioner=daily_parti...
TestPartitionerFileAsset
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/operators/vertex_ai/auto_ml.py
{ "start": 24631, "end": 26661 }
class ____(GoogleCloudBaseOperator): """ Delete an AutoML training job. Can be used with AutoMLForecastingTrainingJob, AutoMLImageTrainingJob, AutoMLTabularTrainingJob, AutoMLTextTrainingJob, or AutoMLVideoTrainingJob. """ template_fields = ("training_pipeline_id", "region", "project_id", "imp...
DeleteAutoMLTrainingJobOperator
python
jupyterlab__jupyterlab
jupyterlab/labapp.py
{ "start": 10215, "end": 10391 }
class ____(WorkspaceListApp): version = version @default("workspaces_dir") def _default_workspaces_dir(self): return get_workspaces_dir()
LabWorkspaceListApp
python
ipython__ipython
IPython/core/magics/pylab.py
{ "start": 1391, "end": 6624 }
class ____(Magics): """Magics related to matplotlib's pylab support""" @skip_doctest @line_magic @magic_arguments.magic_arguments() @magic_arguments.argument('-l', '--list', action='store_true', help='Show available matplotlib backends') @magic_gui_arg def matp...
PylabMagics
python
pytorch__pytorch
test/quantization/pt2e/test_quantize_pt2e_qat.py
{ "start": 39835, "end": 40580 }
class ____(PT2EQATTestCase): @skip_if_no_torchvision @skipIfNoQNNPACK def test_qat_resnet18(self): import torchvision with override_quantized_engine("qnnpack"): example_inputs = (torch.randn(1, 3, 224, 224),) m = torchvision.models.resnet18() self._verify...
TestQuantizePT2EQATModels
python
openai__openai-python
src/openai/types/eval_create_params.py
{ "start": 3488, "end": 3733 }
class ____(TypedDict, total=False): content: Required[str] """The content of the message.""" role: Required[str] """The role of the message (e.g. "system", "assistant", "user")."""
TestingCriterionLabelModelInputSimpleInputMessage
python
MongoEngine__mongoengine
mongoengine/fields.py
{ "start": 78629, "end": 79042 }
class ____(GeoJsonBaseField): """A GeoJSON field storing a line of longitude and latitude coordinates. The data is represented as: .. code-block:: js {'type' : 'LineString' , 'coordinates' : [[x1, y1], [x2, y2] ... [xn, yn]]} You can either pass a dict with the full information or a...
LineStringField
python
TheAlgorithms__Python
data_structures/linked_list/merge_two_lists.py
{ "start": 358, "end": 2210 }
class ____: def __init__(self, ints: Iterable[int]) -> None: self.head: Node | None = None for i in sorted(ints, reverse=True): self.head = Node(i, self.head) def __iter__(self) -> Iterator[int]: """ >>> tuple(SortedLinkedList(test_data_odd)) == tuple(sorted(test_dat...
SortedLinkedList
python
django__django
tests/mail/tests.py
{ "start": 125427, "end": 128572 }
class ____(SimpleTestCase): """ Check django.core.mail does not directly import Python legacy email APIs, with a few specific exceptions. """ # From "Legacy API:" in https://docs.python.org/3/library/email.html. legacy_email_apis = { "email.message.Message", "email.mime", ...
LegacyAPINotUsedTests
python
tensorflow__tensorflow
tensorflow/python/keras/legacy_tf_layers/convolutional.py
{ "start": 60108, "end": 68708 }
class ____(keras_layers.Conv3DTranspose, base.Layer): """Transposed 3D convolution layer (sometimes called 3D Deconvolution). Args: filters: Integer, the dimensionality of the output space (i.e. the number of filters in the convolution). kernel_size: An integer or tuple/list of 3 integers, specifying...
Conv3DTranspose
python
spulec__freezegun
tests/test_datetimes.py
{ "start": 19462, "end": 20275 }
class ____(unittest.TestCase): @classmethod def setUpClass(cls) -> None: assert datetime.date(2013, 4, 9) == datetime.date.today() def setUp(self) -> None: self.assertEqual(datetime.date(2013, 4, 9), datetime.date.today()) def tearDown(self) -> None: self.assertEqual(datetime....
TestUnitTestClassDecorator
python
numpy__numpy
numpy/f2py/symbolic.py
{ "start": 44280, "end": 44820 }
class ____: # Internal class to represent a pair of expressions def __init__(self, left, right): self.left = left self.right = right def substitute(self, symbols_map): left, right = self.left, self.right if isinstance(left, Expr): left = left.substitute(symbols_...
_Pair
python
readthedocs__readthedocs.org
readthedocs/search/parsers.py
{ "start": 241, "end": 17047 }
class ____: # Limit that matches the ``index.mapping.nested_objects.limit`` ES setting. max_inner_documents = 10000 # Limit the size of the contents to be indexed, # to avoid filling the index with too much data. # The limit may be exceeded if the content is too large, # or if the content is mal...
GenericParser
python
langchain-ai__langchain
libs/langchain/tests/unit_tests/output_parsers/test_enum_parser.py
{ "start": 167, "end": 858 }
class ____(Enum): RED = "red" GREEN = "green" BLUE = "blue" def test_enum_output_parser_parse() -> None: parser = EnumOutputParser(enum=Colors) # Test valid inputs result = parser.parse("red") assert result == Colors.RED result = parser.parse("green") assert result == Colors.GREE...
Colors
python
django__django
django/db/models/fields/reverse_related.py
{ "start": 8013, "end": 9862 }
class ____(ForeignObjectRel): """ Used by the ForeignKey field to store information about the relation. ``_meta.get_fields()`` returns this class to provide access to the field flags for the reverse relation. Note: Because we somewhat abuse the Rel objects by using them as reverse fields we ge...
ManyToOneRel
python
fsspec__filesystem_spec
fsspec/tests/test_utils.py
{ "start": 13472, "end": 13539 }
class ____: def __fspath__(self): return "foo"
_HasFspath
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_segment_op_test.py
{ "start": 1496, "end": 9505 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): def expected_value(self, data, segment_ids, num_segments, combiner): """Find the expected value for a call to ragged_segment_<aggregate>. Args: data: The input RaggedTensor, expressed as a nested python list. ...
RaggedSegmentOpsTest
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_dag_run.py
{ "start": 57998, "end": 61130 }
class ____: @pytest.mark.usefixtures("configure_git_connection_for_dag_bundle") def test_clear_dag_run(self, test_client, session): response = test_client.post( f"/dags/{DAG1_ID}/dagRuns/{DAG1_RUN1_ID}/clear", json={"dry_run": False}, ) assert response.status_code...
TestClearDagRun
python
jazzband__tablib
tests/test_tablib_dbfpy_packages_utils.py
{ "start": 2251, "end": 3562 }
class ____(unittest.TestCase): """dbfpy.utils.getDateTime test cases.""" def test_getDateTime_none(self): # Arrange value = None # Act output = utils.getDateTime(value) # Assert self.assertIsInstance(output, dt.datetime) def test_getDateTime_datetime_datet...
UtilsGetDateTimeTestCase
python
realpython__materials
python-wav-files/waveio/reader.py
{ "start": 981, "end": 1495 }
class ____: def __init__(self, values, frames_range): self.values = values self.frames_range = frames_range def __iter__(self): return iter(self.values) def __getattr__(self, name): return getattr(self.values, name) def reshape(self, *args, **kwargs): reshaped ...
ArraySlice
python
google__jax
jax/_src/export/shape_poly.py
{ "start": 1758, "end": 2468 }
class ____(core.InconclusiveDimensionOperation): """Raised when we cannot conclusively compute with symbolic dimensions.""" _help_msg = """ This error arises for comparison operations with shapes that are non-constant, and the result of the operation cannot be represented as a boolean value for all values of the s...
InconclusiveDimensionOperation
python
getsentry__sentry
tests/sentry/api/serializers/test_pull_request.py
{ "start": 423, "end": 4557 }
class ____(TestCase): def test_simple(self) -> None: user = self.create_user() project = self.create_project() release = Release.objects.create( organization_id=project.organization_id, version=uuid4().hex ) release.add_project(project) repository = Reposi...
PullRequestSerializerTest
python
pallets__jinja
src/jinja2/nodes.py
{ "start": 28707, "end": 28979 }
class ____(BinExpr): """Short circuited OR.""" operator = "or" def as_const(self, eval_ctx: EvalContext | None = None) -> t.Any: eval_ctx = get_eval_context(self, eval_ctx) return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
Or
python
scipy__scipy
scipy/linalg/tests/test_fblas.py
{ "start": 18253, "end": 18382 }
class ____(BaseGerComplex): blas_func = fblas.zgeru dtype = complex128 def transform(self,x): return x
TestZgeru
python
getsentry__sentry
src/sentry/integrations/jira_server/integration.py
{ "start": 5416, "end": 7182 }
class ____(forms.Form): url = forms.CharField( label=_("Jira URL"), help_text=_("The base URL for your Jira Server instance, including the host and protocol."), widget=forms.TextInput(attrs={"placeholder": "https://jira.example.com"}), validators=[URLValidator()], ) verify_ss...
InstallationForm
python
jina-ai__jina
jina/types/mixin.py
{ "start": 167, "end": 3814 }
class ____: """The base mixin class of all Jina types. .. note:: - All Jina types should inherit from this class. - All subclass should have ``self._pb_body`` - All subclass should implement ``__init__`` with the possibility of initializing from ``None``, e.g.: .. highlight...
ProtoTypeMixin
python
pandas-dev__pandas
asv_bench/benchmarks/multiindex_object.py
{ "start": 1257, "end": 2000 }
class ____: def setup(self): self.mi_large = MultiIndex.from_product( [np.arange(1000), np.arange(20), list(string.ascii_letters)], names=["one", "two", "three"], ) self.mi_med = MultiIndex.from_product( [np.arange(1000), np.arange(10), list("A")], names=[...
GetLocs
python
getsentry__sentry
tests/sentry/utils/test_event_frames.py
{ "start": 3225, "end": 10337 }
class ____(unittest.TestCase): def test_platform_java(self) -> None: frames = [ { "module": "jdk.internal.reflect.NativeMethodAccessorImpl", "filename": "NativeMethodAccessorImpl.java", "abs_path": "NativeMethodAccessorImpl.java", }, ...
JavaFilenameMungingTestCase
python
cython__cython
Cython/Compiler/ExprNodes.py
{ "start": 216999, "end": 222242 }
class ____(MemoryViewIndexNode): is_memview_slice = True # No-op slicing operation, this node will be replaced is_ellipsis_noop = False is_memview_scalar_assignment = False is_memview_index = False is_memview_broadcast = False def analyse_ellipsis_noop(self, env, getting): """Slic...
MemoryViewSliceNode
python
mwaskom__seaborn
tests/test_categorical.py
{ "start": 86988, "end": 100033 }
class ____(SharedAggTests): func = staticmethod(pointplot) def get_last_color(self, ax): color = ax.lines[-1].get_color() return to_rgba(color) @pytest.mark.parametrize("orient", ["x", "y"]) def test_single_var(self, orient): vals = pd.Series([1, 3, 10]) ax = pointpl...
TestPointPlot
python
PrefectHQ__prefect
tests/server/orchestration/api/test_deployments.py
{ "start": 128827, "end": 131175 }
class ____: async def test_404_on_bad_id(self, client): response = await client.get(f"deployments/{uuid4()}/work_queue_check") assert response.status_code == status.HTTP_404_NOT_FOUND async def test_well_formed_response( self, session, client, flow, ): ...
TestGetDeploymentWorkQueueCheck
python
airbytehq__airbyte
airbyte-ci/connectors/connectors_qa/src/connectors_qa/checks/assets.py
{ "start": 1951, "end": 4288 }
class ____(AssetsCheck): name = "Connectors must have an icon" description = "Each connector must have an icon available in at the root of the connector code directory. It must be an SVG file named `icon.svg` and must be a square." requires_metadata = False def _check_is_valid_svg(self, icon_path: Path...
CheckConnectorIconIsAvailable
python
apache__airflow
providers/apache/kafka/tests/unit/apache/kafka/triggers/test_await_message.py
{ "start": 1490, "end": 1687 }
class ____: def __init__(*args, **kwargs) -> None: pass def poll(*args, **kwargs): return MockedMessage() def commit(*args, **kwargs): return True
MockedConsumer
python
getsentry__sentry
tests/sentry/releases/endpoints/test_organization_release_files.py
{ "start": 7605, "end": 14621 }
class ____(APITestCase): def test_simple(self) -> None: project = self.create_project(name="foo") release = Release.objects.create(organization_id=project.organization_id, version="1") release.add_project(project) assert release.count_artifacts() == 0 url = reverse( ...
ReleaseFileCreateTest
python
encode__django-rest-framework
tests/test_validation.py
{ "start": 5672, "end": 7696 }
class ____(TestCase): CHOICES = [ (0, 'Small'), (1, 'Medium'), (2, 'Large'), ] SINGLE_CHOICES = [0, 1, 2] CHOICES_NESTED = [ ('Category', ( (1, 'First'), (2, 'Second'), (3, 'Third'), )), (4, 'Fourth'), ] MIXED...
TestChoiceFieldChoicesValidate
python
pypa__pip
src/pip/_vendor/pkg_resources/__init__.py
{ "start": 44745, "end": 45226 }
class ____(RuntimeError): """An error occurred extracting a resource The following attributes are available from instances of this exception: manager The resource manager that raised this exception cache_path The base directory for resource extraction original_error The e...
ExtractionError
python
airbytehq__airbyte
airbyte-integrations/connectors/destination-aws-datalake/destination_aws_datalake/config_reader.py
{ "start": 428, "end": 655 }
class ____(enum.Enum): PARQUET = "Parquet" JSONL = "JSONL" @staticmethod def from_string(s: str): if s == "Parquet": return OutputFormat.PARQUET return OutputFormat.JSONL
OutputFormat
python
cython__cython
docs/examples/userguide/early_binding_for_speed/rectangle.py
{ "start": 15, "end": 516 }
class ____: x0: cython.int y0: cython.int x1: cython.int y1: cython.int def __init__(self, x0: cython.int, y0: cython.int, x1: cython.int, y1: cython.int): self.x0 = x0 self.y0 = y0 self.x1 = x1 self.y1 = y1 def area(self): area = (self.x1 - self.x0) * (...
Rectangle
python
celery__celery
t/unit/events/test_events.py
{ "start": 205, "end": 775 }
class ____: raise_on_publish = False def __init__(self, *args, **kwargs): self.sent = [] def publish(self, msg, *args, **kwargs): if self.raise_on_publish: raise KeyError() self.sent.append(msg) def close(self): pass def has_event(self, kind): ...
MockProducer
python
doocs__leetcode
solution/0600-0699/0628.Maximum Product of Three Numbers/Solution2.py
{ "start": 0, "end": 240 }
class ____: def maximumProduct(self, nums: List[int]) -> int: top3 = nlargest(3, nums) bottom2 = nlargest(2, nums, key=lambda x: -x) return max(top3[0] * top3[1] * top3[2], top3[0] * bottom2[0] * bottom2[1])
Solution
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/links/sagemaker_unified_studio.py
{ "start": 914, "end": 1202 }
class ____(BaseAwsLink): """Helper class for constructing Amazon SageMaker Unified Studio Links.""" name = "Amazon SageMaker Unified Studio" key = "sagemaker_unified_studio" format_str = BASE_AWS_CONSOLE_LINK + "/datazone/home?region={region_name}"
SageMakerUnifiedStudioLink
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/dialects/sqlite/base.py
{ "start": 43859, "end": 46337 }
class ____(_DateTimeMixin, sqltypes.Date): r"""Represent a Python date object in SQLite using a string. The default string storage format is:: "%(year)04d-%(month)02d-%(day)02d" e.g.: .. sourcecode:: text 2011-03-15 The incoming storage format is by default parsed using the ...
DATE
python
milvus-io__pymilvus
tests/test_decorators.py
{ "start": 5329, "end": 5518 }
class ____(grpc.RpcError): def code(self): return grpc.StatusCode.DEADLINE_EXCEEDED def details(self): return "details of deadline exceeded"
MockDeadlineExceededError
python
pypa__pipenv
pipenv/patched/pip/_internal/metadata/importlib/_dists.py
{ "start": 1179, "end": 3465 }
class ____(importlib.metadata.Distribution): """An ``importlib.metadata.Distribution`` read from a wheel. Although ``importlib.metadata.PathDistribution`` accepts ``zipfile.Path``, its implementation is too "lazy" for pip's needs (we can't keep the ZipFile handle open for the entire lifetime of the dis...
WheelDistribution
python
kubernetes-client__python
kubernetes/client/models/v1_topology_selector_label_requirement.py
{ "start": 383, "end": 4840 }
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...
V1TopologySelectorLabelRequirement
python
python-pillow__Pillow
src/PIL/ImageCms.py
{ "start": 3932, "end": 6969 }
class ____(IntFlag): """Flags and documentation are taken from ``lcms2.h``.""" NONE = 0 NOCACHE = 0x0040 """Inhibit 1-pixel cache""" NOOPTIMIZE = 0x0100 """Inhibit optimizations""" NULLTRANSFORM = 0x0200 """Don't transform anyway""" GAMUTCHECK = 0x1000 """Out of Gamut alarm""" ...
Flags
python
apache__airflow
providers/apache/spark/src/airflow/providers/apache/spark/operators/spark_jdbc.py
{ "start": 1103, "end": 8913 }
class ____(SparkSubmitOperator): """ Extend the SparkSubmitOperator to perform data transfers to/from JDBC-based databases with Apache Spark. As with the SparkSubmitOperator, it assumes that the "spark-submit" binary is available on the PATH. .. seealso:: For more information on how to use th...
SparkJDBCOperator
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 176075, "end": 187817 }
class ____(VegaLiteSchema): """ BaseTitleNoValueRefs schema wrapper. Parameters ---------- align : :class:`Align`, Literal['left', 'center', 'right'] Horizontal text alignment for title text. One of ``"left"``, ``"center"``, or ``"right"``. anchor : dict, :class:`ExprRef`, :clas...
BaseTitleNoValueRefs
python
pytest-dev__pytest
testing/test_tmpdir.py
{ "start": 2334, "end": 11136 }
class ____: def test_getbasetemp_custom_removes_old(self, pytester: Pytester) -> None: mytemp = pytester.path.joinpath("xyz") p = pytester.makepyfile( """ def test_1(tmp_path): pass """ ) pytester.runpytest(p, f"--basetemp={mytemp}") ...
TestConfigTmpPath
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/roles.py
{ "start": 3300, "end": 3407 }
class ____(AllowsLambdaRole, ByOfRole): __slots__ = () _role_name = "ORDER BY expression"
OrderByRole
python
openai__openai-python
src/openai/resources/fine_tuning/fine_tuning.py
{ "start": 4216, "end": 4794 }
class ____: def __init__(self, fine_tuning: FineTuning) -> None: self._fine_tuning = fine_tuning @cached_property def jobs(self) -> JobsWithStreamingResponse: return JobsWithStreamingResponse(self._fine_tuning.jobs) @cached_property def checkpoints(self) -> CheckpointsWithStreaming...
FineTuningWithStreamingResponse
python
pytorch__pytorch
torch/_inductor/codegen/wrapper.py
{ "start": 27688, "end": 28327 }
class ____(MemoryPlanningLine): node: BufferLike reused_as: BufferLike layout: ir.Layout def plan(self, state: MemoryPlanningState) -> MemoryPlanningLine: return self def codegen(self, code: IndentedBuffer) -> None: assert isinstance(self.layout, ir.NonOwningLayout) assert ...
ReinterpretLine
python
getsentry__sentry
src/sentry/relocation/models/relocationtransfer.py
{ "start": 625, "end": 1405 }
class ____(DefaultFieldsModel): """ Base class for control + region relocation transfer models Relocation transfers are used to record a retriable state of a regional transfer for relocation data. These models replace outbox based transfers. """ __relocation_scope__ = RelocationScope.Exclu...
BaseRelocationTransfer
python
pypa__setuptools
pkg_resources/__init__.py
{ "start": 8567, "end": 9479 }
class ____(ResolutionError): """ An already-installed version conflicts with the requested version. Should be initialized with the installed Distribution and the requested Requirement. """ _template = "{self.dist} is installed but {self.req} is required" @property def dist(self) -> Di...
VersionConflict
python
conda__conda
conda/exceptions.py
{ "start": 20856, "end": 22791 }
class ____(CondaError): def __init__( self, message: str, url: str, status_code: int | str, reason: str, elapsed_time: timedelta | str, response: requests.Response | None = None, caused_by: Any = None, ): # if response includes a valid json...
CondaHTTPError
python
django-compressor__django-compressor
compressor/tests/test_offline.py
{ "start": 16261, "end": 16424 }
class ____(OfflineTestCaseMixin, TestCase): templates_dir = "test_static_templatetag" expected_hash = "be0b1eade28b"
OfflineCompressStaticTemplateTagTestCase
python
huggingface__transformers
tests/models/pvt_v2/test_modeling_pvt_v2.py
{ "start": 4960, "end": 9779 }
class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (PvtV2Model, PvtV2ForImageClassification) if is_torch_available() else () pipeline_model_mapping = ( {"feature-extraction": PvtV2Model, "image-classification": PvtV2ForImageClassification} if is_torch_avail...
PvtV2ModelTest
python
dask__distributed
distributed/client.py
{ "start": 213998, "end": 216475 }
class ____: """ Collect task stream within a context block This provides diagnostic information about every task that was run during the time when this block was active. This must be used as a context manager. Parameters ---------- plot: boolean, str If true then also return a...
get_task_stream
python
numba__numba
numba/cuda/tests/cudapy/test_matmul.py
{ "start": 324, "end": 2084 }
class ____(CUDATestCase): def test_func(self): @cuda.jit(void(float32[:, ::1], float32[:, ::1], float32[:, ::1])) def cu_square_matrix_mul(A, B, C): sA = cuda.shared.array(shape=SM_SIZE, dtype=float32) sB = cuda.shared.array(shape=(tpb, tpb), dtype=float32) tx ...
TestCudaMatMul
python
python-markdown__markdown
markdown/extensions/footnotes.py
{ "start": 9175, "end": 12868 }
class ____(BlockProcessor): """ Find footnote definitions and store for later use. """ RE = re.compile(r'^[ ]{0,3}\[\^([^\]]*)\]:[ ]*(.*)$', re.MULTILINE) def __init__(self, footnotes: FootnoteExtension): super().__init__(footnotes.parser) self.footnotes = footnotes def test(self, par...
FootnoteBlockProcessor
python
run-llama__llama_index
llama-index-integrations/retrievers/llama-index-retrievers-galaxia/llama_index/retrievers/galaxia/base.py
{ "start": 284, "end": 2880 }
class ____: def __init__( self, api_url: str, api_key: str, knowledge_base_id: str, n_retries: int, wait_time: int, ): self.api_url = api_url self.api_key = api_key self.knowledge_base_id = knowledge_base_id self.n_retries = n_retri...
GalaxiaClient
python
doocs__leetcode
solution/2400-2499/2412.Minimum Money Required Before Transactions/Solution.py
{ "start": 0, "end": 323 }
class ____: def minimumMoney(self, transactions: List[List[int]]) -> int: s = sum(max(0, a - b) for a, b in transactions) ans = 0 for a, b in transactions: if a > b: ans = max(ans, s + b) else: ans = max(ans, s + a) return ans
Solution
python
anthropics__anthropic-sdk-python
src/anthropic/resources/beta/files.py
{ "start": 26117, "end": 26779 }
class ____: def __init__(self, files: AsyncFiles) -> None: self._files = files self.list = async_to_streamed_response_wrapper( files.list, ) self.delete = async_to_streamed_response_wrapper( files.delete, ) self.download = async_to_custom_stre...
AsyncFilesWithStreamingResponse
python
redis__redis-py
redis/client.py
{ "start": 29864, "end": 50767 }
class ____: """ PubSub provides publish, subscribe and listen support to Redis channels. After subscribing to one or more channels, the listen() method will block until a message arrives on one of the subscribed channels. That message will be returned and it's safe to start listening again. """...
PubSub
python
scrapy__scrapy
scrapy/dupefilters.py
{ "start": 1318, "end": 4161 }
class ____(BaseDupeFilter): """Duplicate request filtering class (:setting:`DUPEFILTER_CLASS`) that filters out requests with the canonical (:func:`w3lib.url.canonicalize_url`) :attr:`~scrapy.http.Request.url`, :attr:`~scrapy.http.Request.method` and :attr:`~scrapy.http.Request.body`. """ def _...
RFPDupeFilter
python
realpython__materials
flask-connexion-rest-part-2/rp_flask_api/models.py
{ "start": 354, "end": 574 }
class ____(ma.SQLAlchemyAutoSchema): class Meta: model = Person load_instance = True sqla_session = db.session person_schema = PersonSchema() people_schema = PersonSchema(many=True)
PersonSchema
python
wandb__wandb
wandb/sdk/launch/agent/config.py
{ "start": 734, "end": 856 }
class ____(str, Enum): """Enum of valid registry types.""" ecr = "ecr" acr = "acr" gcr = "gcr"
RegistryType
python
huggingface__transformers
tests/models/swiftformer/test_modeling_swiftformer.py
{ "start": 1391, "end": 4370 }
class ____: def __init__( self, parent, batch_size=13, num_channels=3, is_training=True, use_labels=True, hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, image_size=224, num_labels=3, layer_depths=[1, 1, 1, 1], ...
SwiftFormerModelTester
python
scipy__scipy
benchmarks/benchmarks/optimize.py
{ "start": 15428, "end": 16991 }
class ____(Benchmark): """Class for benchmarking nonlinear least squares solvers.""" problems = extract_lsq_problems() params = [ list(problems.keys()), ["average time", "nfev", "success"] ] param_names = [ "problem", "result type" ] def track_all(self, problem_name,...
BenchLeastSquares
python
lepture__authlib
authlib/common/errors.py
{ "start": 743, "end": 1615 }
class ____(AuthlibBaseError): #: HTTP status code status_code = 400 def __init__(self, error=None, description=None, uri=None, status_code=None): super().__init__(error, description, uri) if status_code is not None: self.status_code = status_code def get_error_description(s...
AuthlibHTTPError
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/nn_ops/conv_ops_test.py
{ "start": 136135, "end": 145807 }
class ____(test.TestCase): def _CreateNumpyTensor(self, shape): total_size = np.prod(shape) return np.arange(1, total_size + 1, dtype=np.float32).reshape(shape) def _CreateConv2D(self, input_values, filters, strides=[1, 1], pa...
FusedConv2DTest
python
huggingface__transformers
src/transformers/models/idefics2/image_processing_idefics2.py
{ "start": 5266, "end": 26717 }
class ____(BaseImageProcessor): r""" Constructs a Idefics image processor. Args: do_convert_rgb (`bool`, *optional*, defaults to `True`): Whether to convert the image to RGB. This is useful if the input image is of a different format e.g. RGBA. Only has an effect if the inpu...
Idefics2ImageProcessor
python
doocs__leetcode
solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.py
{ "start": 0, "end": 300 }
class ____: def numMovesStones(self, a: int, b: int, c: int) -> List[int]: x, z = min(a, b, c), max(a, b, c) y = a + b + c - x - z mi = mx = 0 if z - x > 2: mi = 1 if y - x < 3 or z - y < 3 else 2 mx = z - x - 2 return [mi, mx]
Solution
python
kamyu104__LeetCode-Solutions
Python/single-number-iii.py
{ "start": 369, "end": 712 }
class ____(object): # @param {integer[]} nums # @return {integer[]} def singleNumber(self, nums): x_xor_y = 0 for i in nums: x_xor_y ^= i bit = x_xor_y & ~(x_xor_y - 1) x = 0 for i in nums: if i & bit: x ^= i return [...
Solution2
python
pexpect__pexpect
pexpect/spawnbase.py
{ "start": 276, "end": 478 }
class ____(object): """Pass bytes through unchanged.""" @staticmethod def encode(b, final=False): return b @staticmethod def decode(b, final=False): return b
_NullCoder
python
pypa__warehouse
tests/unit/packaging/test_models.py
{ "start": 1544, "end": 1715 }
class ____: def test_repr(self, db_request): role_invitation = DBRoleInvitationFactory() assert isinstance(repr(role_invitation), str)
TestRoleInvitation
python
jazzband__django-waffle
waffle/tests/test_admin.py
{ "start": 1105, "end": 4517 }
class ____(TestCase): def setUp(self): super().setUp() self.site = AdminSite() self.flag_admin = FlagAdmin(Flag, self.site) def test_informative_widget(self): request = mock.Mock() request.has_perm = lambda self, perm: True form = self.flag_admin.get_form(request...
FlagAdminTests
python
pydantic__pydantic
tests/test_type_adapter.py
{ "start": 969, "end": 26010 }
class ____(NamedTuple): x: int @pytest.mark.parametrize( 'tp, val, expected', [ (PydanticModel, PydanticModel(x=1), PydanticModel(x=1)), (PydanticModel, {'x': 1}, PydanticModel(x=1)), (SomeTypedDict, {'x': 1}, {'x': 1}), (SomeNamedTuple, SomeNamedTuple(x=1), SomeNamedTuple(...
SomeNamedTuple
python
getsentry__sentry
src/sentry/web/frontend/debug/debug_incident_trigger_email.py
{ "start": 1035, "end": 3284 }
class ____(MailPreviewView): @mock.patch( "sentry.incidents.models.incident.IncidentTrigger.objects.get", return_value=MockedIncidentTrigger(), ) @mock.patch( "sentry.users.models.user_option.UserOption.objects.get_value", return_value="US/Pacific" ) def get_context(self, req...
DebugIncidentTriggerEmailView
python
scikit-image__scikit-image
benchmarks/benchmark_segmentation.py
{ "start": 458, "end": 2454 }
class ____: """Benchmark for segmentation routines in scikit-image.""" def setup(self): self.image = np.random.random((200, 200, 100)) self.image[:100, :100, :] += 1 self.image[150:, 150:, :] += 0.5 self.msk = np.zeros((200, 200, 100)) self.msk[10:-10, 10:-10, 10:-10] = ...
SlicSegmentation
python
django__django
tests/modeladmin/test_checks.py
{ "start": 7953, "end": 8832 }
class ____(CheckTestCase): def test_duplicate_fields_in_fields(self): class TestModelAdmin(ModelAdmin): fields = ["name", "name"] self.assertIsInvalid( TestModelAdmin, ValidationTestModel, "The value of 'fields' contains duplicate field(s).", ...
FieldsCheckTests
python
PyCQA__pylint
tests/functional/u/unused/unused_argument.py
{ "start": 2494, "end": 2783 }
class ____: """dummy class""" def __init__(self, arg): # [unused-argument] """Constructor with an extra parameter. Should raise a warning""" self.spam = 1 # Regression test for https://github.com/pylint-dev/pylint/issues/5771 # involving keyword-only arguments
BBBB
python
Textualize__textual
docs/examples/widgets/text_area_custom_language.py
{ "start": 415, "end": 885 }
class ____(App): def compose(self) -> ComposeResult: text_area = TextArea.code_editor(text=java_code) text_area.cursor_blink = False # Register the Java language and highlight query text_area.register_language("java", java_language, java_highlight_query) # Switch to Java ...
TextAreaCustomLanguage
python
great-expectations__great_expectations
great_expectations/expectations/core/expect_column_values_to_match_json_schema.py
{ "start": 1147, "end": 8151 }
class ____(ColumnMapExpectation): """Expect the column entries to be JSON objects matching a given JSON schema. ExpectColumnValuesToMatchJsonSchema is a \ Column Map Expectation. Args: column (str): \ The column name. json_schema (dict): \ The JSON schema to ma...
ExpectColumnValuesToMatchJsonSchema
python
PrefectHQ__prefect
tests/test_futures.py
{ "start": 21914, "end": 25030 }
class ____: def test_wait(self): mock_futures = [MockFuture(data=i) for i in range(5)] futures = PrefectFutureList(mock_futures) # should not raise a TimeoutError futures.wait() for future in futures: assert future.state.is_completed() @pytest.mark.timeout(m...
TestPrefectFutureList
python
apache__airflow
providers/sftp/src/airflow/providers/sftp/exceptions.py
{ "start": 871, "end": 1011 }
class ____(AirflowException): """Thrown when a connection has not been opened and has been tried to be used."""
ConnectionNotOpenedException
python
airbytehq__airbyte
airbyte-integrations/connectors/source-mixpanel/source_mixpanel/components.py
{ "start": 3840, "end": 4565 }
class ____(MixpanelHttpRequester): def get_request_params( self, *, stream_state: Optional[StreamState] = None, stream_slice: Optional[StreamSlice] = None, next_page_token: Optional[Mapping[str, Any]] = None, ) -> MutableMapping[str, Any]: params = super().get_req...
EngagesHttpRequester
python
getsentry__sentry-python
sentry_sdk/integrations/opentelemetry/span_processor.py
{ "start": 1919, "end": 13143 }
class ____(SpanProcessor): """ Converts OTel spans into Sentry spans so they can be sent to the Sentry backend. """ # The mapping from otel span ids to sentry spans otel_span_map = {} # type: dict[str, Union[Transaction, SentrySpan]] # The currently open spans. Elements will be discarded afte...
SentrySpanProcessor
python
charliermarsh__ruff
crates/ruff_linter/resources/test/fixtures/flake8_pytest_style/PT023.py
{ "start": 525, "end": 735 }
class ____: class TestNestedClass: @pytest.mark.foo def test_something(): pass # With parentheses @pytest.mark.foo() def test_something(): pass @pytest.mark.foo()
TestClass
python
dask__dask
dask/dataframe/dask_expr/_expr.py
{ "start": 26984, "end": 28682 }
class ____(Expr): _parameters = [ "frame", "func", "before", "after", "meta", "enforce_metadata", "transform_divisions", "clear_divisions", "align_dataframes", "token", "kwargs", ] _defaults = { "meta": None, ...
MapOverlapAlign
python
langchain-ai__langchain
libs/langchain/tests/mock_servers/robot/server.py
{ "start": 679, "end": 1128 }
class ____(str, Enum): location = "location" walking = "walking" speed = "speed" direction = "direction" style = "style" cautiousness = "cautiousness" jumping = "jumping" destruct = "destruct" _ROBOT_STATE = { "location": _ROBOT_LOCATION, "walking": False, "speed": 0, "...
StateItems
python
numba__numba
numba/cuda/cudadrv/driver.py
{ "start": 72250, "end": 72991 }
class ____(object): def __init__(self, memptr, view=None): self._mem = memptr if view is None: self._view = self._mem else: assert not view.is_managed self._view = view mem = self._mem def deref(): try: mem.re...
OwnedPointer
python
airbytehq__airbyte
airbyte-integrations/connectors/source-linkedin-ads/unit_tests/test_source.py
{ "start": 8670, "end": 15498 }
class ____: @pytest.fixture def accounts_stream(self) -> Stream: return find_stream("accounts", TEST_CONFIG) @pytest.fixture def accounts_stream_url(self, accounts_stream) -> str: return f"{accounts_stream._stream_partition_generator._partition_factory._retriever.requester.url_base}/{ac...
TestLinkedinAdsStream
python
huggingface__transformers
src/transformers/models/audioflamingo3/modeling_audioflamingo3.py
{ "start": 16386, "end": 17435 }
class ____(nn.Module): """ Audio adaptor (small MLP) that projects AudioFlamingo3Encoder features to the LLM embedding space so they can replace `<sound>` tokens. """ def __init__(self, config: AudioFlamingo3Config): super().__init__() self.linear_1 = nn.Linear( config.a...
AudioFlamingo3MultiModalProjector
python
sqlalchemy__sqlalchemy
test/sql/test_operators.py
{ "start": 27528, "end": 28118 }
class ____(_CustomComparatorTests, fixtures.TestBase): def _add_override_factory(self): class MyInteger(TypeDecorator): impl = Integer cache_ok = True class comparator_factory(TypeDecorator.Comparator): def __init__(self, expr): super(...
TypeDecoratorComparatorTest
python
ray-project__ray
python/ray/serve/_private/replica_result.py
{ "start": 1814, "end": 8817 }
class ____(ReplicaResult): def __init__( self, obj_ref_or_gen: Union[ray.ObjectRef, ray.ObjectRefGenerator], metadata: RequestMetadata, *, with_rejection: bool = False, ): self._obj_ref: Optional[ray.ObjectRef] = None self._obj_ref_gen: Optional[ray.Object...
ActorReplicaResult
python
getsentry__sentry
tests/sentry/workflow_engine/processors/contexts/test_workflow_event_context.py
{ "start": 1132, "end": 2793 }
class ____(WorkflowEventContextTestCase): def test_set_and_get(self) -> None: detector = self.create_detector() organization = self.organization environment = self.create_environment() ctx_data = WorkflowEventContextData( detector=detector, organization=organ...
TestWorkflowEventContext
python
kamyu104__LeetCode-Solutions
Python/minimum-time-to-kill-all-monsters.py
{ "start": 52, "end": 690 }
class ____(object): def minimumTime(self, power): """ :type power: List[int] :rtype: int """ def ceil_divide(a, b): return (a+b-1)//b INF = float("inf") dp = {0:0} for gain in xrange(1, len(power)+1): new_dp = collections.defau...
Solution