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
great-expectations__great_expectations
tests/core/test_expectation_suite.py
{ "start": 49382, "end": 55773 }
class ____: @pytest.mark.unit def test_hash_consistency_with_equality(self, empty_data_context): expectation1 = ExpectColumnValuesToNotBeNull(column="test_column") expectation2 = ExpectColumnValuesToNotBeNull(column="test_column") suite1 = ExpectationSuite(name="test_suite") sui...
TestExpectationSuiteHash
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 355701, "end": 356349 }
class ____(sgqlc.types.relay.Connection): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("edges", "nodes", "page_info", "total_count") edges = sgqlc.types.Field( sgqlc.types.list_of("IpAllowListEntryEdge"), graphql_name="edges" ) nodes = sg...
IpAllowListEntryConnection
python
PrefectHQ__prefect
tests/server/orchestration/api/test_flows.py
{ "start": 247, "end": 2508 }
class ____: async def test_create_flow(self, session, client): flow_data = {"name": "my-flow", "labels": {"env": "dev"}} response = await client.post("/flows/", json=flow_data) assert response.status_code == status.HTTP_201_CREATED assert response.json()["name"] == "my-flow" ...
TestCreateFlow
python
pytorch__pytorch
torch/_inductor/codegen/wrapper.py
{ "start": 26517, "end": 27688 }
class ____(MemoryPlanningLine): node: BufferLike is_reused: bool = False def __post_init__(self): assert V.graph.scheduler.current_node is not None self.scheduler_node_index = V.graph.scheduler.nodes.index( V.graph.scheduler.current_node ) def plan(self, state: Memo...
FreeIfNotReusedLine
python
neetcode-gh__leetcode
python/0079-word-search.py
{ "start": 0, "end": 1153 }
class ____: def exist(self, board: List[List[str]], word: str) -> bool: ROWS, COLS = len(board), len(board[0]) path = set() def dfs(r, c, i): if i == len(word): return True if ( min(r, c) < 0 or r >= ROWS ...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-bing-ads/unit_tests/integrations/test_product_dimension_performance_report.py
{ "start": 1859, "end": 10958 }
class ____(TestBaseProductDimensionPerformanceReport): stream_name = "product_dimension_performance_report_daily" report_file = "product_dimension_performance_report_daily" incremental_report_file = "product_dimension_performance_report_daily_incremental" incremental_report_file_with_records_further_cur...
TestProductDimensionPerformanceReportDailyStream
python
doocs__leetcode
lcof/面试题14- II. 剪绳子 II/Solution.py
{ "start": 0, "end": 310 }
class ____: def cuttingRope(self, n: int) -> int: mod = 10**9 + 7 if n < 4: return n - 1 if n % 3 == 0: return pow(3, n // 3, mod) if n % 3 == 1: return (pow(3, n // 3 - 1, mod) * 4) % mod return pow(3, n // 3, mod) * 2 % mod
Solution
python
pydantic__pydantic
pydantic/plugin/_schema_validator.py
{ "start": 1581, "end": 5267 }
class ____: """Pluggable schema validator.""" __slots__ = '_schema_validator', 'validate_json', 'validate_python', 'validate_strings' def __init__( self, schema: CoreSchema, schema_type: Any, schema_type_path: SchemaTypePath, schema_kind: SchemaKind, config:...
PluggableSchemaValidator
python
xlwings__xlwings
xlwings/base_classes.py
{ "start": 14278, "end": 14827 }
class ____: # @property # def api(self): # raise NotImplementedError() def delete(self): raise NotImplementedError() @property def name(self): raise NotImplementedError() @name.setter def name(self, value): raise NotImplementedError() @property def...
Name
python
PrefectHQ__prefect
tests/test_flows.py
{ "start": 64721, "end": 67247 }
class ____: @pytest.mark.clear_db async def test_subflow_logs_are_written_correctly(self, prefect_client): @flow def my_subflow(): logger = get_run_logger() logger.info("Hello smaller world!") @flow def my_flow(): logger = get_run_logger() ...
TestSubflowRunLogs
python
jazzband__django-simple-history
simple_history/tests/models.py
{ "start": 3907, "end": 4073 }
class ____(models.Model): question = models.CharField(max_length=200) history = HistoricalRecords(bases=[SessionsHistoricalModel])
PollWithHistoricalSessionAttr
python
coleifer__peewee
peewee.py
{ "start": 90712, "end": 92987 }
class ____(Node): def __init__(self, name, table, expressions, unique=False, safe=False, where=None, using=None): self._name = name self._table = Entity(table) if not isinstance(table, Table) else table self._expressions = expressions self._where = where self...
Index
python
ray-project__ray
python/ray/tune/tests/test_progress_reporter.py
{ "start": 14713, "end": 35772 }
class ____(unittest.TestCase): def setUp(self) -> None: os.environ["TUNE_MAX_PENDING_TRIALS_PG"] = "auto" os.environ["RAY_AIR_NEW_OUTPUT"] = "0" def mock_trial(self, status, i): mock = MagicMock() mock.status = status mock.trial_id = "%05d" % i return mock d...
ProgressReporterTest
python
getsentry__sentry
src/sentry/integrations/api/endpoints/external_user_details.py
{ "start": 1215, "end": 3829 }
class ____(OrganizationEndpoint, ExternalActorEndpointMixin): owner = ApiOwner.ECOSYSTEM permission_classes = (ExternalUserPermission,) publish_status = { "DELETE": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } def convert_args( self, request: Request, ...
ExternalUserDetailsEndpoint
python
pytorch__pytorch
test/torch_np/test_reductions.py
{ "start": 5237, "end": 10667 }
class ____(TestCase): def test_sum(self): m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] tgt = [[6], [15], [24]] out = np.sum(m, axis=1, keepdims=True) assert_equal(tgt, out) am = np.asarray(m) assert_equal(np.sum(m), am.sum()) def test_sum_stability(self): a = n...
TestSum
python
Textualize__textual
tests/test_lazy.py
{ "start": 169, "end": 785 }
class ____(App): def compose(self) -> ComposeResult: with Vertical(): with Lazy(Horizontal()): yield Label(id="foo") with Horizontal(): yield Label(id="bar") async def test_lazy(): app = LazyApp() async with app.run_test() as pilot: #...
LazyApp
python
pydata__xarray
asv_bench/benchmarks/indexing.py
{ "start": 5081, "end": 5252 }
class ____(Indexing): def setup(self, key): requires_dask() super().setup(key) self.ds = self.ds.chunk({"x": 100, "y": 50, "t": 50})
IndexingDask
python
pytorch__pytorch
torch/_dynamo/mutation_guard.py
{ "start": 2291, "end": 5166 }
class ____: generation: int = 0 dynamic_classes: ExactWeakKeyDictionary = ExactWeakKeyDictionary() generation_values: ExactWeakKeyDictionary = ExactWeakKeyDictionary() @classmethod def tag(cls, obj: Any) -> None: cls.generation_values[obj] = cls.generation @staticmethod def mark_cl...
GenerationTracker
python
ray-project__ray
python/ray/data/examples/data/video_processing/video_processor.py
{ "start": 1484, "end": 1696 }
class ____(BaseModel): """Lightweight sampling configuration for ``VideoProcessor``.""" fps: Optional[float] = None num_frames: Optional[int] = None class Config: extra = "forbid"
Sampling
python
anthropics__anthropic-sdk-python
src/anthropic/types/citation_web_search_result_location_param.py
{ "start": 264, "end": 517 }
class ____(TypedDict, total=False): cited_text: Required[str] encrypted_index: Required[str] title: Required[Optional[str]] type: Required[Literal["web_search_result_location"]] url: Required[str]
CitationWebSearchResultLocationParam
python
langchain-ai__langchain
libs/cli/langchain_cli/utils/packages.py
{ "start": 1070, "end": 2347 }
class ____(TypedDict): """Fields from `pyproject.toml` that are relevant to LangServe. Attributes: module: The module to import from, `tool.langserve.export_module` attr: The attribute to import from the module, `tool.langserve.export_attr` package_name: The name of the package, `tool.p...
LangServeExport
python
kamyu104__LeetCode-Solutions
Python/range-sum-of-sorted-subarray-sums.py
{ "start": 1876, "end": 2507 }
class ____(object): def rangeSum(self, nums, n, left, right): """ :type nums: List[int] :type n: int :type left: int :type right: int :rtype: int """ MOD = 10**9+7 min_heap = [] for i, num in enumerate(nums, 1): heapq.heappu...
Solution2
python
airbytehq__airbyte
airbyte-integrations/connectors/source-instagram/components.py
{ "start": 8671, "end": 10295 }
class ____(RecordTransformation): """ The transformation flattens a nested array of breakdown results located at total_value.breakdowns[0].results into a single object (dictionary). In this transformation, each key-value pair in the resulting object represents a dimension and its corresponding value. E...
InstagramBreakDownResultsTransformation
python
apache__airflow
providers/google/src/airflow/providers/google/common/hooks/discovery_api.py
{ "start": 1086, "end": 6482 }
class ____(GoogleBaseHook): """ A hook to use the Google API Discovery Service. :param api_service_name: The name of the api service that is needed to get the data for example 'youtube'. :param api_version: The version of the api that will be requested for example 'v3'. :param gcp_conn_id: ...
GoogleDiscoveryApiHook
python
PyCQA__pylint
pylint/checkers/classes/class_checker.py
{ "start": 26741, "end": 27466 }
class ____: """Store the accessed variables per scope.""" def __init__(self) -> None: self._scopes: defaultdict[ nodes.ClassDef, defaultdict[str, list[_AccessNodes]] ] = defaultdict(_scope_default) def set_accessed(self, node: _AccessNodes) -> None: """Set the given nod...
ScopeAccessMap
python
encode__django-rest-framework
tests/test_model_serializer.py
{ "start": 1262, "end": 2780 }
class ____(models.Model): """ A model class for testing regular flat fields. """ auto_field = models.AutoField(primary_key=True) big_integer_field = models.BigIntegerField() boolean_field = models.BooleanField(default=False) char_field = models.CharField(max_length=100) comma_separated_i...
RegularFieldsModel
python
doocs__leetcode
solution/1500-1599/1524.Number of Sub-arrays With Odd Sum/Solution.py
{ "start": 0, "end": 269 }
class ____: def numOfSubarrays(self, arr: List[int]) -> int: mod = 10**9 + 7 cnt = [1, 0] ans = s = 0 for x in arr: s += x ans = (ans + cnt[s & 1 ^ 1]) % mod cnt[s & 1] += 1 return ans
Solution
python
Lightning-AI__lightning
tests/tests_pytorch/trainer/optimization/test_manual_optimization.py
{ "start": 10311, "end": 20030 }
class ____(collections.abc.Mapping): """A custom implementation of Mapping for testing purposes.""" def __init__(self, *args, **kwargs): self._store = dict(*args, **kwargs) def __getitem__(self, key): return self._store[key] def __iter__(self): return iter(self._store) de...
CustomMapping
python
PrefectHQ__prefect
src/prefect/server/events/storage/__init__.py
{ "start": 354, "end": 2793 }
class ____(ValueError): pass def to_page_token( filter: "EventFilter", count: int, page_size: int, current_offset: int ) -> Optional[str]: if current_offset + page_size >= count: return None return b64encode( json.dumps( { "filter": filter.model_dump(mode="...
InvalidTokenError
python
getsentry__sentry
src/sentry/apidocs/examples/session_examples.py
{ "start": 51, "end": 1104 }
class ____: QUERY_SESSIONS = [ OpenApiExample( "Query Sessions", value={ "groups": [ { "by": {"session.status": "errored"}, "totals": {"sum(session)": 1000}, "series": {"sum(se...
SessionExamples
python
huggingface__transformers
src/transformers/models/gpt_neo/modeling_gpt_neo.py
{ "start": 6920, "end": 11785 }
class ____(GPTNeoSelfAttention): """ GPTNeo flash attention module. This module inherits from `GPTNeoSelfAttention` as the weights of the module stays untouched. The only required change would be on the forward pass where it needs to correctly call the public API of flash attention and deal with padding...
GPTNeoFlashAttention2
python
django-extensions__django-extensions
django_extensions/management/commands/dumpscript.py
{ "start": 8650, "end": 15519 }
class ____(Code): """Produces a python script that can recreate data for a given model instance.""" def __init__( self, instance, id, context=None, stdout=None, stderr=None, options=None ): """We need the instance in question and an id""" super().__init__(indent=0, stdout=stdout, s...
InstanceCode
python
ray-project__ray
python/ray/dashboard/utils.py
{ "start": 14758, "end": 16177 }
class ____(Immutable, Sequence): """Makes a :class:`list` immutable.""" __slots__ = ("_list", "_proxy") def __init__(self, list_value): if type(list_value) not in (list, ImmutableList): raise TypeError(f"{type(list_value)} object is not a list.") if isinstance(list_value, Immut...
ImmutableList
python
great-expectations__great_expectations
great_expectations/datasource/fluent/sql_datasource.py
{ "start": 7446, "end": 7833 }
class ____(_PartitionerDatetime): column_name: str sort_ascending: bool = True method_name: Literal["partition_on_year"] = "partition_on_year" @property @override def param_names(self) -> List[str]: return ["year"] @override def partitioner_method_kwargs(self) -> Dict[str, Any]...
SqlPartitionerYear
python
jina-ai__jina
tests/docker_compose/custom-gateway/dummy_gateway.py
{ "start": 361, "end": 1660 }
class ____(Gateway): def __init__( self, arg1: str = None, arg2: str = None, arg3: str = 'default-arg3', **kwargs ): super().__init__(**kwargs) self.arg1 = arg1 self.arg2 = arg2 self.arg3 = arg3 async def setup_server(self): from fastapi import FastAPI ...
DummyGateway
python
doocs__leetcode
solution/1500-1599/1515.Best Position for a Service Centre/Solution.py
{ "start": 0, "end": 807 }
class ____: def getMinDistSum(self, positions: List[List[int]]) -> float: n = len(positions) x = y = 0 for x1, y1 in positions: x += x1 y += y1 x, y = x / n, y / n decay = 0.999 eps = 1e-6 alpha = 0.5 while 1: grad_x...
Solution
python
pypa__setuptools
setuptools/command/build.py
{ "start": 462, "end": 6052 }
class ____(Protocol): """In order to support editable installations (see :pep:`660`) all build subcommands **SHOULD** implement this protocol. They also **MUST** inherit from ``setuptools.Command``. When creating an :pep:`editable wheel <660>`, ``setuptools`` will try to evaluate custom ``build`` s...
SubCommand
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/hooks/translate.py
{ "start": 2639, "end": 5696 }
class ____(GoogleBaseHook): """ Hook for Google Cloud translate APIs. All the methods in the hook where project_id is used must be called with keyword arguments rather than positional. """ def __init__( self, gcp_conn_id: str = "google_cloud_default", impersonation_chai...
CloudTranslateHook
python
numpy__numpy
numpy/_core/tests/test_scalarmath.py
{ "start": 33461, "end": 46217 }
class ____: @pytest.mark.parametrize("type_code", np.typecodes['AllInteger']) def test_integer_hashes(self, type_code): scalar = np.dtype(type_code).type for i in range(128): assert hash(i) == hash(scalar(i)) @pytest.mark.parametrize("type_code", np.typecodes['AllFloat']) de...
TestHash
python
getsentry__sentry
src/sentry/utils/kvstore/memory.py
{ "start": 297, "end": 1340 }
class ____(KVStorage[K, V]): """ This class provides an in-memory key/value store. It is intended for use in testing as a lightweight substitute for other backends. """ def __init__(self) -> None: self.__records: MutableMapping[K, Record[V]] = {} def get(self, key: K) -> V | None: ...
MemoryKVStorage
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/protocol29.py
{ "start": 317, "end": 576 }
class ____(Protocol[_T]): @property def func(self) -> Callable[..., _T]: ... def __new__( cls: type[Self], __func: Callable[..., _T], *args: Any, **kwargs: Any ) -> Self: ... def func1(x: Partial[int]): ... func1(partial(int))
Partial
python
coleifer__peewee
tests/apsw_ext.py
{ "start": 162, "end": 214 }
class ____(TestModel): username = TextField()
User
python
huggingface__transformers
src/transformers/models/llava_next_video/modular_llava_next_video.py
{ "start": 12242, "end": 12357 }
class ____(LlavaNextPreTrainedModel): input_modalities = ("image", "video", "text")
LlavaNextVideoPreTrainedModel
python
mlflow__mlflow
examples/sktime/flavor.py
{ "start": 19987, "end": 23456 }
class ____: def __init__(self, sktime_model): self.sktime_model = sktime_model def predict(self, dataframe, params: dict[str, Any] | None = None) -> pd.DataFrame: df_schema = dataframe.columns.values.tolist() if len(dataframe) > 1: raise MlflowException( f"T...
_SktimeModelWrapper
python
django__django
django/test/client.py
{ "start": 1794, "end": 2086 }
class ____(Exception): """The test client has been asked to follow a redirect loop.""" def __init__(self, message, last_response): super().__init__(message) self.last_response = last_response self.redirect_chain = last_response.redirect_chain
RedirectCycleError
python
numba__numba
numba/tests/test_typedlist.py
{ "start": 28728, "end": 30521 }
class ____(TestCase): def test_simple_refine_append(self): @njit def foo(): l = List() l.append(1) return l expected = foo.py_func() got = foo() self.assertEqual(expected, got) self.assertEqual(list(got), [1]) self.assertE...
TestListInferred
python
allegroai__clearml
clearml/binding/frameworks/tensorflow_bind.py
{ "start": 109988, "end": 114951 }
class ____(object): _current_task = None __patched = None @staticmethod def update_current_task(task: Any, **_: Any) -> None: PatchTensorflow2ModelIO._current_task = task if not task: return PatchTensorflow2ModelIO._patch_model_checkpoint() PostImportHookPatc...
PatchTensorflow2ModelIO
python
getsentry__sentry
src/sentry/dashboards/endpoints/organization_dashboards_starred.py
{ "start": 3031, "end": 4696 }
class ____(OrganizationEndpoint): publish_status = {"PUT": ApiPublishStatus.PRIVATE} owner = ApiOwner.DASHBOARDS permission_classes = (MemberPermission,) def has_feature(self, organization: Organization, request: Request) -> bool: return features.has( "organizations:dashboards-starr...
OrganizationDashboardsStarredOrderEndpoint
python
pytorch__pytorch
torch/utils/_python_dispatch.py
{ "start": 25526, "end": 25620 }
class ____: alias_set: set[str] is_write: bool name: str | None @dataclass
AliasInfo
python
lepture__authlib
tests/flask/test_oauth2/models.py
{ "start": 300, "end": 1767 }
class ____(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(40), unique=True, nullable=False) def get_user_id(self): return self.id def check_password(self, password): return password != "wrong" def generate_user_info(self, scopes=None): ...
User
python
mitmproxy__pdoc
test/testdata/misc.py
{ "start": 6958, "end": 7094 }
class ____(sched.scheduler): """Test for broken links for inherited methods, https://github.com/mitmproxy/pdoc/issues/490"""
scheduler
python
pytorch__pytorch
torch/testing/_internal/common_device_type.py
{ "start": 56726, "end": 59188 }
class ____: def __init__(self, num_required_devices): self.num_required_devices = num_required_devices def __call__(self, fn): assert not hasattr(fn, "num_required_devices"), ( f"deviceCountAtLeast redefinition for {fn.__name__}" ) fn.num_required_devices = self.num_...
deviceCountAtLeast
python
altair-viz__altair
altair/vegalite/v6/schema/core.py
{ "start": 1214637, "end": 1214846 }
class ____(AllSortString): """SortByChannelDesc schema wrapper.""" _schema = {"$ref": "#/definitions/SortByChannelDesc"} def __init__(self, *args): super().__init__(*args)
SortByChannelDesc
python
tensorflow__tensorflow
tensorflow/python/training/saver_large_variable_test.py
{ "start": 1175, "end": 2214 }
class ____(test.TestCase): # NOTE: This is in a separate file from saver_test.py because the # large allocations do not play well with TSAN, and cause flaky # failures. def testLargeVariable(self): save_path = os.path.join(self.get_temp_dir(), "large_variable") with session.Session("", graph=ops.Graph(...
SaverLargeVariableTest
python
wandb__wandb
wandb/automations/_filters/run_states.py
{ "start": 469, "end": 848 }
class ____(LenientStrEnum): # from: StateToReport RUNNING = "RUNNING" FINISHED = "FINISHED" FAILED = "FAILED" # Convenience aliases that are equivalent when *creating* or *editing* # the triggering event for a run state automation. # NOTE: These may still be reported as distinct values from an...
ReportedRunState
python
pytorch__pytorch
test/cpp/jit/tests_setup.py
{ "start": 784, "end": 1102 }
class ____(FileSetup): path = "ivalue.pt" def setup(self): ones = torch.ones(2, 2) twos = torch.ones(3, 5) * 2 value = (ones, twos) torch.save(value, self.path, _use_new_zipfile_serialization=True) # See testTorchSaveError in test/cpp/jit/tests.h for usage
SerializationInterop
python
ansible__ansible
lib/ansible/_internal/_templating/_jinja_common.py
{ "start": 6931, "end": 7401 }
class ____(Marker): """ An `Marker` value was previously encountered and reported. A subsequent `Marker` value (this instance) indicates the template may have been truncated as a result. It will only be visible if the previous `Marker` was ignored/replaced instead of being tripped, which would raise an ...
TruncationMarker
python
sanic-org__sanic
sanic/mixins/base.py
{ "start": 132, "end": 188 }
class ____(Protocol): __name__: str
DunderNameProtocol
python
tiangolo__fastapi
tests/test_security_openid_connect_description.py
{ "start": 302, "end": 2469 }
class ____(BaseModel): username: str def get_current_user(oauth_header: str = Security(oid)): user = User(username=oauth_header) return user @app.get("/users/me") def read_current_user(current_user: User = Depends(get_current_user)): return current_user client = TestClient(app) def test_security...
User
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/tryExcept1.py
{ "start": 758, "end": 841 }
class ____(BaseException): ... base_exceptions = (RuntimeError, NameError)
Exception1
python
pytorch__pytorch
test/test_fake_tensor.py
{ "start": 44849, "end": 48891 }
class ____(TestCase): def test_memoized_conversion_to_meta(self): x = torch.rand(2, 2, 2) mode = FakeTensorMode() self.assertTrue(mode.from_tensor(x) is mode.from_tensor(x)) def test_memoized_conversion_from_meta(self): x = torch.rand(2, 2).to(device="meta") mode = FakeT...
FakeTensorConverterTest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/definitions/metadata/metadata_value.py
{ "start": 19630, "end": 20407 }
class ____(MetadataValue[str], IHaveNew): """Container class for path metadata entry data. Args: path (str): The path as a string or conforming to os.PathLike. """ fspath: str def __new__(cls, path: Optional[Union[str, PathLike]]): return super().__new__( cls, ...
PathMetadataValue
python
python-openxml__python-docx
src/docx/oxml/table.py
{ "start": 4603, "end": 8588 }
class ____(BaseOxmlElement): """``<w:tbl>`` element.""" add_tr: Callable[[], CT_Row] tr_lst: list[CT_Row] tblPr: CT_TblPr = OneAndOnlyOne("w:tblPr") # pyright: ignore[reportAssignmentType] tblGrid: CT_TblGrid = OneAndOnlyOne("w:tblGrid") # pyright: ignore[reportAssignmentType] tr = ZeroOrMor...
CT_Tbl
python
ray-project__ray
doc/source/ray-core/doc_code/actor_checkpointing.py
{ "start": 588, "end": 1713 }
class ____: def __init__(self): self.worker = Worker.remote() self.worker_state = ray.get(self.worker.checkpoint.remote()) def execute_task_with_fault_tolerance(self): i = 0 while True: i = i + 1 try: ray.get(self.worker.execute_task.remot...
Controller
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/quantization_ops/quantization_ops_test.py
{ "start": 14234, "end": 14774 }
class ____(test_util.TensorFlowTestCase): @test_util.run_in_graph_and_eager_modes def test_invalid_inputs(self): inputs = constant_op.constant( np.int32(0), shape=[3, 3, 3, 3], dtype=dtypes.qint32) with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), ...
QuantizeDownAndShrinkRangeOpTest
python
urllib3__urllib3
test/contrib/test_socks.py
{ "start": 24218, "end": 25928 }
class ____(IPV4SocketDummyServerTestCase): """ Test that TLS behaves properly for SOCKS proxies. """ @pytest.mark.skipif(not HAS_SSL, reason="No TLS available") def test_basic_request(self) -> None: def request_handler(listener: socket.socket) -> None: sock = listener.accept()[0...
TestSOCKSWithTLS
python
pypa__pipenv
pipenv/patched/pip/_internal/index/collector.py
{ "start": 12953, "end": 16695 }
class ____: """ Responsible for collecting Link objects from all configured locations, making network requests as needed. The class's main method is its collect_sources() method. """ def __init__( self, session: PipSession, search_scope: SearchScope, index_looku...
LinkCollector
python
pandas-dev__pandas
pandas/tests/io/json/test_json_table_schema.py
{ "start": 7759, "end": 23684 }
class ____: def test_build_series(self): s = pd.Series([1, 2], name="a") s.index.name = "id" result = s.to_json(orient="table", date_format="iso") result = json.loads(result, object_pairs_hook=OrderedDict) assert "pandas_version" in result["schema"] result["schema"]....
TestTableOrient
python
wandb__wandb
wandb/vendor/graphql-core-1.1/wandb_graphql/language/lexer.py
{ "start": 797, "end": 1202 }
class ____(object): __slots__ = 'source', 'prev_position' def __init__(self, source): self.source = source self.prev_position = 0 def next_token(self, reset_position=None): if reset_position is None: reset_position = self.prev_position token = read_token(self.so...
Lexer
python
fluentpython__example-code-2e
15-more-types/cafeteria/cafeteria.py
{ "start": 80, "end": 132 }
class ____(Beverage): """Any fruit juice."""
Juice
python
kubernetes-client__python
kubernetes/client/models/v1_self_subject_access_review_spec.py
{ "start": 383, "end": 4837 }
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...
V1SelfSubjectAccessReviewSpec
python
walkccc__LeetCode
solutions/1373. Maximum Sum BST in Binary Tree/1373.py
{ "start": 47, "end": 161 }
class ____: isBST: bool | None = False mx: int | None = None mn: int | None = None summ: int | None = None
T
python
great-expectations__great_expectations
tests/integration/fluent/test_integration_datasource.py
{ "start": 21883, "end": 23768 }
class ____: context: EphemeralDataContext datasource: SparkDatasource dataframe: SparkDataFrame def _validate_whole_dataframe_batch_definition( context_source_frame: ContextPandasDataSourceAndFrame | ContextSparkDataSourceAndFrame, ): asset = context_source_frame.datasource.add_dataframe_asset(nam...
ContextSparkDataSourceAndFrame
python
kamyu104__LeetCode-Solutions
Python/minimum-rectangles-to-cover-points.py
{ "start": 48, "end": 469 }
class ____(object): def minRectanglesToCoverPoints(self, points, w): """ :type points: List[List[int]] :type w: int :rtype: int """ points.sort(key=lambda x: x[0]) result = 0 left = -(w+1) for right, _ in points: if right-left <= w:...
Solution
python
django__django
tests/composite_pk/tests.py
{ "start": 10341, "end": 16914 }
class ____(TestCase): fixtures = ["tenant"] def test_objects(self): tenant_1, tenant_2, tenant_3 = Tenant.objects.order_by("pk") self.assertEqual(tenant_1.id, 1) self.assertEqual(tenant_1.name, "Tenant 1") self.assertEqual(tenant_2.id, 2) self.assertEqual(tenant_2.name, ...
CompositePKFixturesTests
python
Netflix__metaflow
test/unit/inheritance/flows/comprehensive_linear_base.py
{ "start": 180, "end": 373 }
class ____(FlowSpec): """Base class with parameters""" alpha = Parameter("alpha", help="Alpha parameter", default=10) beta = Parameter("beta", help="Beta parameter", default=5)
BaseA
python
astropy__astropy
astropy/io/votable/exceptions.py
{ "start": 22722, "end": 23149 }
class ____(VOWarning, FutureWarning): """ The VO catalog database retrieved from the www is designed for a newer version of ``astropy.io.votable``. This may cause problems or limited features performing service queries. Consider upgrading ``astropy.io.votable`` to the latest version. """ ...
W24
python
huggingface__transformers
src/transformers/models/phimoe/modeling_phimoe.py
{ "start": 27002, "end": 33807 }
class ____(PhimoePreTrainedModel): def __init__(self, config: PhimoeConfig): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) self.lay...
PhimoeModel
python
encode__django-rest-framework
rest_framework/renderers.py
{ "start": 8943, "end": 14669 }
class ____(BaseRenderer): """ Renderers serializer data into an HTML form. If the serializer was instantiated without an object then this will return an HTML form not bound to any object, otherwise it will return an HTML form with the appropriate initial data populated from the object. Not...
HTMLFormRenderer
python
Netflix__metaflow
test/core/tests/dynamic_parameters.py
{ "start": 67, "end": 1928 }
class ____(MetaflowTest): PRIORITY = 3 SKIP_GRAPHS = [ "simple_switch", "nested_switch", "branch_in_switch", "foreach_in_switch", "switch_in_branch", "switch_in_foreach", "recursive_switch", "recursive_switch_inside_foreach", ] PARAMETERS =...
DynamicParameterTest
python
ray-project__ray
python/ray/data/_internal/metadata_exporter.py
{ "start": 1292, "end": 1527 }
class ____: """Represents a sub-stage within an operator in the DAG. Attributes: name: The name of the sub-stage. id: The unique identifier of the sub-stage. """ name: str id: str @dataclass
SubStage
python
huggingface__transformers
tests/models/prompt_depth_anything/test_modeling_prompt_depth_anything.py
{ "start": 8777, "end": 12546 }
class ____(unittest.TestCase): def test_inference_wo_prompt_depth(self): image_processor = AutoImageProcessor.from_pretrained("depth-anything/prompt-depth-anything-vits-hf") model = PromptDepthAnythingForDepthEstimation.from_pretrained( "depth-anything/prompt-depth-anything-vits-hf" ...
PromptDepthAnythingModelIntegrationTest
python
allegroai__clearml
clearml/backend_api/services/v2_9/tasks.py
{ "start": 172804, "end": 174002 }
class ____(Response): """ Response of tasks.edit_hyper_params endpoint. :param updated: Indicates if the task was updated successfully :type updated: int """ _service = "tasks" _action = "edit_hyper_params" _version = "2.9" _schema = { "definitions": {}, "properties...
EditHyperParamsResponse
python
huggingface__transformers
src/transformers/models/hunyuan_v1_moe/modular_hunyuan_v1_moe.py
{ "start": 8005, "end": 8082 }
class ____(HunYuanDenseV1RotaryEmbedding): pass
HunYuanMoEV1RotaryEmbedding
python
great-expectations__great_expectations
docs/docusaurus/versioned_docs/version-0.18/oss/guides/expectations/creating_custom_expectations/expect_batch_columns_to_be_unique.py
{ "start": 3431, "end": 9233 }
class ____(BatchExpectation): # </snippet> # <snippet name="docs/docusaurus/docs/oss/guides/expectations/creating_custom_expectations/expect_batch_columns_to_be_unique.py docstring"> """Expect batch to contain columns with unique contents.""" # </snippet> strict: bool = True # These examples w...
ExpectBatchColumnsToBeUnique
python
allegroai__clearml
clearml/utilities/pigar/__main__.py
{ "start": 356, "end": 8897 }
class ____(object): _force_modules_reqs = dict() def __init__( self, save_path: str, project_path: str, ignores: list, installed_pkgs: dict, comparison_operator: str = "==", ) -> None: self._save_path = save_path self._project_path = project_p...
GenerateReqs
python
davidhalter__jedi
test/completion/dynamic_arrays.py
{ "start": 2876, "end": 5498 }
class ____(): def blub(self, b): if 1: a = [] a.append(b) return a def blub2(self): """ mapper function """ a = self.blub(1.0) #? float() a[0] return a def literal_arr(self, el): self.a = [] self.a.append(e...
C
python
doocs__leetcode
solution/1800-1899/1876.Substrings of Size Three with Distinct Characters/Solution.py
{ "start": 0, "end": 362 }
class ____: def countGoodSubstrings(self, s: str) -> int: ans = mask = l = 0 for r, x in enumerate(map(lambda c: ord(c) - 97, s)): while mask >> x & 1: y = ord(s[l]) - 97 mask ^= 1 << y l += 1 mask |= 1 << x ans += i...
Solution
python
ansible__ansible
lib/ansible/cli/vault.py
{ "start": 848, "end": 23195 }
class ____(CLI): """ can encrypt any structured data file used by Ansible. This can include *group_vars/* or *host_vars/* inventory variables, variables loaded by *include_vars* or *vars_files*, or variable files passed on the ansible-playbook command line with *-e @file.yml* or *-e @file.json*. Rol...
VaultCLI
python
huggingface__transformers
tests/models/musicgen_melody/test_processing_musicgen_melody.py
{ "start": 1762, "end": 6484 }
class ____(unittest.TestCase): def setUp(self): # Ignore copy self.checkpoint = "facebook/musicgen-melody" self.tmpdirname = tempfile.mkdtemp() def get_tokenizer(self, **kwargs): return T5Tokenizer.from_pretrained(self.checkpoint, **kwargs) def get_feature_extractor(self, *...
MusicgenMelodyProcessorTest
python
pytorch__pytorch
torch/utils/_python_dispatch.py
{ "start": 15117, "end": 25526 }
class ____(Protocol): def __tensor_flatten__(self) -> tuple[Sequence[str], object]: ... @staticmethod def __tensor_unflatten__( inner_tensors: int, flatten_spec: int, outer_size: int, outer_stride: int ) -> torch.Tensor: ... # It would be really nice to be able to say that the return of ...
TensorWithFlatten
python
huggingface__transformers
src/transformers/models/data2vec/modular_data2vec_audio.py
{ "start": 8848, "end": 8940 }
class ____(Wav2Vec2ForSequenceClassification): pass
Data2VecAudioForSequenceClassification
python
python__mypy
mypyc/irbuild/classdef.py
{ "start": 10330, "end": 12005 }
class ____(ClassBuilder): def __init__(self, builder: IRBuilder, cdef: ClassDef) -> None: super().__init__(builder, cdef) # If the class is not decorated, generate an extension class for it. self.type_obj: Value | None = allocate_class(builder, cdef) def skip_attr_default(self, name: st...
ExtClassBuilder
python
huggingface__transformers
examples/pytorch/speech-recognition/run_speech_recognition_ctc_adapter.py
{ "start": 4763, "end": 10353 }
class ____: """ Arguments pertaining to what data we are going to input our model for training and eval. Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify them on the command line. """ dataset_name: str = field( metadata={"help": "Path or...
DataTrainingArguments
python
django__django
django/contrib/gis/db/models/functions.py
{ "start": 9632, "end": 9735 }
class ____(OracleToleranceMixin, GeomOutputGeoFunc): arity = 2 geom_param_pos = (0, 1)
Difference
python
allegroai__clearml
clearml/backend_api/services/v2_23/tasks.py
{ "start": 522638, "end": 525076 }
class ____(Request): """ Unarchive tasks :param ids: IDs of the tasks to unarchive :type ids: Sequence[str] :param status_reason: Reason for status change :type status_reason: str :param status_message: Extra information regarding status change :type status_message: str """ _se...
UnarchiveManyRequest
python
tensorflow__tensorflow
tensorflow/python/distribute/cluster_resolver/tpu/tpu_cluster_resolver_test.py
{ "start": 3025, "end": 24702 }
class ____(test.TestCase): def _verifyClusterSpecEquality(self, cluster_spec, expected_proto): """Verifies that the ClusterSpec generates the correct proto. We are testing this four different ways to ensure that the ClusterSpec returned by the TPUClusterResolver behaves identically to a normal Clust...
TPUClusterResolverTest
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/memberAccess4.py
{ "start": 797, "end": 863 }
class ____(Mixin2): def must_have(self) -> None: pass
A2
python
kamyu104__LeetCode-Solutions
Python/number-of-dice-rolls-with-target-sum.py
{ "start": 37, "end": 602 }
class ____(object): def numRollsToTarget(self, d, f, target): """ :type d: int :type f: int :type target: int :rtype: int """ MOD = 10**9+7 dp = [[0 for _ in xrange(target+1)] for _ in xrange(2)] dp[0][0] = 1 for i in xrange(1, d+1): ...
Solution
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_chart_pattern08.py
{ "start": 315, "end": 3540 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("chart_pattern08.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.g...
TestCompareXLSXFiles