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/syndication_tests/feeds.py
{ "start": 3774, "end": 4104 }
class ____(TestRss2Feed): """ A feed to test that RSS feeds work with a single enclosure. """ def item_enclosure_url(self, item): return "http://example.com" def item_enclosure_size(self, item): return 0 def item_mime_type(self, item): return "image/png"
TestSingleEnclosureRSSFeed
python
openai__openai-python
src/openai/types/responses/response_function_web_search.py
{ "start": 380, "end": 535 }
class ____(BaseModel): type: Literal["url"] """The type of source. Always `url`.""" url: str """The URL of the source."""
ActionSearchSource
python
ansible__ansible
lib/ansible/_internal/_json/_profiles/_legacy.py
{ "start": 3081, "end": 6831 }
class ____(_profiles._JSONSerializationProfile["Encoder", "Decoder"]): visitor_type = _LegacyVariableVisitor @classmethod def serialize_untrusted(cls, value: _Untrusted) -> dict[str, str] | str: return dict( __ansible_unsafe=_datatag.AnsibleTagHelper.untag(value.value), ) @...
_Profile
python
huggingface__transformers
src/transformers/models/reformer/modeling_reformer.py
{ "start": 78796, "end": 80334 }
class ____(ModelOutput): r""" loss (`torch.FloatTensor` of shape *(1,)*, *optional*, returned when `labels` is provided): Language modeling loss (for next-token prediction). logits (`torch.FloatTensor` of shape `(batch_size, num_predict, config.vocab_size)`): Prediction scores of the languag...
ReformerModelWithLMHeadOutput
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/hooks/test_quicksight.py
{ "start": 3266, "end": 10559 }
class ____: def test_get_conn_returns_a_boto3_connection(self): hook = QuickSightHook(aws_conn_id="aws_default", region_name="us-east-1") assert hook.conn is not None @pytest.mark.parametrize( ("response", "expected_status"), [ pytest.param(MOCK_DESCRIBE_INGESTION_SU...
TestQuicksight
python
getsentry__sentry
tests/sentry/monitors/endpoints/test_base_monitor_checkin_index.py
{ "start": 509, "end": 9957 }
class ____(MonitorTestCase): __test__ = False def setUp(self) -> None: super().setUp() self.login_as(user=self.user) def create_error(self, platform, trace_id, project_id, timestamp): data = load_data(platform, timestamp=timestamp) if "contexts" not in data: dat...
BaseListMonitorCheckInsTest
python
pyparsing__pyparsing
pyparsing/core.py
{ "start": 152063, "end": 152643 }
class ____(PositionToken): """ Matches if current position is at the end of the parse string """ def __init__(self) -> None: super().__init__() self.set_name("end of text") def parseImpl(self, instring, loc, do_actions=True) -> ParseImplReturnType: if loc < len(instring): ...
StringEnd
python
doocs__leetcode
solution/3400-3499/3476.Maximize Profit from Task Assignment/Solution.py
{ "start": 0, "end": 469 }
class ____: def maxProfit(self, workers: List[int], tasks: List[List[int]]) -> int: d = defaultdict(SortedList) for skill, profit in tasks: d[skill].add(profit) ans = 0 for skill in workers: if not d[skill]: continue ans += d[skill]...
Solution
python
Netflix__metaflow
metaflow/plugins/pypi/parsers.py
{ "start": 133, "end": 8556 }
class ____(MetaflowException): headline = "Value error" def requirements_txt_parser(content: str): """ Parse non-comment lines from a requirements.txt file as strictly valid PEP 508 requirements. Recognizes direct references (e.g. "my_lib @ git+https://..."), extras (e.g. "requests[security]"...
ParserValueError
python
joke2k__faker
tests/test_unique.py
{ "start": 90, "end": 3093 }
class ____: def test_uniqueness(self): fake = Faker("en_US") names = set() # There are (at time of writing 690) first names in the # US identity provider. Birthday paradox puts the chances of # no duplicates in 250 selections as low enough to be impossible for i in r...
TestUniquenessClass
python
huggingface__transformers
src/transformers/models/clvp/modeling_clvp.py
{ "start": 53296, "end": 61403 }
class ____(ClvpPreTrainedModel, GenerationMixin): def __init__(self, config): super().__init__(config) self.config = config self.model = ClvpModel(self.config) self.final_norm = nn.LayerNorm(self.config.hidden_size) self.lm_head = nn.Linear(self.config.hidden_size, self.con...
ClvpForCausalLM
python
keon__algorithms
algorithms/tree/trie/trie.py
{ "start": 296, "end": 981 }
class ____: def __init__(self): self.root = TrieNode() def insert(self, word): current = self.root for letter in word: current = current.children[letter] current.is_word = True def search(self, word): current = self.root for letter in word: ...
Trie
python
airbytehq__airbyte
airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/resources/gcp.py
{ "start": 695, "end": 6910 }
class ____(GCSFileManager): """ Slighlty modified dagster_gcp.gcs.file_manager.GCSFileManager to allow setting the content type of the file """ def get_content_type(self, ext): if ext == "csv": return "text/csv" elif ext == "json": return "application/json" ...
ContentTypeAwareGCSFileManager
python
pytorch__pytorch
test/inductor/test_ordered_set.py
{ "start": 41398, "end": 43867 }
class ____(TestCase): def setUp(self): super().setUp() self.values = ["a", "b", "c"] self.OrderedSet = OrderedSet(self.values) def test_add_present(self): self.OrderedSet.add("c") self.assertEqual(self.OrderedSet, OrderedSet("abc")) def test_add_absent(self): ...
TestMutate
python
Netflix__metaflow
metaflow/plugins/datatools/s3/s3.py
{ "start": 2952, "end": 3034 }
class ____(MetaflowException): headline = "S3 access failed"
MetaflowS3Exception
python
streamlit__streamlit
lib/tests/streamlit/data_mocks/modin_mocks.py
{ "start": 1519, "end": 2269 }
class ____: """This is dummy Series class, which imitates modin.pandas.series.Series class for testing purposes. We use this to make sure that our code does a special handling if it detects a modin Series. This allows testing of the functionality without having the library installed, but it won't c...
Series
python
openai__openai-python
src/openai/_module_client.py
{ "start": 3215, "end": 3362 }
class ____(LazyProxy["Completions"]): @override def __load__(self) -> Completions: return _load_client().completions
CompletionsProxy
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/metrics_test.py
{ "start": 171485, "end": 173596 }
class ____(test.TestCase): def setUp(self): np.random.seed(1) ops.reset_default_graph() @test_util.run_deprecated_v1 def testVars(self): metrics.false_positives_at_thresholds( predictions=array_ops.ones((10, 1)), labels=array_ops.ones((10, 1)), thresholds=[0.15, 0.5, 0.85]) ...
FalsePositivesAtThresholdsTest
python
ipython__ipython
IPython/terminal/ipapp.py
{ "start": 6663, "end": 12512 }
class ____(BaseIPythonApplication, InteractiveShellApp): name = "ipython" description = usage.cl_usage crash_handler_class = IPAppCrashHandler # typing: ignore[assignment] examples = _examples flags = flags aliases = aliases classes = List() interactive_shell_class = Type( kla...
TerminalIPythonApp
python
numba__numba
numba/core/compiler_machinery.py
{ "start": 12834, "end": 14391 }
class ____(object): """ Pass registry singleton class. """ _id = 0 _registry = dict() def register(self, mutates_CFG, analysis_only): def make_festive(pass_class): assert not self.is_registered(pass_class) assert not self._does_pass_name_alias(pass_class.name()...
PassRegistry
python
scipy__scipy
scipy/linalg/_testutils.py
{ "start": 158, "end": 1807 }
class ____: def __init__(self, data): self._data = data def __array__(self, dtype=None, copy=None): if copy: return self._data.copy() return self._data def _get_array(shape, dtype): """ Get a test array of given shape and data type. Returned NxN matrices are po...
_FakeMatrix2
python
django__django
django/views/generic/detail.py
{ "start": 249, "end": 3664 }
class ____(ContextMixin): """ Provide the ability to retrieve a single object for further manipulation. """ model = None queryset = None slug_field = "slug" context_object_name = None slug_url_kwarg = "slug" pk_url_kwarg = "pk" query_pk_and_slug = False def get_object(self,...
SingleObjectMixin
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/generic3.py
{ "start": 708, "end": 888 }
class ____(Generic[_T1], Generic[_T2]): pass K = TypeVar("K") V = TypeVar("V") # This should generate an error because V isn't included # in the Generic type variable list.
Bar
python
pappasam__jedi-language-server
jedi_language_server/text_edit_utils.py
{ "start": 4336, "end": 5045 }
class ____(NamedTuple): """Typed opcode. Op can be one of the following values: 'replace': a[i1:i2] should be replaced by b[j1:j2] 'delete': a[i1:i2] should be deleted. Note that j1==j2 in this case. 'insert': b[j1:j2] should be inserted at a[i1:i1]. Note th...
Opcode
python
huggingface__transformers
tests/models/mobilenet_v1/test_image_processing_mobilenet_v1.py
{ "start": 2696, "end": 4337 }
class ____(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = MobileNetV1ImageProcessor if is_vision_available() else None fast_image_processing_class = MobileNetV1ImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() self.image_proc...
MobileNetV1ImageProcessingTest
python
dagster-io__dagster
python_modules/dagster/dagster/_core/storage/event_log/sqlite/sqlite_event_log.py
{ "start": 21684, "end": 23346 }
class ____(PatternMatchingEventHandler): def __init__( self, event_log_storage: SqliteEventLogStorage, run_id: str, callback: EventHandlerFn, cursor: Optional[str], **kwargs: Any, ): self._event_log_storage = check.inst_param( event_log_storage...
SqliteEventLogStorageWatchdog
python
Textualize__textual
docs/examples/how-to/layout.py
{ "start": 835, "end": 1113 }
class ____(Screen): def compose(self) -> ComposeResult: yield Header(id="Header") yield Footer(id="Footer") with HorizontalScroll(): yield Column() yield Column() yield Column() yield Column()
TweetScreen
python
google__pytype
pytype/overlays/special_builtins.py
{ "start": 21972, "end": 25635 }
class ____(abstract.Function, mixin.HasSlots): """Property instance (constructed by Property.call()).""" def __init__(self, ctx, name, cls, fget=None, fset=None, fdel=None, doc=None): super().__init__("property", ctx) mixin.HasSlots.init_mixin(self) self.name = name # Reports the correct decorator in ...
PropertyInstance
python
openai__openai-python
tests/api_resources/audio/test_transcriptions.py
{ "start": 4606, "end": 9149 }
class ____: parametrize = pytest.mark.parametrize( "async_client", [False, True, {"http_client": "aiohttp"}], indirect=True, ids=["loose", "strict", "aiohttp"] ) @parametrize async def test_method_create_overload_1(self, async_client: AsyncOpenAI) -> None: transcription = await async_cl...
TestAsyncTranscriptions
python
google__jax
jax/_src/mesh.py
{ "start": 7331, "end": 15117 }
class ____(BaseMesh, contextlib.ContextDecorator): """Declare the hardware resources available in the scope of this manager. See `Distributed arrays and automatic parallelization`_ and `Explicit Sharding`_ tutorials. Args: devices: A NumPy ndarray object containing JAX device objects (as obtained e....
Mesh
python
automl__auto-sklearn
autosklearn/metalearning/metafeatures/metafeatures.py
{ "start": 20819, "end": 21139 }
class ____(MetaFeature): def _calculate(self, X, y, logger, feat_type): kurts = helper_functions.get_value("Kurtosisses") maximum = np.nanmax(kurts) if len(kurts) > 0 else 0 return maximum if np.isfinite(maximum) else 0 @metafeatures.define("KurtosisMean", dependency="Kurtosisses")
KurtosisMax
python
sqlalchemy__sqlalchemy
test/sql/test_lambdas.py
{ "start": 1477, "end": 58342 }
class ____( fixtures.TestBase, testing.AssertsExecutionResults, AssertsCompiledSQL ): __dialect__ = "default" def test_reject_methods(self): """test #7032""" t1 = table("t1", column("q"), column("p")) subq = select(t1).subquery with expect_raises_message( exc....
LambdaElementTest
python
getsentry__sentry
tests/sentry/integrations/api/endpoints/test_organization_integration_channel_validate.py
{ "start": 4836, "end": 5856 }
class ____(BaseChannelValidateTest): def test_missing_channel_param(self): integration = self.create_integration( organization=self.organization, provider="slack", name="Slack", external_id="slack:1" ) resp = self.get_error_response(self.organization.slug, integration.id, status_...
ChannelValidateErrorCasesTest
python
scrapy__scrapy
tests/test_exporters.py
{ "start": 3694, "end": 5809 }
class ____(TestBaseItemExporter): def _get_exporter(self, **kwargs): return PythonItemExporter(**kwargs) def test_invalid_option(self): with pytest.raises(TypeError, match="Unexpected options: invalid_option"): PythonItemExporter(invalid_option="something") def test_nested_item...
TestPythonItemExporter
python
langchain-ai__langchain
libs/core/langchain_core/tracers/memory_stream.py
{ "start": 3406, "end": 4995 }
class ____(Generic[T]): """Stream data from a writer to a reader even if they are in different threads. Uses asyncio queues to communicate between two co-routines. This implementation should work even if the writer and reader co-routines belong to two different event loops (e.g. one running from an eve...
_MemoryStream
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 261483, "end": 262409 }
class ____(_PrintableStructure): _fields_ = [ ('version', c_uint), ('profileId', c_uint), ('paramId', c_uint), ('value', c_double), ] def __init__(self): super(c_nvmlPowerSmoothingProfile_v1_t, self).__init__(version=nvmlPowerSmoothingProfile_v1) def nvmlDevicePower...
c_nvmlPowerSmoothingProfile_v1_t
python
dask__dask
dask/dataframe/dask_expr/io/io.py
{ "start": 17158, "end": 18339 }
class ____(FromPandas): _parameters = [ "frame", "divisions", "columns", "pyarrow_strings_enabled", "_partitions", "_series", "_pd_length_stats", ] _defaults = { "columns": None, "_partitions": None, "_series": False, "_...
FromPandasDivisions
python
kamyu104__LeetCode-Solutions
Python/maximum-number-of-removable-characters.py
{ "start": 918, "end": 1758 }
class ____(object): def maximumRemovals(self, s, p, removable): """ :type s: str :type p: str :type removable: List[int] :rtype: int """ def check(s, p, lookup, x): j = 0 for i in xrange(len(s)): if lookup[i] <= x or s[i...
Solution2
python
allegroai__clearml
clearml/backend_api/services/v2_23/dataviews.py
{ "start": 30229, "end": 33119 }
class ____(NonStrictDataModel): """ :param cls: Augmentation class :type cls: str :param types: Augmentation type :type types: Sequence[str] :param strength: Augmentation strength. Range [0,). :type strength: float :param arguments: Arguments dictionary per custom augmentation type. ...
AugmentationSet
python
plotly__plotly.py
plotly/graph_objs/densitymapbox/hoverlabel/_font.py
{ "start": 233, "end": 17174 }
class ____(_BaseTraceHierarchyType): _parent_path_str = "densitymapbox.hoverlabel" _path_str = "densitymapbox.hoverlabel.font" _valid_props = { "color", "colorsrc", "family", "familysrc", "lineposition", "linepositionsrc", "shadow", "shadowsrc"...
Font
python
docker__docker-py
docker/models/containers.py
{ "start": 18559, "end": 46782 }
class ____(Collection): model = Container def run(self, image, command=None, stdout=True, stderr=False, remove=False, **kwargs): """ Run a container. By default, it will wait for the container to finish and return its logs, similar to ``docker run``. If the ``detach...
ContainerCollection
python
tensorflow__tensorflow
tensorflow/python/ops/parallel_for/math_test.py
{ "start": 23409, "end": 27654 }
class ____(PForTestCase): def test_cholesky(self): z = random_ops.random_normal([2, 3, 3]) x = ( math_ops.matmul(z, array_ops.matrix_transpose(z)) # Ensure pos. def. + linalg_ops.eye(3)) # Ensure well-conditioned. def loop_fn(i): return linalg_ops.cholesky(array_ops.gather(x, i))...
LinalgTest
python
facebook__pyre-check
stubs/integration_test/fixture_source/integration_test/cache.py
{ "start": 573, "end": 625 }
class ____: def method(self, x): pass
Base
python
scipy__scipy
scipy/stats/_continuous_distns.py
{ "start": 356170, "end": 366279 }
class ____(rv_continuous): r"""A Von Mises continuous random variable. %(before_notes)s See Also -------- scipy.stats.vonmises_fisher : Von-Mises Fisher distribution on a hypersphere Notes ----- The probability density function for `vonmises` and `von...
vonmises_gen
python
doocs__leetcode
lcp/LCP 30. 魔塔游戏/Solution.py
{ "start": 0, "end": 392 }
class ____: def magicTower(self, nums: List[int]) -> int: q = [] blood = 1 ans = v = 0 for x in nums: if x < 0: heappush(q, x) blood += x if blood <= 0: ans += 1 v += q[0] blood -= hea...
Solution
python
scipy__scipy
scipy/linalg/tests/test_decomp_update.py
{ "start": 24959, "end": 25022 }
class ____(BaseQRdelete): dtype = np.dtype('F')
TestQRdelete_F
python
Netflix__metaflow
metaflow/plugins/argo/argo_events.py
{ "start": 384, "end": 6017 }
class ____(object): """ ArgoEvent is a small event, a message, that can be published to Argo Workflows. The event will eventually start all flows which have been previously deployed with `@trigger` to wait for this particular named event. Parameters ---------- name : str, Name of th...
ArgoEvent
python
Farama-Foundation__Gymnasium
gymnasium/envs/classic_control/continuous_mountain_car.py
{ "start": 609, "end": 11337 }
class ____(gym.Env): """ ## Description The Mountain Car MDP is a deterministic MDP that consists of a car placed stochastically at the bottom of a sinusoidal valley, with the only possible actions being the accelerations that can be applied to the car in either direction. The goal of the MDP is to...
Continuous_MountainCarEnv
python
altair-viz__altair
tools/generate_schema_wrapper.py
{ "start": 6995, "end": 7562 }
class ____: _encoding_name: str def to_dict( self, validate: bool = True, ignore: list[str] | None = None, context: dict[str, Any] | None = None, ) -> dict: context = context or {} ignore = ignore or [] datum = self._get("datum", Undefined) # type: ig...
DatumChannelMixin
python
getsentry__sentry
src/sentry/core/endpoints/scim/members.py
{ "start": 3529, "end": 3996 }
class ____(serializers.Serializer): op = serializers.CharField(required=True) value = OperationValue() path = serializers.CharField(required=False) def validate_op(self, value: str) -> str: value = value.lower() if value in [MemberPatchOps.REPLACE]: return value rais...
SCIMPatchOperationSerializer
python
scrapy__scrapy
scrapy/dupefilters.py
{ "start": 612, "end": 1318 }
class ____: """Dummy duplicate request filtering class (:setting:`DUPEFILTER_CLASS`) that does not filter out any request.""" @classmethod def from_crawler(cls, crawler: Crawler) -> Self: return cls() def request_seen(self, request: Request) -> bool: return False def open(self...
BaseDupeFilter
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_stackdriver.py
{ "start": 9882, "end": 10426 }
class ____: @mock.patch("airflow.providers.google.cloud.operators.stackdriver.StackdriverHook") def test_execute(self, mock_hook): operator = StackdriverDeleteNotificationChannelOperator( task_id=TEST_TASK_ID, name="test-channel", ) operator.execute(context=mock.M...
TestStackdriverDeleteNotificationChannelOperator
python
davidhalter__parso
parso/python/tree.py
{ "start": 32644, "end": 36241 }
class ____(PythonBaseNode): """ It's a helper class that makes business logic with params much easier. The Python grammar defines no ``param`` node. It defines it in a different way that is not really suited to working with parameters. """ type = 'param' def __init__(self, children, parent=...
Param
python
kamyu104__LeetCode-Solutions
Python/count-artifacts-that-can-be-extracted.py
{ "start": 611, "end": 1253 }
class ____(object): def digArtifacts(self, n, artifacts, dig): """ :type n: int :type artifacts: List[List[int]] :type dig: List[List[int]] :rtype: int """ lookup = {(i, j):idx for idx, (r1, c1, r2, c2) in enumerate(artifacts) for i in xrange(r1, r2+1) for j i...
Solution2
python
jmcnamara__XlsxWriter
xlsxwriter/test/comparison/test_image_anchor04.py
{ "start": 315, "end": 948 }
class ____(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.set_filename("image_anchor04.xlsx") def test_create_file(self): """Test the creation of a simple XlsxWriter file with image(s).""" workbook = Wo...
TestCompareXLSXFiles
python
huggingface__transformers
src/transformers/models/phi4_multimodal/modular_phi4_multimodal.py
{ "start": 69641, "end": 77168 }
class ____(Phi3ForCausalLM): _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"} def __init__(self, config): super().__init__(config) self.model = Phi4MultimodalModel(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config...
Phi4MultimodalForCausalLM
python
pydantic__pydantic
pydantic/v1/errors.py
{ "start": 15355, "end": 15466 }
class ____(PydanticValueError): msg_template = 'value is not a valid IPv4 or IPv6 network'
IPvAnyNetworkError
python
ray-project__ray
python/ray/data/_internal/datasource/webdataset_datasource.py
{ "start": 9204, "end": 12562 }
class ____(FileBasedDatasource): """A Datasource for WebDataset datasets (tar format with naming conventions).""" _FILE_EXTENSIONS = ["tar"] def __init__( self, paths: Union[str, List[str]], decoder: Optional[Union[bool, str, callable, list]] = True, fileselect: Optional[Un...
WebDatasetDatasource
python
apache__airflow
task-sdk/tests/conftest.py
{ "start": 8512, "end": 12362 }
class ____(Protocol): def __call__( self, dag_id: str = ..., run_id: str = ..., logical_date: str = ..., data_interval_start: str | datetime = ..., data_interval_end: str | datetime = ..., clear_number: int = ..., start_date: str | datetime = ..., ...
MakeTIContextDictCallable
python
gevent__gevent
src/gevent/_threading.py
{ "start": 4261, "end": 4374 }
class ____(Exception): """Raised from :meth:`Queue.get` if no item is available in the timeout."""
EmptyTimeout
python
graphql-python__graphene
graphene/types/base.py
{ "start": 766, "end": 1386 }
class ____(SubclassWithMeta): @classmethod def create_type(cls, class_name, **options): return type(class_name, (cls,), {"Meta": options}) @classmethod def __init_subclass_with_meta__( cls, name=None, description=None, _meta=None, **_kwargs ): assert "_meta" not in cls.__dic...
BaseType
python
getsentry__sentry
src/sentry/core/endpoints/scim/utils.py
{ "start": 4254, "end": 4598 }
class ____(OrganizationSCIMPermission): scope_map = { "GET": ["member:read", "member:write", "member:admin"], "POST": ["member:write", "member:admin"], "PATCH": ["member:write", "member:admin"], "PUT": ["member:write", "member:admin"], "DELETE": ["member:admin"], }
OrganizationSCIMMemberPermission
python
aio-libs__aiohttp
aiohttp/web_routedef.py
{ "start": 3973, "end": 6113 }
class ____(Sequence[AbstractRouteDef]): """Route definition table""" def __init__(self) -> None: self._items: list[AbstractRouteDef] = [] def __repr__(self) -> str: return f"<RouteTableDef count={len(self._items)}>" @overload def __getitem__(self, index: int) -> AbstractRouteDef: ...
RouteTableDef
python
getsentry__sentry
src/sentry/backup/services/import_export/impl.py
{ "start": 5431, "end": 31027 }
class ____(ImportExportService): """ This implementation is universal regardless of which mode (CONTROL, REGION, or MONOLITH) it is run in. All import/export codepaths must be executed in REGION or MONOLITH instances only, so the only case in which the caller should use the remote implementation are whe...
UniversalImportExportService
python
scipy__scipy
scipy/io/_harwell_boeing/hb.py
{ "start": 1177, "end": 12957 }
class ____: @classmethod def from_data(cls, m, title="Default title", key="0", mxtype=None, fmt=None): """Create a HBInfo instance from an existing sparse matrix. Parameters ---------- m : sparse array or matrix the HBInfo instance will derive its parameters from m ...
HBInfo
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/lambda5.py
{ "start": 319, "end": 473 }
class ____: ... def check(func: "Callable[[MsgT, int], object]") -> MsgT: ... notification: Msg[Request] = check(lambda msg, foo: (msg.body, foo))
Request
python
django__django
tests/admin_views/admin.py
{ "start": 16969, "end": 17277 }
class ____(admin.ModelAdmin): readonly_fields = ("name", "toppings") def has_add_permission(self, request): return False def has_change_permission(self, request, obj=None): return True def has_delete_permission(self, request, obj=None): return True
ReadOnlyPizzaAdmin
python
google__pytype
pytype/rewrite/abstract/functions.py
{ "start": 21403, "end": 21781 }
class ____(SimpleFunction[SimpleReturn]): def call_with_mapped_args( self, mapped_args: MappedArgs[FrameType]) -> SimpleReturn: log.info('Calling function %s:\n Sig: %s\n Args: %s', self.full_name, mapped_args.signature, mapped_args.argdict) ret = mapped_args.signature.annotations['retu...
PytdFunction
python
getsentry__sentry
src/sentry/plugins/migrator.py
{ "start": 675, "end": 2593 }
class ____: integration: RpcIntegration organization: RpcOrganization def run(self) -> None: for project in self.projects: for plugin in plugins.for_project(project): if plugin.slug != self.integration.provider: continue if self.all_r...
Migrator
python
doocs__leetcode
solution/2700-2799/2799.Count Complete Subarrays in an Array/Solution.py
{ "start": 0, "end": 324 }
class ____: def countCompleteSubarrays(self, nums: List[int]) -> int: cnt = len(set(nums)) ans, n = 0, len(nums) for i in range(n): s = set() for x in nums[i:]: s.add(x) if len(s) == cnt: ans += 1 return ans
Solution
python
getsentry__sentry
src/sentry/models/rollbackorganization.py
{ "start": 284, "end": 829 }
class ____(DefaultFieldsModel): """ Stores a summary of every organization's year-in-review information to power the 2024 Sentry Rollback. """ __relocation_scope__ = RelocationScope.Excluded organization = FlexibleForeignKey("sentry.Organization") data = models.JSONField(null=True, default=Non...
RollbackOrganization
python
pandas-dev__pandas
asv_bench/benchmarks/categoricals.py
{ "start": 2028, "end": 3264 }
class ____: def setup(self): N = 10**5 random_pick = np.random.default_rng().choice categories = { "str": list(string.ascii_letters), "int": np.random.randint(2**16, size=154), "float": sys.maxsize * np.random.random((38,)), "timestamp": [ ...
AsType
python
pennersr__django-allauth
allauth/socialaccount/providers/dingtalk/provider.py
{ "start": 486, "end": 941 }
class ____(OAuth2Provider): id = "dingtalk" name = "DingTalk" account_class = DingTalkAccount oauth2_adapter_class = DingTalkOAuth2Adapter def extract_uid(self, data): return data["openId"] def get_default_scope(self): return ["openid", "corpid"] def extract_common_fields(...
DingTalkProvider
python
apache__airflow
providers/celery/src/airflow/providers/celery/sensors/celery_queue.py
{ "start": 1348, "end": 3148 }
class ____(BaseSensorOperator): """ Waits for a Celery queue to be empty. By default, in order to be considered empty, the queue must not have any tasks in the ``reserved``, ``scheduled`` or ``active`` states. :param celery_queue: The name of the Celery queue to wait for. :param target_task_id...
CeleryQueueSensor
python
doocs__leetcode
solution/1700-1799/1784.Check if Binary String Has at Most One Segment of Ones/Solution.py
{ "start": 0, "end": 93 }
class ____: def checkOnesSegment(self, s: str) -> bool: return '01' not in s
Solution
python
apache__airflow
providers/google/tests/unit/google/cloud/operators/test_dataproc.py
{ "start": 46416, "end": 50451 }
class ____: @mock.patch(DATAPROC_PATH.format("DataprocHook")) def test_execute(self, mock_hook): op = DataprocDeleteClusterOperator( task_id=TASK_ID, region=GCP_REGION, project_id=GCP_PROJECT, cluster_name=CLUSTER_NAME, request_id=REQUEST_ID, ...
TestDataprocClusterDeleteOperator
python
run-llama__llama_index
llama-index-integrations/protocols/llama-index-protocols-ag-ui/llama_index/protocols/ag_ui/events.py
{ "start": 1689, "end": 1808 }
class ____(MessagesSnapshotEvent, Event): type: EventType = EventType.MESSAGES_SNAPSHOT
MessagesSnapshotWorkflowEvent
python
getsentry__sentry
tests/snuba/models/test_group.py
{ "start": 1179, "end": 6425 }
class ____(TestCase, SnubaTestCase, PerformanceIssueTestCase, OccurrenceTestMixin): def test_get_oldest_latest_for_environments(self) -> None: project = self.create_project() self.store_event( data={ "event_id": "a" * 32, "environment": "production", ...
GroupTestSnuba
python
sqlalchemy__sqlalchemy
test/orm/test_joins.py
{ "start": 8181, "end": 67103 }
class ____(QueryTest, AssertsCompiledSQL): __dialect__ = "default" @testing.combinations_list( set( itertools.product( [ "relationship", "relationship_only", "none", "explicit", ...
JoinTest
python
Farama-Foundation__Gymnasium
gymnasium/spaces/multi_discrete.py
{ "start": 389, "end": 11922 }
class ____(Space[NDArray[np.integer]]): """This represents the cartesian product of arbitrary :class:`Discrete` spaces. It is useful to represent game controllers or keyboards where each key can be represented as a discrete action space. Note: Some environment wrappers assume a value of 0 always r...
MultiDiscrete
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/descriptor1.py
{ "start": 1735, "end": 2041 }
class ____: @overload def __get__(self, instance: None, owner: Any) -> int: ... @overload def __get__(self, instance: Any, owner: Any) -> str: ... def __get__(self, instance: Any, owner: Any) -> int | str: ... def __set__(self, owner: Any, value: int | None) -> None: ...
Descriptor4
python
rushter__MLAlgorithms
mla/ensemble/random_forest.py
{ "start": 169, "end": 1687 }
class ____(BaseEstimator): def __init__( self, n_estimators=10, max_features=None, min_samples_split=10, max_depth=None, criterion=None, ): """Base class for RandomForest. Parameters ---------- n_estimators : int The nu...
RandomForest
python
chardet__chardet
chardet/resultdict.py
{ "start": 41, "end": 148 }
class ____(TypedDict): encoding: Optional[str] confidence: float language: Optional[str]
ResultDict
python
more-itertools__more-itertools
tests/test_more.py
{ "start": 25419, "end": 27563 }
class ____(TestCase): def test_basic(self): iterable = [1, 2, 3, 4, 5] for n, expected in ( (6, [(1, 2, 3, 4, 5, None)]), (5, [(1, 2, 3, 4, 5)]), (4, [(1, 2, 3, 4), (2, 3, 4, 5)]), (3, [(1, 2, 3), (2, 3, 4), (3, 4, 5)]), (2, [(1, 2), (2, 3...
WindowedTests
python
apache__airflow
shared/secrets_masker/tests/secrets_masker/test_secrets_masker.py
{ "start": 2943, "end": 15055 }
class ____: def test_message(self, logger, caplog): logger.info("XpasswordY") assert caplog.text == "INFO X***Y\n" def test_args(self, logger, caplog): logger.info("Cannot connect to %s", "user:password") assert caplog.text == "INFO Cannot connect to user:***\n" def test_e...
TestSecretsMasker
python
facebookresearch__faiss
tests/test_index_accuracy.py
{ "start": 21222, "end": 21974 }
class ____(unittest.TestCase): def test_roundoff(self): # params that force use of BLAS implementation nb = 100 nq = 25 d = 4 xb = np.zeros((nb, d), dtype="float32") xb[:, 0] = np.arange(nb) + 12345 xq = xb[:nq] + 0.3 index = faiss.IndexFlat(d) ...
TestRoundoff
python
pytorch__pytorch
test/quantization/core/test_workflow_module.py
{ "start": 21472, "end": 27066 }
class ____(HistogramObserver): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @torch.jit.ignore def _non_linear_param_search(self): r"""Non-linear parameter search. An approximation for L2 error minimization for selecting min/max. By selecting new mi...
_ReferenceHistogramObserver
python
pytorch__pytorch
test/distributed/_shard/sharded_tensor/test_sharded_tensor.py
{ "start": 14633, "end": 48410 }
class ____(ShardedTensorTestBase): @with_comms @skip_if_lt_x_gpu(4) @requires_nccl() def test_sharded_tensor_metadata(self): spec = ChunkShardingSpec( dim=0, placements=[ "rank:0/cuda:0", "rank:1/cuda:1", "rank:2/cuda:2", ...
TestShardedTensorChunked
python
pytorch__pytorch
test/distributed/fsdp/test_fsdp_state_dict.py
{ "start": 50917, "end": 53610 }
class ____(FSDPTest): @property def world_size(self): return torch.accelerator.device_count() @skip_if_lt_x_gpu(4) def test_local_state_dict_reshard(self): """ This test demonstrates the ability to do resharding when using local_state_dict. Although we do not recommend u...
TestFSDPStateDict4GPUs
python
facelessuser__pymdown-extensions
tests/test_extensions/test_blocks/test_general_blocks.py
{ "start": 12227, "end": 13531 }
class ____(util.MdCase): """Test blocks with `md_in_html`.""" extension = ['pymdownx.blocks.tab', 'pymdownx.blocks.html', 'markdown.extensions.md_in_html'] extension_configs = { 'pymdownx.blocks.tab': {'alternate_style': True} } def test_md_in_html_inserted_correctly(self): """Test...
TestBlocksMdInHTML
python
PyCQA__pylint
pylint/reporters/json_reporter.py
{ "start": 3269, "end": 6395 }
class ____(BaseReporter): name = "json2" extension = "json2" def display_reports(self, layout: Section) -> None: """Don't do anything in this reporter.""" def _display(self, layout: Section) -> None: """Do nothing.""" def display_messages(self, layout: Section | None) -> None: ...
JSON2Reporter
python
pytorch__pytorch
test/quantization/jit/test_quantize_jit.py
{ "start": 1864, "end": 59080 }
class ____(QuantizationTestCase): """Test graph mode quantization passes used by quantize_jit""" def test_skip_dequant_constant_prop(self): class M(torch.nn.Module): def __init__(self) -> None: super().__init__() self.conv = torch.nn.Conv2d(3, 5, 3).float() ...
TestQuantizeJitPasses
python
matplotlib__matplotlib
lib/mpl_toolkits/axisartist/grid_helper_curvelinear.py
{ "start": 10376, "end": 13506 }
class ____(GridHelperBase): def __init__(self, aux_trans, extreme_finder=None, grid_locator1=None, grid_locator2=None, tick_formatter1=None, tick_formatter2=None): """ Parameters ---------- aux_trans...
GridHelperCurveLinear
python
apache__airflow
providers/amazon/tests/unit/amazon/aws/triggers/test_emr.py
{ "start": 9525, "end": 10353 }
class ____: def test_serialization(self): application_id = "test_application_id" waiter_delay = 30 waiter_max_attempts = 60 aws_conn_id = "aws_default" trigger = EmrServerlessDeleteApplicationTrigger( application_id=application_id, waiter_delay=waiter...
TestEmrServerlessDeleteApplicationTrigger
python
tensorflow__tensorflow
tensorflow/python/distribute/collective_all_reduce_strategy_test.py
{ "start": 17316, "end": 18243 }
class ____( CollectiveAllReduceStrategyTestBase, parameterized.TestCase): @classmethod def setUpClass(cls): """Create a local cluster with 3 workers and 1 chief.""" cls._cluster_spec = multi_worker_test_base.create_in_process_cluster( num_workers=3, num_ps=0, has_chief=True) @combinations.ge...
DistributedCollectiveAllReduceStrategyTestWithChief
python
ray-project__ray
python/ray/data/stats.py
{ "start": 2314, "end": 4960 }
class ____: """Container for categorized columns and their aggregators.""" numerical_columns: List[str] str_columns: List[str] vector_columns: List[str] aggregators: List[AggregateFnV2] def feature_aggregators_for_dataset( dataset: "Dataset", columns: Optional[List[str]] = None ) -> FeatureAg...
FeatureAggregators
python
tensorflow__tensorflow
tensorflow/python/kernel_tests/distributions/bijector_test.py
{ "start": 1084, "end": 3057 }
class ____(test.TestCase): """Tests properties of the Bijector base-class.""" def testIsAbstract(self): # In Python 3.9, "abstract methods" become "abstract method" with self.assertRaisesRegex(TypeError, r"Can't instantiate abstract class Bijector " ...
BaseBijectorTest
python
google__pytype
pytype/rewrite/load_abstract_test.py
{ "start": 1851, "end": 2478 }
class ____(test_utils.ContextfulTestBase): def test_builtin_type(self): t = self.ctx.abstract_loader.load_raw_type(int) self.assertIsInstance(t, abstract.SimpleClass) self.assertEqual(t.name, 'int') self.assertEqual(t.module, 'builtins') def test_stdlib_type(self): t = self.ctx.abstract_loader...
LoadRawTypeTest
python
nedbat__coveragepy
tests/test_api.py
{ "start": 40067, "end": 41557 }
class ____(CoverageTest): """Test the numerical analysis of results.""" def test_many_missing_branches(self) -> None: cov = coverage.Coverage(branch=True) self.make_file( "missing.py", """\ def fun1(x): if x == 1: print("o...
AnalysisTest
python
altair-viz__altair
altair/vegalite/v6/schema/channels.py
{ "start": 856496, "end": 877885 }
class ____(FieldChannelMixin, core.TimeDef): r""" Time schema wrapper. Parameters ---------- shorthand : str, dict, Sequence[str], :class:`RepeatRef` shorthand for field, aggregate, and type aggregate : dict, :class:`Aggregate`, :class:`ArgmaxDef`, :class:`ArgminDef`, :class:`NonArgAggr...
Time