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
gevent__gevent
src/gevent/tests/test__socket.py
{ "start": 22637, "end": 23490 }
class ____(greentest.TestCase): def test_shutdown_when_closed(self): # https://github.com/gevent/gevent/issues/1089 # we once raised an AttributeError. s = socket.socket() s.close() with self.assertRaises(socket.error): s.shutdown(socket.SHUT_RDWR) def test_...
TestSocket
python
getsentry__sentry
tests/apidocs/endpoints/projects/test_tag_values.py
{ "start": 136, "end": 786 }
class ____(APIDocsTestCase): def setUp(self) -> None: key, value = "foo", "bar" self.create_event("a", tags={key: value}) self.url = reverse( "sentry-api-0-project-tagkey-values", kwargs={ "organization_id_or_slug": self.organization.slug, ...
ProjectTagValuesDocs
python
google__jax
jax/_src/profiler.py
{ "start": 11127, "end": 15315 }
class ____(TraceAnnotation): """Context manager that generates a step trace event in the profiler. The step trace event spans the duration of the code enclosed by the context. The profiler will provide the performance analysis for each step trace event. For example, it can be used to mark training steps and e...
StepTraceAnnotation
python
django__django
django/contrib/gis/db/models/functions.py
{ "start": 14001, "end": 14654 }
class ____(GeoFuncMixin, Transform): output_field = CharField() lookup_name = "geom_type" def as_oracle(self, compiler, connection, **extra_context): lhs, params = compiler.compile(self.lhs) sql = ( "(SELECT DECODE(" f"SDO_GEOMETRY.GET_GTYPE({lhs})," "1, ...
GeometryType
python
huggingface__transformers
tests/models/whisper/test_modeling_whisper.py
{ "start": 242559, "end": 250008 }
class ____: def __init__( self, parent, batch_size=3, # need batch_size != num_hidden layers is_training=True, use_labels=False, vocab_size=200, hidden_size=16, num_hidden_layers=2, num_attention_heads=4, input_channels=1, hidd...
WhisperStandaloneDecoderModelTester
python
joke2k__faker
faker/providers/color/fr_FR/__init__.py
{ "start": 98, "end": 5998 }
class ____(ColorProvider): """Implement color provider for ``fr_FR`` locale.""" all_colors = OrderedDict( ( ("Noir", "#000000"), ("Gris mat", "#696969"), ("Gris", "#808080"), ("Gris foncé (Acier)", "#A9A9A9"), ("Gris argent", "#C0C0C0"), ...
Provider
python
astropy__astropy
astropy/modeling/tests/test_input.py
{ "start": 16303, "end": 23065 }
class ____: """ A suite of tests to check various cases of parameter and input combinations on models with n_input = n_output = 1 on a toy model with n_models=2. Many of these tests mirror test cases in ``astropy.modeling.tests.test_parameters.TestParameterInitialization``, except that this tes...
TestSingleInputSingleOutputTwoModel
python
ApeWorX__ape
src/ape/managers/base.py
{ "start": 103, "end": 552 }
class ____(ManagerAccessMixin): """ Base manager that allows us to add other IPython integration features """ @raises_not_implemented def _repr_mimebundle_(self, include=None, exclude=None): # This works better than AttributeError for Ape. pass @raises_not_implemented def _...
BaseManager
python
dagster-io__dagster
python_modules/dagster/dagster/_core/loader.py
{ "start": 5389, "end": 5872 }
class ____(LoadingContext): """Loading context intended to be used in unit tests that would not otherwise construct a LoadingContext.""" def __init__(self, instance: "DagsterInstance"): self._instance = instance self._loaders = {} @property def instance(self) -> "DagsterInstance": ...
LoadingContextForTest
python
kamyu104__LeetCode-Solutions
Python/closest-dessert-cost.py
{ "start": 1073, "end": 2096 }
class ____(object): def closestCost(self, baseCosts, toppingCosts, target): """ :type baseCosts: List[int] :type toppingCosts: List[int] :type target: int :rtype: int """ max_count = 2 def backtracking(toppingCosts, i, cost, target, lookup, result): ...
Solution2
python
pytorch__pytorch
torch/utils/mkldnn.py
{ "start": 3696, "end": 4403 }
class ____(_MkldnnConvNd): def __init__(self, dense_module, dtype) -> None: super().__init__(dense_module) self.register_buffer('weight', torch._C._nn.mkldnn_reorder_conv3d_weight( dense_module.weight.to_mkldnn(dtype), self.padding, self.stride, self....
MkldnnConv3d
python
Netflix__metaflow
metaflow/plugins/cards/card_modules/components.py
{ "start": 35602, "end": 44615 }
class ____(UserComponent): """ An events timeline component for displaying structured log messages in real-time. This component displays events in a timeline format with the latest events at the top. Each event can contain structured data including other UserComponents for rich display. Example: B...
EventsTimeline
python
tornadoweb__tornado
tornado/platform/asyncio.py
{ "start": 1382, "end": 2397 }
class ____(Protocol): def fileno(self) -> int: pass _FileDescriptorLike = Union[int, _HasFileno] _T = TypeVar("_T") if typing.TYPE_CHECKING: _Ts = TypeVarTuple("_Ts") # Collection of selector thread event loops to shut down on exit. _selector_loops: Set["SelectorThread"] = set() def _atexit_callb...
_HasFileno
python
apache__airflow
airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_xcom.py
{ "start": 18650, "end": 20694 }
class ____(TestXComEndpoint): @pytest.mark.parametrize( ("query_params", "expected_xcom_ids"), [ ( {"limit": "1"}, ["TEST_XCOM_KEY0"], ), ( {"limit": "2"}, ["TEST_XCOM_KEY0", "TEST_XCOM_KEY1"], ...
TestPaginationGetXComEntries
python
qdrant__qdrant-client
qdrant_client/http/models/models.py
{ "start": 83733, "end": 83852 }
class ____(BaseModel): type: Literal[ "in_memory", ] = Field(..., description="")
PayloadStorageTypeOneOf
python
numpy__numpy
numpy/typing/tests/test_runtime.py
{ "start": 288, "end": 2746 }
class ____(NamedTuple): typ: type args: tuple[type, ...] origin: type | None def _flatten_type_alias(t: Any) -> Any: # "flattens" a TypeAliasType to its underlying type alias return getattr(t, "__value__", t) NDArrayTup = TypeTup(npt.NDArray, npt.NDArray.__args__, np.ndarray) TYPES = { "Arr...
TypeTup
python
getsentry__sentry
src/sentry/incidents/models/alert_rule.py
{ "start": 1562, "end": 1667 }
class ____(Enum): PENDING = 0 SNAPSHOT = 4 DISABLED = 5 NOT_ENOUGH_DATA = 6
AlertRuleStatus
python
huggingface__transformers
src/transformers/models/segformer/modeling_segformer.py
{ "start": 21650, "end": 22074 }
class ____(nn.Module): """ Linear Embedding. """ def __init__(self, config: SegformerConfig, input_dim): super().__init__() self.proj = nn.Linear(input_dim, config.decoder_hidden_size) def forward(self, hidden_states: torch.Tensor): hidden_states = hidden_states.flatten(2)....
SegformerMLP
python
openai__openai-python
src/openai/types/beta/realtime/conversation_item.py
{ "start": 291, "end": 2327 }
class ____(BaseModel): id: Optional[str] = None """ The unique ID of the item, this can be generated by the client to help manage server-side context, but is not required because the server will generate one if not provided. """ arguments: Optional[str] = None """The arguments of the fu...
ConversationItem
python
tornadoweb__tornado
tornado/test/template_test.py
{ "start": 6621, "end": 10075 }
class ____(unittest.TestCase): def test_error_line_number_expression(self): loader = DictLoader( { "test.html": """one two{{1/0}} three """ } ) try: loader.load("test.html").generate() self.fail("did not get expected exc...
StackTraceTest
python
spack__spack
lib/spack/spack/installer.py
{ "start": 5382, "end": 25621 }
class ____: """ This class is used in distributed builds to inform the user that other packages are being installed by another process. """ def __init__(self, enabled: bool): self.enabled: bool = enabled self.pkg_set: Set[str] = set() self.pkg_list: List[str] = [] def a...
TermStatusLine
python
cython__cython
docs/examples/tutorial/cdef_classes/math_function_2.py
{ "start": 15, "end": 109 }
class ____: @cython.ccall def evaluate(self, x: float) -> float: return 0
Function
python
apache__airflow
task-sdk/tests/task_sdk/execution_time/test_context.py
{ "start": 9983, "end": 11504 }
class ____: def test_getattr_variable(self, mock_supervisor_comms): """ Test that the variable is fetched when accessed via __getattr__. """ accessor = VariableAccessor(deserialize_json=False) # Variable from the supervisor / API Server var_result = VariableResult(ke...
TestVariableAccessor
python
openai__openai-python
src/openai/types/beta/assistant_stream_event.py
{ "start": 1552, "end": 1768 }
class ____(BaseModel): data: Run """ Represents an execution run on a [thread](https://platform.openai.com/docs/api-reference/threads). """ event: Literal["thread.run.created"]
ThreadRunCreated
python
celery__celery
t/unit/tasks/test_tasks.py
{ "start": 60265, "end": 63283 }
class ____(TasksCase): def common_send_task_arguments(self): return (ANY, ANY, ANY), dict( compression=ANY, delivery_mode=ANY, exchange=ANY, expires=ANY, immediate=ANY, link=ANY, link_error=ANY, mandatory=ANY, ...
test_apply_async
python
pytorch__pytorch
test/fx/test_lazy_graph_module.py
{ "start": 463, "end": 8672 }
class ____(TestCase): exit_stack = None @classmethod def setUpClass(cls): cls.exit_stack = contextlib.ExitStack() cls.exit_stack.enter_context(_use_lazy_graph_module(True)) @classmethod def tearDownClass(cls): cls.exit_stack.close() @staticmethod def replace_sin_wi...
TestLazyGraphModule
python
matplotlib__matplotlib
lib/matplotlib/widgets.py
{ "start": 5191, "end": 8756 }
class ____(AxesWidget): """ A GUI neutral button. For the button to remain responsive you must keep a reference to it. Call `.on_clicked` to connect to the button. Attributes ---------- ax The `~.axes.Axes` the button renders into. label A `.Text` instance. color ...
Button
python
apache__airflow
providers/google/src/airflow/providers/google/cloud/transfers/bigquery_to_sql.py
{ "start": 1435, "end": 9814 }
class ____(BaseOperator): """ Fetch data from a BigQuery table (alternatively fetch selected columns) and insert it into an SQL table. This is a BaseOperator; an abstract class. Refer to children classes which are related to specific SQL databases (MySQL, MsSQL, Postgres...). .. note:: If ...
BigQueryToSqlBaseOperator
python
pytorch__pytorch
torch/testing/_internal/common_quantization.py
{ "start": 82014, "end": 82467 }
class ____(nn.Module): def __init__(self) -> None: super().__init__() self.linear1 = FunctionalLinear() self.relu = nn.ReLU() self.linear2 = FunctionalLinear() def forward(self, x): x = self.linear1(x) x = self.relu(x) x = self.linear2(x) return x...
FunctionalLinearReluLinearModel
python
chroma-core__chroma
chromadb/utils/embedding_functions/chroma_cloud_splade_embedding_function.py
{ "start": 383, "end": 481 }
class ____(Enum): SPLADE_PP_EN_V1 = "prithivida/Splade_PP_en_v1"
ChromaCloudSpladeEmbeddingModel
python
pypa__pipenv
pipenv/vendor/plette/models/scripts.py
{ "start": 75, "end": 2318 }
class ____(DataModel): """Parse a script line (in Pipfile's [scripts] section). This always works in POSIX mode, even on Windows. """ __OPTIONAL__ = { "script": (str, list, dict) } def __init__(self, data): self.validate(data) if isinstance(data, str): data ...
Script
python
pypa__setuptools
setuptools/_vendor/more_itertools/more.py
{ "start": 84830, "end": 88959 }
class ____: """Wrap an iterator to allow for seeking backward and forward. This progressively caches the items in the source iterable so they can be re-visited. Call :meth:`seek` with an index to seek to that position in the source iterable. To "reset" an iterator, seek to ``0``: >>> ...
seekable
python
tensorflow__tensorflow
tensorflow/python/framework/ops_test.py
{ "start": 129962, "end": 131904 }
class ____(test_util.TensorFlowTestCase): def testStripAndPrependScope(self): strs = [ "hidden1/hidden1/weights", # Same prefix. Should strip. "hidden1///hidden1/weights", # Extra "/". Should strip. "^hidden1/hidden1/weights", # Same prefix. Should strip. "loc:@hidden1/hidden1/...
NameScopeTest
python
huggingface__transformers
src/transformers/models/bamba/modeling_bamba.py
{ "start": 47605, "end": 52064 }
class ____(GradientCheckpointingLayer): def __init__(self, config: BambaConfig, layer_idx: int, layer_type: str = "mamba"): super().__init__() num_experts = 1 ffn_layer_class = BambaMLP if num_experts == 1 else None self.feed_forward = ffn_layer_class(config) self.input_laye...
BambaDecoderLayer
python
FactoryBoy__factory_boy
factory/declarations.py
{ "start": 12537, "end": 13737 }
class ____: """Handle a 'factory' arg. Such args can be either a Factory subclass, or a fully qualified import path for that subclass (e.g 'myapp.factories.MyFactory'). """ def __init__(self, factory_or_path): self.factory = None self.module = self.name = '' if isinstance(fa...
_FactoryWrapper
python
scipy__scipy
scipy/spatial/tests/test_kdtree.py
{ "start": 21880, "end": 43358 }
class ____(sparse_distance_matrix_consistency): def setup_method(self): n = 50 m = 4 np.random.seed(1234) data1 = np.random.randn(n, m) data2 = np.random.randn(n, m) self.T1 = self.kdtree_type(data1, leafsize=2) self.T2 = self.kdtree_type(data2, leafsize=2) ...
_Test_sparse_distance_matrix
python
neetcode-gh__leetcode
python/0024-swap-nodes-in-pairs.py
{ "start": 151, "end": 646 }
class ____: def swapPairs(self, head: ListNode) -> ListNode: dummy = ListNode(0, head) prev, curr = dummy, head while curr and curr.next: # save ptrs nxtPair = curr.next.next second = curr.next # reverse this pair second.next = cu...
Solution
python
pytorch__pytorch
torch/_dynamo/variables/dicts.py
{ "start": 55014, "end": 56935 }
class ____(SetVariable): def debug_repr(self) -> str: if not self.items: return "frozenset()" else: return "{" + ",".join(k.vt.debug_repr() for k in self.items) + "}" @property def set_items(self) -> set["ConstDictVariable._HashableTracker"]: return self.item...
FrozensetVariable
python
skorch-dev__skorch
examples/word_language_model/data.py
{ "start": 98, "end": 454 }
class ____: def __init__(self): self.word2idx = {} self.idx2word = [] def add_word(self, word): if word not in self.word2idx: self.idx2word.append(word) self.word2idx[word] = len(self.idx2word) - 1 return self.word2idx[word] def __len__(self): ...
Dictionary
python
django__django
tests/auth_tests/test_views.py
{ "start": 43526, "end": 47271 }
class ____(AuthViewsTestCase): dont_redirect_url = "/login/redirect_authenticated_user_default/" do_redirect_url = "/login/redirect_authenticated_user/" def test_default(self): """Stay on the login page by default.""" self.login() response = self.client.get(self.dont_redirect_url) ...
LoginRedirectAuthenticatedUser
python
airbytehq__airbyte
airbyte-integrations/connectors/source-github/source_github/github_schema.py
{ "start": 19366, "end": 20117 }
class ____(sgqlc.types.Enum): """The possible values for the enterprise members can create repositories setting. Enumeration Choices: * `ALL`: Members will be able to create public and private repositories. * `DISABLED`: Members will not be able to create public or private repositories...
EnterpriseMembersCanCreateRepositoriesSettingValue
python
pennersr__django-allauth
tests/apps/socialaccount/providers/okta/tests.py
{ "start": 236, "end": 1021 }
class ____(OAuth2TestsMixin, TestCase): provider_id = OktaProvider.id def get_mocked_response(self): return MockedResponse( HTTPStatus.OK, """ { "sub": "00u33ow83pjQpCQJr1j8", "name": "Jon Smith", "locale": "AE", ...
OktaTests
python
pytorch__pytorch
test/jit/test_backends.py
{ "start": 24602, "end": 25527 }
class ____(JitTestCase): """ This class wraps and invokes all subclasses of JitBackendTestCaseWithCompiler so that each one does not have to be individually imported in test_jit.py. """ def __init__(self, name): super().__init__(name) self.basic_module_compiler_test = BasicModuleTes...
TestBackendsWithCompiler
python
pytorch__pytorch
benchmarks/operator_benchmark/pt/matmul_test.py
{ "start": 700, "end": 2639 }
class ____(op_bench.TorchBenchmarkBase): def init(self, M, N, K, trans_a, trans_b, device, dtype=torch.float): # Create tensors without requires_grad first, then set it separately # This avoids creating graph leaves that cannot be deep copied if trans_a: input_one = torch.rand(M,...
MatMulBenchmark
python
django__django
tests/test_utils/test_testcase.py
{ "start": 330, "end": 459 }
class ____: def __getstate__(self): raise pickle.PickleError("cannot be pickled for testing reasons")
UnpicklableObject
python
google__pytype
pytype/abstract/function.py
{ "start": 33995, "end": 34416 }
class ____: """A type mutation.""" instance: _base.BaseValue name: str value: cfg.Variable def __eq__(self, other: "Mutation") -> bool: return ( self.instance == other.instance and self.name == other.name and frozenset(self.value.data) == frozenset(other.value.data) ) def ...
Mutation
python
django__django
tests/admin_changelist/models.py
{ "start": 2289, "end": 2549 }
class ____(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4) origin = models.CharField(max_length=255) load = models.FloatField() speed = models.FloatField() class Meta: ordering = ("speed", "load")
Swallow
python
scrapy__scrapy
scrapy/linkextractors/lxmlhtml.py
{ "start": 1492, "end": 5139 }
class ____: def __init__( self, tag: str | Callable[[str], bool] = "a", attr: str | Callable[[str], bool] = "href", process: Callable[[Any], Any] | None = None, unique: bool = False, strip: bool = True, canonicalized: bool = False, ): # mypy doesn'...
LxmlParserLinkExtractor
python
getsentry__sentry
src/sentry/api/endpoints/source_map_debug_blue_thunder_edition.py
{ "start": 11964, "end": 31427 }
class ____: def __init__(self, abs_path: str, project: Project, release: Release, event): self.abs_path = abs_path self.project = project self.release = release self.event = event self.matching_source_file_names = ReleaseFile.normalize(abs_path) # Source file lookup...
ReleaseLookupData
python
allegroai__clearml
clearml/backend_api/services/v2_20/projects.py
{ "start": 98902, "end": 101609 }
class ____(Response): """ Response of projects.get_model_metadata_keys endpoint. :param keys: A list of model keys :type keys: Sequence[str] :param remaining: Remaining results :type remaining: int :param total: Total number of results :type total: int """ _service = "projects"...
GetModelMetadataKeysResponse
python
pytest-dev__pytest
src/_pytest/doctest.py
{ "start": 4479, "end": 4903 }
class ____(TerminalRepr): def __init__( self, reprlocation_lines: Sequence[tuple[ReprFileLocation, Sequence[str]]] ) -> None: self.reprlocation_lines = reprlocation_lines def toterminal(self, tw: TerminalWriter) -> None: for reprlocation, lines in self.reprlocation_lines: ...
ReprFailDoctest
python
sympy__sympy
sympy/integrals/transforms.py
{ "start": 34358, "end": 36021 }
class ____(FourierTypeTransform): """ Class representing unevaluated Fourier transforms. For usage of this class, see the :class:`IntegralTransform` docstring. For how to compute Fourier transforms, see the :func:`fourier_transform` docstring. """ _name = 'Fourier' def a(self): ...
FourierTransform
python
pyca__cryptography
tests/hazmat/primitives/test_dsa.py
{ "start": 19818, "end": 23390 }
class ____: def test_dsa_signing(self, backend, subtests): vectors = load_vectors_from_file( os.path.join("asymmetric", "DSA", "FIPS_186-3", "SigGen.txt"), load_fips_dsa_sig_vectors, ) for vector in vectors: with subtests.test(): digest_alg...
TestDSASignature
python
redis__redis-py
redis/asyncio/connection.py
{ "start": 48457, "end": 51482 }
class ____(ConnectionPool): """ A blocking connection pool:: >>> from redis.asyncio import Redis, BlockingConnectionPool >>> client = Redis.from_pool(BlockingConnectionPool()) It performs the same function as the default :py:class:`~redis.asyncio.ConnectionPool` implementation, in that...
BlockingConnectionPool
python
pypa__pip
src/pip/_internal/exceptions.py
{ "start": 20733, "end": 21709 }
class ____(ConfigurationError): """When there are errors while loading a configuration file""" def __init__( self, reason: str = "could not be loaded", fname: str | None = None, error: configparser.Error | None = None, ) -> None: super().__init__(error) self....
ConfigurationFileCouldNotBeLoaded
python
facebook__pyre-check
stubs/integration_test/run_cache_test.py
{ "start": 5423, "end": 34368 }
class ____: """ Invariant: Before and after each subtest, the cache file is the same as what is built from calling build_fresh_cache """ typeshed_path: str cache_path: Path expected: List[Dict[str, Any]] save_results_to: Path exit_on_error: bool def temporary_cache_file(self) -...
Test
python
django__django
tests/admin_scripts/tests.py
{ "start": 9677, "end": 13017 }
class ____(AdminScriptTestCase): """ A series of tests for django-admin when using a settings.py file that contains the test application. """ def setUp(self): super().setUp() self.write_settings("settings.py") def test_builtin_command(self): """ default: django-...
DjangoAdminDefaultSettings
python
Netflix__metaflow
metaflow/plugins/pypi/conda_environment.py
{ "start": 866, "end": 23197 }
class ____(MetaflowEnvironment): TYPE = "conda" _filecache = None _force_rebuild = False def __init__(self, flow): super().__init__(flow) self.flow = flow def set_local_root(self, local_root): # TODO: Make life simple by passing echo to the constructor and getting rid of ...
CondaEnvironment
python
run-llama__llama_index
llama-index-integrations/vector_stores/llama-index-vector-stores-solr/llama_index/vector_stores/solr/client/async_.py
{ "start": 705, "end": 10892 }
class ____(_BaseSolrClient): """ A Solr client that wraps :py:class:`aiosolr.Client`. See `aiosolr <https://github.com/youversion/aiosolr>`_ for implementation details. """ async def _build_client(self) -> aiosolr.Client: try: logger.info("Initializing aiosolr client for URL: %...
AsyncSolrClient
python
celery__celery
t/unit/app/test_annotations.py
{ "start": 137, "end": 407 }
class ____: def setup_method(self): @self.app.task(shared=False) def add(x, y): return x + y self.add = add @self.app.task(shared=False) def mul(x, y): return x * y self.mul = mul
AnnotationCase
python
coleifer__peewee
tests/manytomany.py
{ "start": 1158, "end": 1344 }
class ____(TestModel): course = ForeignKeyField(Course, backref='+') student = ForeignKeyField(Student, backref='+') CourseStudentDeferred.set_model(CourseStudent2)
CourseStudent2
python
encode__starlette
starlette/middleware/gzip.py
{ "start": 1028, "end": 4928 }
class ____: content_encoding: str def __init__(self, app: ASGIApp, minimum_size: int) -> None: self.app = app self.minimum_size = minimum_size self.send: Send = unattached_send self.initial_message: Message = {} self.started = False self.content_encoding_set = Fa...
IdentityResponder
python
pytorch__pytorch
test/dynamo/cpython/3_13/test_float.py
{ "start": 45621, "end": 49827 }
class ____(__TestCase): def test_inf_from_str(self): self.assertTrue(isinf(float("inf"))) self.assertTrue(isinf(float("+inf"))) self.assertTrue(isinf(float("-inf"))) self.assertTrue(isinf(float("infinity"))) self.assertTrue(isinf(float("+infinity"))) self.assertTrue(i...
InfNanTest
python
gevent__gevent
src/gevent/tests/test__selectors.py
{ "start": 217, "end": 1604 }
class ____(object): @staticmethod def run_selector_once(sel, timeout=3): # Run in a background greenlet, leaving the main # greenlet free to send data. events = sel.select(timeout=timeout) for key, mask in events: key.data(sel, key.fileobj, mask) gevent.s...
SelectorTestMixin
python
Textualize__textual
src/textual/validation.py
{ "start": 14260, "end": 16217 }
class ____(Validator): """Validate that a string is within a range (inclusive).""" def __init__( self, minimum: int | None = None, maximum: int | None = None, failure_description: str | None = None, ) -> None: super().__init__(failure_description=failure_description)...
Length
python
pandas-dev__pandas
pandas/tests/indexes/ranges/test_setops.py
{ "start": 242, "end": 17505 }
class ____: @pytest.mark.parametrize("dtype", [None, "int64", "uint64"]) def test_intersection_mismatched_dtype(self, dtype): # check that we cast to float, not object index = RangeIndex(start=0, stop=20, step=2, name="foo") index = Index(index, dtype=dtype) flt = index.astype(n...
TestRangeIndexSetOps
python
huggingface__transformers
src/transformers/models/albert/configuration_albert.py
{ "start": 797, "end": 6614 }
class ____(PreTrainedConfig): r""" This is the configuration class to store the configuration of a [`AlbertModel`]. It is used to instantiate an ALBERT model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar config...
AlbertConfig
python
huggingface__transformers
src/transformers/models/maskformer/modeling_maskformer.py
{ "start": 2280, "end": 3695 }
class ____(BaseModelOutputWithCrossAttentions): r""" cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`): Tuple of `torch.FloatTensor` (one for each layer) of shape `(bat...
DetrDecoderOutput
python
getsentry__sentry
src/sentry/integrations/mixins/issues.py
{ "start": 15123, "end": 15189 }
class ____(IntegrationError): pass
IntegrationSyncTargetNotFound
python
weaviate__weaviate-python-client
weaviate/collections/classes/config_vectorizers.py
{ "start": 7882, "end": 8372 }
class ____(_VectorizerConfigCreate): vectorizer: Union[Vectorizers, _EnumLikeStr] = Field( default=Vectorizers.TEXT2VEC_AWS, frozen=True, exclude=True ) model: Optional[str] endpoint: Optional[str] region: str service: str vectorizeClassName: bool @field_validator("region") ...
_Text2VecAWSConfig
python
sanic-org__sanic
tests/test_config.py
{ "start": 629, "end": 892 }
class ____: not_for_config = "should not be used" CONFIG_VALUE = "should be used" @property def ANOTHER_VALUE(self): return self.CONFIG_VALUE @property def another_not_for_config(self): return self.not_for_config
ConfigTest
python
chroma-core__chroma
chromadb/db/impl/sqlite_pool.py
{ "start": 1262, "end": 1849 }
class ____(ABC): """Abstract base class for a pool of connections to a sqlite database.""" @abstractmethod def __init__(self, db_file: str, is_uri: bool) -> None: pass @abstractmethod def connect(self, *args: Any, **kwargs: Any) -> Connection: """Return a connection from the pool."...
Pool
python
pytorch__pytorch
torch/utils/benchmark/utils/timer.py
{ "start": 664, "end": 720 }
class ____(enum.Enum): PYTHON = 0 CPP = 1
Language
python
pypa__virtualenv
src/virtualenv/app_data/base.py
{ "start": 1618, "end": 2083 }
class ____(ABC): @abstractmethod def exists(self): raise NotImplementedError @abstractmethod def read(self): raise NotImplementedError @abstractmethod def write(self, content): raise NotImplementedError @abstractmethod def remove(self): raise NotImpleme...
ContentStore
python
hyperopt__hyperopt
hyperopt/tests/unit/test_rdists.py
{ "start": 4594, "end": 6512 }
class ____(unittest.TestCase): def logp(self, x, low, high, q): return qloguniform_gen(low, high, q).logpmf(x) def test_smallq(self): low, high, q = (0, 1, 0.1) qlu = qloguniform_gen(low, high, q) check_d_samples(qlu, n=10000) def test_bigq(self): low, high, q = (-2...
TestQLogUniform
python
pypa__pip
build-project/build-project.py
{ "start": 229, "end": 1968 }
class ____(venv.EnvBuilder): """A subclass of venv.EnvBuilder that exposes the python executable command.""" def ensure_directories( self, env_dir: Union[str, bytes, "PathLike[str]", "PathLike[bytes]"] ) -> SimpleNamespace: context = super().ensure_directories(env_dir) self.env_exec...
EnvBuilder
python
cython__cython
Demos/benchmarks/bm_pyaes.py
{ "start": 12621, "end": 18058 }
class ____(object): """Cipher Block Chaining (CBC) mode encryption. This mode avoids content leaks. In CBC encryption, each plaintext block is XORed with the ciphertext block preceding it; decryption is simply the inverse. """ # A better explanation of CBC can be found here: # http://en.wikipe...
CBCMode
python
PrefectHQ__prefect
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
{ "start": 689817, "end": 690432 }
class ____(sgqlc.types.Type, Node): """ See source code for more info. """ __schema__ = graphql_schema __field_names__ = ("actor", "assignable", "assignee", "created_at", "user") actor = sgqlc.types.Field(Actor, graphql_name="actor") assignable = sgqlc.types.Field( sgqlc.types.non_n...
AssignedEvent
python
PrefectHQ__prefect
tests/utilities/test_asyncutils.py
{ "start": 10092, "end": 15206 }
class ____: def test_run_coro_as_sync(self): async def foo(): return 42 assert run_coro_as_sync(foo()) == 42 def test_run_coro_as_sync_error(self): async def foo(): raise ValueError("test-42") with pytest.raises(ValueError, match="test-42"): ...
TestRunCoroAsSync
python
ansible__ansible
test/units/module_utils/datatag/test_datatag.py
{ "start": 5065, "end": 5163 }
class ____(AnsibleProfileJSONEncoder): _profile = RoundTripEverything
RoundTripEverythingEncoder
python
rapidsai__cudf
python/cudf_polars/cudf_polars/dsl/expressions/base.py
{ "start": 4047, "end": 4327 }
class ____(Expr): __slots__ = ("error",) _non_child = ("dtype", "error") error: str def __init__(self, dtype: DataType, error: str) -> None: self.dtype = dtype self.error = error self.children = () self.is_pointwise = False
ErrorExpr
python
pypa__pip
src/pip/_vendor/urllib3/contrib/pyopenssl.py
{ "start": 13846, "end": 17081 }
class ____(object): """ I am a wrapper class for the PyOpenSSL ``Context`` object. I am responsible for translating the interface of the standard library ``SSLContext`` object to calls into PyOpenSSL. """ def __init__(self, protocol): self.protocol = _openssl_versions[protocol] ...
PyOpenSSLContext
python
keras-team__keras
keras/src/trainers/data_adapters/torch_data_loader_adapter.py
{ "start": 201, "end": 2835 }
class ____(DataAdapter): """Adapter that handles `torch.utils.data.DataLoader`.""" def __init__(self, dataloader): import torch if not isinstance(dataloader, torch.utils.data.DataLoader): raise ValueError( f"Expected argument `dataloader` to be an instance of" ...
TorchDataLoaderAdapter
python
pytorch__pytorch
test/inductor/test_custom_post_grad_passes.py
{ "start": 2338, "end": 10726 }
class ____(TestCustomPassBase): # mkldnn fusion's pattern_matcher # (torch/_inductor/fx_passes/mkldnn_fusion.py), # and apply it to custom post_grad_passes. def _register_mkldnn_conv_relu_fusion(self, custom_pass_dict): # pattern def _mkldnn_conv_relu_pattern(): return CallF...
TestPostGradCustomPrePostPass
python
doocs__leetcode
solution/0600-0699/0649.Dota2 Senate/Solution.py
{ "start": 0, "end": 517 }
class ____: def predictPartyVictory(self, senate: str) -> str: qr = deque() qd = deque() for i, c in enumerate(senate): if c == "R": qr.append(i) else: qd.append(i) n = len(senate) while qr and qd: if qr[0] <...
Solution
python
walkccc__LeetCode
solutions/3228. Maximum Number of Operations to Move Ones to the End/3228.py
{ "start": 0, "end": 234 }
class ____: def maxOperations(self, s: str) -> int: ans = 0 ones = 0 for i, c in enumerate(s): if c == '1': ones += 1 elif i + 1 == len(s) or s[i + 1] == '1': ans += ones return ans
Solution
python
tensorflow__tensorflow
tensorflow/python/distribute/multi_process_runner_test.py
{ "start": 17740, "end": 20160 }
class ____(test.TestCase): def test_same_process_across_runs(self): cluster_spec = multi_worker_test_base.create_cluster_spec(num_workers=2) runner = multi_process_runner.MultiProcessPoolRunner(cluster_spec) pid = runner.run(fn_that_returns_pid) for _ in range(3): self.assertAllEqual(runner.run...
MultiProcessPoolRunnerTest
python
huggingface__transformers
src/transformers/models/visual_bert/modeling_visual_bert.py
{ "start": 11250, "end": 11985 }
class ____(nn.Module): def __init__(self, config): super().__init__() self.self = VisualBertSelfAttention(config) self.output = VisualBertSelfOutput(config) def forward( self, hidden_states, attention_mask=None, output_attentions=False, ): sel...
VisualBertAttention
python
allegroai__clearml
clearml/backend_api/services/v2_13/tasks.py
{ "start": 247169, "end": 264117 }
class ____(Request): """ Get all the company's tasks and all public tasks :param id: List of IDs to filter by :type id: Sequence[str] :param name: Get only tasks whose name matches this pattern (python regular expression syntax) :type name: str :param user: List of user IDs used to ...
GetAllRequest
python
apache__airflow
providers/dbt/cloud/tests/unit/dbt/cloud/operators/test_dbt.py
{ "start": 34360, "end": 35306 }
class ____: def setup_method(self): self.dag = DAG("test_dbt_cloud_list_jobs_op", schedule=None, start_date=DEFAULT_DATE) self.mock_ti = MagicMock() self.mock_context = {"ti": self.mock_ti} @patch("airflow.providers.dbt.cloud.hooks.dbt.DbtCloudHook.list_jobs") @pytest.mark.parametri...
TestDbtCloudListJobsOperator
python
scipy__scipy
scipy/special/tests/test_basic.py
{ "start": 177340, "end": 178888 }
class ____: def test_softplus(self): # Test cases for the softplus function. Selected based on Eq.(10) of: # Mächler, M. (2012). log1mexp-note.pdf. Rmpfr: R MPFR - Multiple Precision # Floating-Point Reliable. Retrieved from: # https://cran.r-project.org/web/packages/Rmpfr/vignettes/...
TestSoftplus
python
dagster-io__dagster
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/destinations.py
{ "start": 30917, "end": 32523 }
class ____(GeneratedAirbyteDestination): @public def __init__( self, name: str, host: str, port: int, database: str, username: str, password: Optional[str] = None, ssl: Optional[bool] = None, jdbc_url_params: Optional[str] = None, ): ...
MysqlDestination
python
jmcnamara__XlsxWriter
xlsxwriter/exceptions.py
{ "start": 831, "end": 920 }
class ____(XlsxInputError): """Worksheet name already exists."""
DuplicateWorksheetName
python
apache__airflow
providers/github/tests/unit/github/operators/test_github.py
{ "start": 1276, "end": 3997 }
class ____: # TODO: Potential performance issue, converted setup_class to a setup_connections function level fixture @pytest.fixture(autouse=True) def setup_connections(self, create_connection_without_db): create_connection_without_db( Connection( conn_id="github_default"...
TestGithubOperator
python
tensorflow__tensorflow
tensorflow/python/ops/ragged/ragged_split_op_test.py
{ "start": 1305, "end": 17782 }
class ____(test_util.TensorFlowTestCase, parameterized.TestCase): @parameterized.parameters([ #========================================================================= # Uniform splits. #========================================================================= dict( descr='Uniform ...
RaggedSplitOpTest
python
ansible__ansible
test/units/module_utils/facts/test_ansible_collector.py
{ "start": 16960, "end": 17099 }
class ____(collector.BaseFactCollector): def collect(self, module=None, collected_facts=None): return None
NoneReturningCollector
python
RaRe-Technologies__gensim
gensim/test/test_corpora.py
{ "start": 17900, "end": 18253 }
class ____(CorpusTestCase): TEST_CORPUS = [[(1, 1)], [], [(0, 2), (2, 1)], []] def setUp(self): self.corpus_class = ucicorpus.UciCorpus self.file_extension = '.uci' def test_serialize_compressed(self): # UciCorpus needs file write with seek => doesn't support compressed output (onl...
TestUciCorpus
python
pytorch__pytorch
test/higher_order_ops/test_invoke_quant.py
{ "start": 3838, "end": 3914 }
class ____(TestInvokeQuant): backend = "aot_eager"
TestInvokeQuantAotEager
python
facebookresearch__faiss
tests/test_clustering.py
{ "start": 7765, "end": 9705 }
class ____(unittest.TestCase): def evaluate_obj(self, centroids, x): index = faiss.IndexFlatL2(1) index.add(centroids) D, I = index.search(x, k=1) return D.sum() def subtest_cluster1d(self, n, k): rs = np.random.RandomState(123) x = rs.uniform(size=(n, 1)).astyp...
TestClustering1D
python
django__django
tests/forms_tests/tests/test_formsets.py
{ "start": 69651, "end": 72027 }
class ____(SimpleTestCase): def setUp(self): data = { "choices-TOTAL_FORMS": "1", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-MAX_NUM_FORMS": "0", "choices-0-choice": "Calexico", "choices-0-votes": "100", ...
FormsetAsTagTests