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
tensorflow__tensorflow
tensorflow/python/data/kernel_tests/interleave_test.py
{ "start": 17134, "end": 25288 }
class ____( checkpoint_test_base.CheckpointTestBase, parameterized.TestCase ): @combinations.generate( combinations.times( test_base.default_test_combinations(), checkpoint_test_base.default_test_combinations(), combinations.combine( symbolic_checkpoint=[False, T...
InterleaveCheckpointTest
python
pypa__setuptools
setuptools/_distutils/command/clean.py
{ "start": 285, "end": 2644 }
class ____(Command): description = "clean up temporary files from 'build' command" user_options = [ ('build-base=', 'b', "base build directory [default: 'build.build-base']"), ( 'build-lib=', None, "build directory for all modules [default: 'build.build-lib']"...
clean
python
huggingface__transformers
src/transformers/models/deepseek_v2/modeling_deepseek_v2.py
{ "start": 2111, "end": 4020 }
class ____(nn.Module): """Collection of expert weights stored as 3D tensors.""" def __init__(self, config): super().__init__() self.num_experts = config.n_routed_experts self.hidden_dim = config.hidden_size self.intermediate_dim = config.moe_intermediate_size self.gate_u...
DeepseekV2Experts
python
ray-project__ray
python/ray/serve/tests/unit/test_application_state.py
{ "start": 49760, "end": 58087 }
class ____: @pytest.fixture def info(self): return DeploymentInfo( route_prefix="/", version="123", deployment_config=DeploymentConfig(num_replicas=1), replica_config=ReplicaConfig.create(lambda x: x), start_time_ms=0, deployer_job_...
TestOverrideDeploymentInfo
python
pytorch__pytorch
torch/_dynamo/variables/misc.py
{ "start": 65990, "end": 66710 }
class ____(VariableTracker): def __init__(self, **kwargs) -> None: super().__init__(**kwargs) def __repr__(self) -> str: return "NullVariable" def reconstruct(self, codegen: "PyCodegen"): if sys.version_info < (3, 11): unimplemented( gb_type="cannot reco...
NullVariable
python
RaRe-Technologies__gensim
gensim/similarities/docsim.py
{ "start": 40411, "end": 43854 }
class ____(interfaces.SimilarityABC): """Compute negative WMD similarity against a corpus of documents. Check out `the Gallery <https://radimrehurek.com/gensim/auto_examples/tutorials/run_wmd.html>`__ for more examples. When using this code, please consider citing the following papers: * `Rémi Fl...
WmdSimilarity
python
Lightning-AI__lightning
tests/tests_pytorch/overrides/test_distributed.py
{ "start": 988, "end": 3650 }
class ____(LightningModule): def setup(self, stage: str) -> None: self.layer = torch.nn.Linear(1, 1) weights = self.layer.weight.item(), self.layer.bias.item() self.rank_0_weights = self.trainer.strategy.broadcast(weights) def test_step(self, batch, batch_idx): current = self.la...
MyModel
python
pyqtgraph__pyqtgraph
pyqtgraph/graphicsItems/ROI.py
{ "start": 1196, "end": 58617 }
class ____(GraphicsObject): """ Generic region-of-interest widget. Can be used for implementing many types of selection box with rotate/translate/scale handles. ROIs can be customized to have a variety of shapes (by subclassing or using any of the built-in subclasses) and any combination o...
ROI
python
tensorflow__tensorflow
tensorflow/core/function/polymorphism/function_type_test.py
{ "start": 29611, "end": 31994 }
class ____(test.TestCase, parameterized.TestCase): @parameterized.parameters( { "signature": ((1, 2, 3), {}), "expected_types": ( trace_type.from_value(1), trace_type.from_value(2), trace_type.from_value(3), ), }, { "...
FromStructuredSignatureTest
python
django__django
tests/cache/liberal_backend.py
{ "start": 60, "end": 141 }
class ____: def validate_key(self, key): pass
LiberalKeyValidationMixin
python
pytorch__pytorch
test/distributed/test_c10d_nccl.py
{ "start": 246753, "end": 249140 }
class ____(NCCLTraceTestBase): def _wait_process(self, rank, timeout): try: self.processes[rank].join(timeout) return self.processes[rank].exitcode except TimeoutError: return None @check_if_test_is_skipped def _check_return_codes(self, elapsed_time): ...
NcclErrorDumpTest
python
numba__llvmlite
llvmlite/binding/typeref.py
{ "start": 997, "end": 5272 }
class ____(ffi.ObjectRef): """A weak reference to a LLVM type """ @property def name(self): """ Get type name """ return ffi.ret_string(ffi.lib.LLVMPY_GetTypeName(self)) @property def is_struct(self): """ Returns true if the type is a struct type....
TypeRef
python
google__pytype
pytype/imports/typeshed.py
{ "start": 1719, "end": 2923 }
class ____(TypeshedStore): """Filesystem-based typeshed store.""" def __init__(self, *, missing_file=None, open_function=open): self._root = self.get_root() self._open_function = open_function self._missing_file = missing_file @abc.abstractmethod def get_root(self): raise NotImplementedError ...
TypeshedFs
python
qdrant__qdrant-client
qdrant_client/local/sparse_distances.py
{ "start": 1864, "end": 2449 }
class ____: def __init__(self, target: SparseVector, context: list[SparseContextPair]): validate_sparse_vector(target) self.target: SparseVector = sort_sparse_vector(target) self.context = context def transform_sparse( self, foo: Callable[["SparseVector"], "SparseVector"] ) ...
SparseDiscoveryQuery
python
apache__airflow
airflow-core/src/airflow/api_fastapi/execution_api/datamodels/taskinstance.py
{ "start": 11802, "end": 11938 }
class ____(BaseModel): """Response for task states with run_id, task and state.""" task_states: dict[str, Any]
TaskStatesResponse
python
sqlalchemy__sqlalchemy
test/base/test_utils.py
{ "start": 42851, "end": 43547 }
class ____(fixtures.TestBase): @testing.combinations( (["one", "two", "three"], True), (("one", "two", "three"), True), ((), True), ("four", False), (252, False), (Decimal("252"), False), (b"four", False), (iter("four"), True), (b"", False), ...
MiscTest
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/sql/elements.py
{ "start": 99184, "end": 101728 }
class ____(ColumnElement[_T]): """base for expressions that contain an operator and operands .. versionadded:: 2.0 """ operator: OperatorType type: TypeEngine[_T] group: bool = True @property def is_comparison(self): return operators.is_comparison(self.operator) def sel...
OperatorExpression
python
sympy__sympy
sympy/simplify/cse_main.py
{ "start": 11143, "end": 31310 }
class ____: def __init__(self, func, args): self.func = func self.args = args def __str__(self): return "Uneval<{}>({})".format( self.func, ", ".join(str(a) for a in self.args)) def as_unevaluated_basic(self): return self.func(*self.args, evaluate=False) ...
Unevaluated
python
django__django
tests/queries/models.py
{ "start": 13168, "end": 13374 }
class ____(models.Model): a = models.ForeignKey(FK1, models.SET_NULL, null=True) b = models.ForeignKey(FK2, models.SET_NULL, null=True) c = models.ForeignKey(FK3, models.SET_NULL, null=True)
BaseA
python
sphinx-doc__sphinx
sphinx/transforms/post_transforms/__init__.py
{ "start": 11256, "end": 11743 }
class ____(SphinxPostTransform): default_priority = 50 def run(self, **kwargs: Any) -> None: # A comment on the comment() nodes being inserted: replacing by [] would # result in a "Losing ids" exception if there is a target node before # the only node, so we make sure docutils can trans...
OnlyNodeTransform
python
kamyu104__LeetCode-Solutions
Python/count-anagrams.py
{ "start": 66, "end": 1316 }
class ____(object): def countAnagrams(self, s): """ :type s: str :rtype: int """ MOD = 10**9+7 fact, inv, inv_fact = [[1]*2 for _ in xrange(3)] def lazy_init(n): while len(inv) <= n: # lazy initialization fact.append(fact[-1]*len(i...
Solution
python
airbytehq__airbyte
airbyte-integrations/connectors/source-instagram/components.py
{ "start": 14251, "end": 15264 }
class ____(TypeTransformer): """ The Instagram API returns dates in the format 2025-01-01T07:00:00+0000, but the existing implementation normalized dates to the RFC 3339 format 2025-01-01T07:00:00+00:00. """ def __init__(self, *args, **kwargs): config = TransformConfig.CustomSchemaNormaliza...
RFC3339DatetimeSchemaNormalization
python
huggingface__transformers
src/transformers/models/esm/modeling_esmfold.py
{ "start": 10665, "end": 15822 }
class ____(nn.Module): """ Standard multi-head attention using AlphaFold's default layer initialization. Allows multiple bias vectors. """ def __init__( self, c_q: int, c_k: int, c_v: int, c_hidden: int, no_heads: int, gating: bool = True, ): ...
EsmFoldAttention
python
sqlalchemy__sqlalchemy
lib/sqlalchemy/testing/fixtures/sql.py
{ "start": 14148, "end": 16171 }
class ____(CacheKeyFixture): @classmethod def run_suite_tests(cls, fn): def decorate(self): self._run_cache_key_fixture(fn(self), compare_values=False) self._run_compare_fixture(fn(self), compare_values=False) decorate.__name__ = fn.__name__ return decorate def...
CacheKeySuite
python
getsentry__sentry
tests/sentry/notifications/platform/slack/test_provider.py
{ "start": 2167, "end": 3181 }
class ____(TestCase): def setUp(self) -> None: super().setUp() self.integration, self.org_integration = self.create_provider_integration_for( provider=IntegrationProviderSlug.SLACK, organization=self.organization, user=self.user, name="test-slack", ...
SlackNotificationProviderTest
python
huggingface__transformers
src/transformers/models/sew_d/modeling_sew_d.py
{ "start": 38995, "end": 43871 }
class ____(nn.Module): """Modified BertEncoder with relative position bias support""" def __init__(self, config): super().__init__() self.layer = nn.ModuleList([SEWDLayer(config) for _ in range(config.num_hidden_layers)]) self.relative_attention = getattr(config, "relative_attention", ...
SEWDTransformerEncoder
python
getsentry__sentry
src/sentry/auth/providers/saml2/provider.py
{ "start": 12425, "end": 12781 }
class ____(TypedDict): authnRequestsSigned: bool logoutRequestSigned: bool logoutResponseSigned: bool signMetadata: bool wantMessagesSigned: bool wantAssertionsSigned: bool wantAssertionsEncrypted: bool signatureAlgorithm: bool digestAlgorithm: bool wantNameId: bool requested...
_SamlConfigSecurity
python
sphinx-doc__sphinx
sphinx/domains/c/_ast.py
{ "start": 47478, "end": 48597 }
class ____(ASTBaseParenExprList): def __init__(self, exprs: list[ASTExpression]) -> None: self.exprs = exprs def __eq__(self, other: object) -> bool: if not isinstance(other, ASTParenExprList): return NotImplemented return self.exprs == other.exprs def __hash__(self) ->...
ASTParenExprList
python
dagster-io__dagster
python_modules/dagster/dagster/components/lib/shim_components/asset_check.py
{ "start": 458, "end": 1427 }
class ____(ShimScaffolder[AssetCheckScaffoldParams]): @classmethod def get_scaffold_params(cls) -> type[AssetCheckScaffoldParams]: return AssetCheckScaffoldParams def get_text(self, request: ScaffoldRequest[AssetCheckScaffoldParams]) -> str: """Get the text for an asset check. Args...
AssetCheckScaffolder
python
neetcode-gh__leetcode
python/0006-zigzag-conversion.py
{ "start": 0, "end": 420 }
class ____: def convert(self, s: str, numRows: int) -> str: if numRows == 1 or numRows >= len(s): return s res = [""] * numRows index = 0 step = 1 for c in s: res[index] += c if index == 0: step = 1 elif index ...
Solution
python
run-llama__llama_index
llama-index-integrations/tools/llama-index-tools-google/llama_index/tools/google/calendar/base.py
{ "start": 847, "end": 7604 }
class ____(BaseToolSpec): """ Google Calendar tool spec. Currently a simple wrapper around the data loader. TODO: add more methods to the Google Calendar spec. """ spec_functions = ["load_data", "create_event", "get_date"] def __init__(self, creds: Optional[Any] = None): """ ...
GoogleCalendarToolSpec
python
ray-project__ray
python/ray/_private/thirdparty/pynvml/pynvml.py
{ "start": 243807, "end": 243930 }
class ____(Structure): pass # opaque handle c_nvmlGpmSample_t = POINTER(struct_c_nvmlGpmSample_t)
struct_c_nvmlGpmSample_t
python
django__django
tests/invalid_models_tests/test_models.py
{ "start": 23777, "end": 32183 }
class ____(TestCase): databases = {"default", "other"} def test_ending_with_underscore(self): class Model(models.Model): field_ = models.CharField(max_length=10) m2m_ = models.ManyToManyField("self") self.assertEqual( Model.check(), [ ...
FieldNamesTests
python
keras-team__keras
keras/src/layers/preprocessing/text_vectorization.py
{ "start": 561, "end": 28161 }
class ____(Layer): """A preprocessing layer which maps text features to integer sequences. This layer has basic options for managing text in a Keras model. It transforms a batch of strings (one example = one string) into either a list of token indices (one example = 1D tensor of integer token indices) ...
TextVectorization
python
huggingface__transformers
src/transformers/models/mistral3/modeling_mistral3.py
{ "start": 2508, "end": 4063 }
class ____(nn.Module): """ Learned merging of spatial_merge_size ** 2 patches """ def __init__(self, config: Mistral3Config): super().__init__() self.config = config hidden_size = config.vision_config.hidden_size self.spatial_merge_size = config.spatial_merge_size ...
Mistral3PatchMerger
python
bottlepy__bottle
bottle.py
{ "start": 98171, "end": 98749 }
class ____(list): """ A stack-like list. Calling it returns the head of the stack. """ def __call__(self): """ Return the current default application. """ return self.default def push(self, value=None): """ Add a new :class:`Bottle` instance to the stack """ if not isinstan...
AppStack
python
getsentry__sentry
src/sentry/hybridcloud/rpc/service.py
{ "start": 4636, "end": 7130 }
class ____(DelegatedBySiloMode["RpcService"]): def __init__( self, base_service_cls: type[RpcService], constructors: Mapping[SiloMode, Callable[[], RpcService]], signatures: Mapping[str, RpcMethodSignature], ) -> None: super().__init__(constructors) self._base_ser...
DelegatingRpcService
python
pola-rs__polars
py-polars/src/polars/lazyframe/in_process.py
{ "start": 208, "end": 1133 }
class ____: """ A placeholder for an in process query. This can be used to do something else while a query is running. The queries can be cancelled. You can peek if the query is finished, or you can await the result. """ def __init__(self, ipq: PyInProcessQuery) -> None: self._inne...
InProcessQuery
python
pytorch__pytorch
torch/export/unflatten.py
{ "start": 4102, "end": 4474 }
class ____: _ty: Optional[str] def type_name(self) -> Optional[str]: """ Subclass of this class - InterpreterModule, InterpreterModuleDispatcher, represents corresponding model in eager model. To get this type information for those modules in eager model we need to use this meth...
_SubmoduleBase
python
pypa__warehouse
warehouse/accounts/models.py
{ "start": 1405, "end": 1695 }
class ____: def __init__(self, request): self.request = request def __getitem__(self, username): try: return self.request.db.query(User).filter(User.username == username).one() except NoResultFound: raise KeyError from None
UserFactory
python
mlflow__mlflow
mlflow/bedrock/stream.py
{ "start": 2583, "end": 4434 }
class ____(BaseEventStreamWrapper): """A wrapper class for a event stream returned by the InvokeModelWithResponseStream API. This wrapper intercepts streaming events from Bedrock's invoke_model_with_response_stream API and accumulates token usage information across multiple chunks. It buffers partial t...
InvokeModelStreamWrapper
python
run-llama__llama_index
llama-index-core/llama_index/core/extractors/interface.py
{ "start": 517, "end": 5578 }
class ____(TransformComponent): """Metadata extractor.""" is_text_node_only: bool = True show_progress: bool = Field(default=True, description="Whether to show progress.") metadata_mode: MetadataMode = Field( default=MetadataMode.ALL, description="Metadata mode to use when reading nodes." ...
BaseExtractor
python
kamyu104__LeetCode-Solutions
Python/find-the-highest-altitude.py
{ "start": 29, "end": 296 }
class ____(object): def largestAltitude(self, gain): """ :type gain: List[int] :rtype: int """ result = curr = 0 for g in gain: curr += g result = max(result, curr) return result
Solution
python
getsentry__sentry
tests/sentry/api/endpoints/test_project_proguard_artifact_releases.py
{ "start": 202, "end": 8087 }
class ____(APITestCase): def test_create_proguard_artifact_release_successfully(self) -> None: project = self.create_project(name="foo") proguard_uuid = "660f839b-8bfd-580d-9a7c-ea339a6c9867" url = reverse( "sentry-api-0-proguard-artifact-releases", kwargs={ ...
ProguardArtifactReleasesEndpointTest
python
scipy__scipy
scipy/datasets/tests/test_data.py
{ "start": 817, "end": 4213 }
class ____: @pytest.fixture(scope='module', autouse=True) def test_download_all(self): # This fixture requires INTERNET CONNECTION # test_setup phase download_all() yield @pytest.mark.fail_slow(10) def test_existence_all(self): assert len(os.listdir(data_dir))...
TestDatasets
python
microsoft__pyright
packages/pyright-internal/src/tests/samples/coroutines1.py
{ "start": 733, "end": 1332 }
class ____: def __aenter__(self): return self @coroutine def __await__(self) -> Generator[Any, None, int]: yield 3 return 3 async def __aexit__( self, t: Optional[type] = None, exc: Optional[BaseException] = None, tb: Optional[Any] = None, ) ...
ScopedClass1
python
huggingface__transformers
src/transformers/models/granitemoehybrid/modular_granitemoehybrid.py
{ "start": 7599, "end": 10933 }
class ____(GraniteMoeSharedModel): def __init__(self, config: GraniteMoeHybridConfig): super().__init__(config) self.layers = nn.ModuleList( [GraniteMoeHybridDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.embedding_multiplier = co...
GraniteMoeHybridModel
python
ansible__ansible
lib/ansible/module_utils/_internal/_datatag/__init__.py
{ "start": 32600, "end": 33737 }
class ____(datetime.time, AnsibleTaggedObject): __slots__ = _ANSIBLE_TAGGED_OBJECT_SLOTS @classmethod def _instance_factory(cls, value: datetime.time, tags_mapping: _AnsibleTagsMapping) -> _AnsibleTaggedTime: instance = cls( hour=value.hour, minute=value.minute, ...
_AnsibleTaggedTime
python
facelessuser__pymdown-extensions
pymdownx/superfences.py
{ "start": 6057, "end": 10241 }
class ____(Extension): """SuperFences code block extension.""" def __init__(self, *args, **kwargs): """Initialize.""" self.superfences = [] self.config = { 'disable_indented_code_blocks': [False, "Disable indented code blocks - Default: False"], 'custom_fences':...
SuperFencesCodeExtension
python
walkccc__LeetCode
solutions/385. Mini Parser/385.py
{ "start": 0, "end": 643 }
class ____: def deserialize(self, s: str) -> NestedInteger: if s[0] != '[': return NestedInteger(int(s)) stack = [] for i, c in enumerate(s): if c == '[': stack.append(NestedInteger()) start = i + 1 elif c == ',': if i > start: num = int(s[start:i]) ...
Solution
python
readthedocs__readthedocs.org
readthedocs/embed/views.py
{ "start": 358, "end": 900 }
class ____(EmbedAPIMixin, APIView): permission_classes = [AllowAny] renderer_classes = [JSONRenderer] def get(self, request): return Response( { "error": ( "Embed API v2 has been deprecated and is no longer available, please use embed API v3 instead. ...
EmbedAPI
python
great-expectations__great_expectations
great_expectations/core/serializer.py
{ "start": 2189, "end": 2699 }
class ____(AbstractConfigSerializer): @override def serialize(self, obj: AbstractConfig) -> dict: """Serialize config to json dict. Args: obj: AbstractConfig object to serialize. Returns: Representation of object as a dict suitable for serializing to json. ...
JsonConfigSerializer
python
redis__redis-py
redis/commands/search/field.py
{ "start": 3593, "end": 3818 }
class ____(Field): """ GeoField is used to define a geo-indexing field in a schema definition """ def __init__(self, name: str, **kwargs): Field.__init__(self, name, args=[Field.GEO], **kwargs)
GeoField
python
jina-ai__jina
jina/orchestrate/flow/asyncio.py
{ "start": 134, "end": 2175 }
class ____(AsyncPostMixin, AsyncProfileMixin, AsyncHealthCheckMixin, Flow): """ Asynchronous version of :class:`jina.Flow`. They share the same interface, except in :class:`AsyncFlow` :meth:`train`, :meth:`index`, :meth:`search` methods are coroutines (i.e. declared with the async/await syntax), simply ...
AsyncFlow
python
tiangolo__fastapi
docs_src/body_nested_models/tutorial007_py310.py
{ "start": 144, "end": 329 }
class ____(BaseModel): name: str description: str | None = None price: float tax: float | None = None tags: set[str] = set() images: list[Image] | None = None
Item
python
pytorch__pytorch
test/test_serialization.py
{ "start": 40407, "end": 40526 }
class ____(ClassThatUsesBuildInstructionAllSlots): x: int y: int c: str
ClassThatUsesBuildInstructionSomeSlots
python
huggingface__transformers
src/transformers/models/luke/modeling_luke.py
{ "start": 32747, "end": 33309 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.config = config self.transform = EntityPredictionHeadTransform(config) self.decoder = nn.Linear(config.entity_emb_size, config.entity_vocab_size, bias=False) self.bias = nn.Parameter(torch.zeros(config...
EntityPredictionHead
python
encode__django-rest-framework
rest_framework/permissions.py
{ "start": 4298, "end": 4630 }
class ____(BasePermission): """ The request is authenticated as a user, or is a read-only request. """ def has_permission(self, request, view): return bool( request.method in SAFE_METHODS or request.user and request.user.is_authenticated )
IsAuthenticatedOrReadOnly
python
apache__airflow
providers/amazon/src/airflow/providers/amazon/aws/operators/bedrock.py
{ "start": 12398, "end": 17116 }
class ____(AwsBaseOperator[BedrockHook]): """ Create a fine-tuning job to customize a base model. .. seealso:: For more information on how to use this operator, take a look at the guide: :ref:`howto/operator:BedrockCreateProvisionedModelThroughputOperator` :param model_units: Number of...
BedrockCreateProvisionedModelThroughputOperator
python
django__django
tests/gis_tests/utils.py
{ "start": 954, "end": 2398 }
class ____: """Assert that Func expressions aren't mutated during their as_sql().""" def setUp(self): def as_sql_wrapper(original_as_sql): def inner(*args, **kwargs): func = original_as_sql.__self__ # Resolve output_field before as_sql() so touching it in ...
FuncTestMixin
python
kamyu104__LeetCode-Solutions
Python/find-the-most-common-response.py
{ "start": 83, "end": 424 }
class ____(object): def findCommonResponse(self, responses): """ :type responses: List[List[str]] :rtype: str """ cnt = collections.defaultdict(int) for r in responses: for x in set(r): cnt[x] += 1 return min((-c, x) for x, c in cnt...
Solution
python
conda__conda
conda/models/enums.py
{ "start": 1684, "end": 2559 }
class ____(Enum): """ Refers to if the file in question is hard linked or soft linked. Originally designed to be used in paths.json """ hardlink = "hardlink" softlink = "softlink" directory = "directory" # these additional types should not be included by conda-build in packages lin...
PathType
python
jazzband__django-redis
tests/test_client.py
{ "start": 582, "end": 2162 }
class ____: def test_close_client_disconnect_default( self, cache_client: DefaultClient, mocker: MockerFixture, ): cache_client._options.clear() mock = mocker.patch.object(cache_client.connection_factory, "disconnect") cache_client.close() assert not mock....
TestClientClose
python
sphinx-doc__sphinx
tests/roots/test-ext-autodoc/target/__init__.py
{ "start": 2382, "end": 2553 }
class ____: """Foo""" class Inner: """Foo""" def meth(self): """Foo""" # should be documented as an alias factory = dict
Outer
python
cython__cython
Cython/Shadow.py
{ "start": 12728, "end": 16473 }
class ____(CythonType): __getitem__ = index_type def fused_type(*args): if not args: raise TypeError("Expected at least one type as argument") # Find the numeric type with biggest rank if all types are numeric rank = -1 for type in args: if type not in (py_int, py_long, py_float, ...
_FusedType
python
walkccc__LeetCode
solutions/412. Fizz Buzz/412.py
{ "start": 0, "end": 179 }
class ____: def fizzBuzz(self, n: int) -> list[str]: d = {3: 'Fizz', 5: 'Buzz'} return [''.join([d[k] for k in d if i % k == 0]) or str(i) for i in range(1, n + 1)]
Solution
python
huggingface__transformers
tests/models/owlvit/test_modeling_owlvit.py
{ "start": 7268, "end": 10591 }
class ____: def __init__( self, parent, batch_size=12, num_queries=4, seq_length=16, is_training=True, use_input_mask=True, use_labels=True, vocab_size=99, hidden_size=64, num_hidden_layers=12, num_attention_heads=4, ...
OwlViTTextModelTester
python
scipy__scipy
scipy/signal/tests/test_ltisys.py
{ "start": 26184, "end": 26980 }
class ____: def test_lti_instantiation(self): # Test that lti can be instantiated with sequences, scalars. # See PR-225. # TransferFunction s = lti([1], [-1]) assert isinstance(s, TransferFunction) assert isinstance(s, lti) assert not isinstance(s, dlti) ...
TestLti
python
langchain-ai__langchain
libs/cli/langchain_cli/integration_template/integration_template/document_loaders.py
{ "start": 176, "end": 2112 }
class ____(BaseLoader): # TODO: Replace all TODOs in docstring. See example docstring: # https://github.com/langchain-ai/langchain/blob/869523ad728e6b76d77f170cce13925b4ebc3c1e/libs/community/langchain_community/document_loaders/recursive_url_loader.py#L54 """ __ModuleName__ document loader integration ...
__ModuleName__Loader
python
numpy__numpy
numpy/f2py/tests/test_return_character.py
{ "start": 138, "end": 817 }
class ____(util.F2PyTest): def check_function(self, t, tname): if tname in ["t0", "t1", "s0", "s1"]: assert t("23") == b"2" r = t("ab") assert r == b"a" r = t(array("ab")) assert r == b"a" r = t(array(77, "u1")) assert r == ...
TestReturnCharacter
python
milvus-io__pymilvus
pymilvus/orm/schema.py
{ "start": 24620, "end": 30420 }
class ____: def __init__(self): self.name = "" self._kwargs = {} self._fields = [] self._description = "" self._type_params = {} # max_capacity will be set when added to CollectionSchema self.max_capacity = None def _check_kwargs(self): """Check s...
StructFieldSchema
python
PyCQA__pylint
tests/functional/u/unbalanced/unbalanced_tuple_unpacking.py
{ "start": 1698, "end": 2944 }
class ____: """Test unbalanced tuple unpacking in instance attributes.""" # pylint: disable=attribute-defined-outside-init, invalid-name, too-few-public-methods def test(self): """unpacking in instance attributes""" # we're not sure if temp() returns two or three values # so we shou...
UnbalancedUnpacking
python
pyqtgraph__pyqtgraph
benchmarks/renderImageItem.py
{ "start": 923, "end": 8085 }
class ____: unit = "seconds" param_names = ["size", "acceleration", "use_levels", "dtype", "channels", "lut_length"] params = Parameters( [ # (256, 256), # other sizes useful to test for # (512, 512), # seeing performance scale # (1024,...
TimeSuite
python
dask__distributed
distributed/utils_test.py
{ "start": 72547, "end": 78528 }
class ____(Nanny): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.in_kill = asyncio.Event() self.wait_kill = asyncio.Event() async def kill(self, **kwargs): self.in_kill.set() await self.wait_kill.wait() return await super().kill(**kw...
BlockedKillNanny
python
pypa__pip
tests/unit/test_resolution_legacy_resolver.py
{ "start": 845, "end": 2441 }
class ____(BaseDistribution): def __init__(self, metadata: email.message.Message) -> None: self._canonical_name = cast(NormalizedName, "my-project") self._metadata = metadata def __str__(self) -> str: return f"<distribution {self.canonical_name!r}>" @property def canonical_name...
FakeDist
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/qgroupnorm_test.py
{ "start": 306, "end": 1504 }
class ____(op_bench.TorchBenchmarkBase): def init(self, dims, num_groups, dtype): X = (torch.rand(*dims) - 0.5) * 256 num_channels = dims[1] scale = 1.0 zero_point = 0 self.inputs = { "qX": torch.quantize_per_tensor( X, scale=scale, zero_point=zer...
QGroupNormBenchmark
python
PrefectHQ__prefect
src/prefect/settings/models/server/services.py
{ "start": 8921, "end": 13936 }
class ____(ServicesBaseSetting): """ Settings for controlling the scheduler service """ model_config: ClassVar[SettingsConfigDict] = build_settings_config( ("server", "services", "scheduler") ) enabled: bool = Field( default=True, description="Whether or not to start th...
ServerServicesSchedulerSettings
python
pydantic__pydantic
pydantic/types.py
{ "start": 9569, "end": 13239 }
class ____(_fields.PydanticMetadata): """A field metadata class to indicate that a field should allow `-inf`, `inf`, and `nan`. Use this class as an annotation via [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated), as seen below. Attributes: allow_inf_nan: Whether to al...
AllowInfNan
python
keras-team__keras
keras/src/losses/losses.py
{ "start": 1673, "end": 3245 }
class ____(LossFunctionWrapper): """Computes the mean of squares of errors between labels and predictions. Formula: ```python loss = mean(square(y_true - y_pred)) ``` Args: reduction: Type of reduction to apply to the loss. In almost all cases this should be `"sum_over_bat...
MeanSquaredError
python
great-expectations__great_expectations
great_expectations/data_context/types/resource_identifiers.py
{ "start": 17673, "end": 18210 }
class ____(Schema): configuration_key = fields.Str() # noinspection PyUnusedLocal @post_load def make_configuration_identifier(self, data, **kwargs): return ConfigurationIdentifier(**data) expectationSuiteIdentifierSchema = ExpectationSuiteIdentifierSchema() validationResultIdentifierSchema =...
ConfigurationIdentifierSchema
python
optuna__optuna
optuna/terminator/terminator.py
{ "start": 669, "end": 875 }
class ____(metaclass=abc.ABCMeta): """Base class for terminators.""" @abc.abstractmethod def should_terminate(self, study: Study) -> bool: pass @experimental_class("3.2.0")
BaseTerminator
python
dagster-io__dagster
python_modules/libraries/dagster-airlift/dagster_airlift/core/serialization/serialized_data.py
{ "start": 4239, "end": 4365 }
class ____: asset_key: AssetKey mapped_tasks: AbstractSet[TaskHandle] @whitelist_for_serdes @record
KeyScopedTaskHandles
python
TheAlgorithms__Python
data_structures/linked_list/doubly_linked_list_two.py
{ "start": 649, "end": 815 }
class ____[DataType]: data: DataType previous: Self | None = None next: Self | None = None def __str__(self) -> str: return f"{self.data}"
Node
python
graphql-python__graphene
graphene/relay/connection.py
{ "start": 4191, "end": 6539 }
class ____(Field): def __init__(self, type_, *args, **kwargs): kwargs.setdefault("before", String()) kwargs.setdefault("after", String()) kwargs.setdefault("first", Int()) kwargs.setdefault("last", Int()) super(IterableConnectionField, self).__init__(type_, *args, **kwargs) ...
IterableConnectionField
python
Textualize__textual
src/textual/markup.py
{ "start": 674, "end": 1682 }
class ____(Exception): """An error occurred parsing content markup.""" expect_markup_tag = ( Expect( "markup style value", end_tag=r"(?<!\\)\]", key=r"[@a-zA-Z_-][a-zA-Z0-9_-]*=", percent=PERCENT, color=COLOR, token=TOKEN, variable_ref=VARIABLE_REF, ...
MarkupError
python
django__django
tests/signing/tests.py
{ "start": 200, "end": 7892 }
class ____(SimpleTestCase): def test_signature(self): "signature() method should generate a signature" signer = signing.Signer(key="predictable-secret") signer2 = signing.Signer(key="predictable-secret2") for s in ( b"hello", b"3098247:529:087:", "...
TestSigner
python
kamyu104__LeetCode-Solutions
Python/convert-integer-to-the-sum-of-two-no-zero-integers.py
{ "start": 473, "end": 693 }
class ____(object): def getNoZeroIntegers(self, n): """ :type n: int :rtype: List[int] """ return next([a, n-a] for a in xrange(1, n) if '0' not in '{}{}'.format(a, n-a))
Solution2
python
django-debug-toolbar__django-debug-toolbar
debug_toolbar/panels/templates/panel.py
{ "start": 2271, "end": 9475 }
class ____(Panel): """ A panel that lists all templates used during processing of a response. """ is_async = True def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.templates = [] # An associated list of dictionaries and their prettified # r...
TemplatesPanel
python
EpistasisLab__tpot
tpot/builtin_modules/arithmetictransformer.py
{ "start": 12152, "end": 12798 }
class ____(TransformerMixin, BaseEstimator): def __init__(self): """ A transformer that takes the minimum of all elements in a row. """ pass def fit(self, X, y=None): return self def transform(self, X): transformed_X = np.array(self.transform_helper(np.array...
MinTransformer
python
fluentpython__example-code-2e
24-class-metaprog/metabunch/from3.6/bunch.py
{ "start": 1130, "end": 2381 }
class ____(type): # <1> def __new__(meta_cls, cls_name, bases, cls_dict): # <2> defaults = {} # <3> def __init__(self, **kwargs): # <4> for name, default in defaults.items(): # <5> setattr(self, name, kwargs.pop(name, default)) if kwargs: # <6> ...
MetaBunch
python
ray-project__ray
python/ray/dashboard/subprocesses/module.py
{ "start": 1393, "end": 9187 }
class ____(abc.ABC): """ A Dashboard Head Module that runs in a subprocess as a standalone aiohttp server. """ def __init__( self, config: SubprocessModuleConfig, ): """ Initialize current module when DashboardHead loading modules. :param dashboard_head: The ...
SubprocessModule
python
allegroai__clearml
clearml/backend_api/services/v2_23/frames.py
{ "start": 31063, "end": 33957 }
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. ...
DvAugmentationSet
python
sqlalchemy__sqlalchemy
test/orm/test_query.py
{ "start": 171045, "end": 182186 }
class ____(_fixtures.FixtureTest): run_setup_mappers = "each" run_inserts = "each" __sparse_driver_backend__ = True def _eagerload_mappings(self, addresses_lazy=True, user_lazy=True): User, Address = self.classes("User", "Address") users, addresses = self.tables("users", "addresses") ...
YieldTest
python
pytorch__pytorch
torch/ao/nn/intrinsic/modules/fused.py
{ "start": 7405, "end": 8005 }
class ____(_FusedModule): r"""This is a sequential container which calls the BatchNorm 3d and ReLU modules. During quantization this will be replaced with the corresponding fused module.""" def __init__(self, batch_norm, relu): assert ( type_before_parametrizations(batch_norm) == BatchN...
BNReLU3d
python
allegroai__clearml
clearml/backend_api/services/v2_23/events.py
{ "start": 102863, "end": 106356 }
class ____(Response): """ Response of events.get_scalar_metric_data endpoint. :param events: task scalar metric events :type events: Sequence[dict] :param returned: amount of events returned :type returned: int :param total: amount of events in task :type total: int :param scroll_id...
GetScalarMetricDataResponse
python
dagster-io__dagster
python_modules/libraries/dagster-gcp/dagster_gcp/pipes/context_injectors.py
{ "start": 392, "end": 1906 }
class ____(PipesContextInjector): """A context injector that injects context by writing to a temporary GCS location. Args: bucket (str): The GCS bucket to write to. client (google.cloud.storage.Client): A Google Cloud SDK client to use to write to GCS. key_prefix (Optional[str]): An opt...
PipesGCSContextInjector
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/needs_text_relocation/package.py
{ "start": 216, "end": 860 }
class ____(Package): """A dumy package that encodes its prefix.""" homepage = "https://www.cmake.org" url = "https://cmake.org/files/v3.4/cmake-3.4.3.tar.gz" version("0.0.0", md5="12345678qwertyuiasdfghjkzxcvbnm0") def install(self, spec, prefix): mkdirp(prefix.bin) exe = join_pa...
NeedsTextRelocation
python
apache__airflow
providers/google/tests/unit/google/cloud/triggers/test_gcs.py
{ "start": 2242, "end": 6143 }
class ____: def test_gcs_blob_trigger_serialization(self, trigger): """ Asserts that the GCSBlobTrigger correctly serializes its arguments and classpath. """ classpath, kwargs = trigger.serialize() assert classpath == "airflow.providers.google.cloud.triggers.gcs.GCSB...
TestGCSBlobTrigger
python
spack__spack
var/spack/test_repos/spack_repo/builtin_mock/packages/pkg_c/package.py
{ "start": 217, "end": 686 }
class ____(Package): """Simple package with no dependencies""" homepage = "http://www.example.com" url = "http://www.example.com/c-1.0.tar.gz" # Needed to test CDash reporting phases = ["configure", "build", "install"] version("1.0", md5="0123456789abcdef0123456789abcdef") def configure(...
PkgC
python
kamyu104__LeetCode-Solutions
Python/design-excel-sum-formula.py
{ "start": 113, "end": 2432 }
class ____(object): def __init__(self, H, W): """ :type H: int :type W: str """ self.__exl = [[0 for _ in xrange(ord(W)-ord('A')+1)] \ for _ in xrange(H+1)] self.__fward = collections.defaultdict(lambda : collections.defaultdict(int)) se...
Excel